使用httpclient连接池来实现远程调用

在项目中,如果没有使用成熟的RPC框架又要实现简单的远程调用,那么httpClient是一个不错的选择。然是在使用httpClient的过程中,频繁的创建和销毁socket连接也是一个比较大的开销,将其封装成连接池会比较节约性能,直接上代码。

 

public class HttpConnectionManager {
    PoolingHttpClientConnectionManager cm = null;

    @PostConstruct
    public void init() {
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create()
                .register("http", new PlainConnectionSocketFactory())
                .build();
        cm =new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        cm.setMaxTotal(200);
        cm.setDefaultMaxPerRoute(20);
    }

    public CloseableHttpClient getHttpClient() {
        CloseableHttpClient httpClient = null;
        try {
            httpClient = HttpClients.custom()
                    .setConnectionManager(cm)
                    .build();
        } catch (Exception e) {
            this.init();
        }
        //CloseableHttpClient httpClient2 = HttpClients.createDefault();//如果不采用连接池就是这种方式获取连接
        return httpClient;
    }
}

这是一个连接池初始化以及获取httpclient连接的封装类,此时并没有真正的创建连接,而是创建了一个池化的httpclient管理器,可以设置池中的最大连接数。

 

@Component
@PropertySource(value = { "classpath:sys.properties" })
public class HttpClientFromPool {

    @Autowired
    HttpConnectionManager connManager;

    @Value("${xxx.xxx}")
    String vaseUrl;

    public String get(String path){
        CloseableHttpClient httpClient = connManager.getHttpClient();
        HttpGet httpget = new HttpGet(vaseUrl + path);
        String json = null;
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpget);
            json = EntityUtils.toString(response.getEntity());
        } catch (UnsupportedOperationException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(response!=null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return json;
    }
}

这个方法就是一个真正创建httpclient并调用的过程。从池化管理器中获取client,继而根据请求路径去调用获取请求结果。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值