package core.thrift; import core.thrift.comment.QueryComment; import org.apache.commons.pool2.impl.GenericObjectPool; import org.apache.thrift.async.TAsyncClientManager; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TProtocolFactory; import org.apache.thrift.transport.TNonblockingTransport; import org.apache.thrift.transport.TTransport; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import javax.annotation.PostConstruct; @Service public class ThriftClientPool { @Value("${thrift.ip}") private String ip; @Value("${thrift.port}") private int port; @Value("${thrift.timeout}") private int timeout; private static GenericObjectPool pool; @PostConstruct public void init() { pool = new GenericObjectPool<>(new ConnectionPoolFactory(ip, port, timeout)); } public static void doExecute(Thrift thrift) throws Exception { //从池里获取一个Transport对象 TTransport transport = pool.borrowObject(); TAsyncClientManager clientManager = new TAsyncClientManager(); TProtocolFactory protocol = new TBinaryProtocol.Factory(); QueryComment.AsyncClient asyncClient = new QueryComment.AsyncClient(protocol, clientManager, (TNonblockingTransport) transport); thrift.doExecute(asyncClient); //把一个Transport对象归还到池里 pool.returnObject(transport); } public interface Thrift { void doExecute(QueryComment.AsyncClient client) throws Exception; } }