grpc(三)之grpc客户端使用连接池
本文使用commons-pool2来实现连接池应用
1、定义一个产生连接池的工厂,需要继承BasePooledObjectFactory,其用处是生产和销毁连接池中保存的对象。根据需求,现在池子里保存的应该是grpc客户端对象。
GrpcClientFactory类:
package com.oy.grpc; import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import com.oy.grpc.client.GrpcClient;
import com.oy.utils.UtilFunctions; public class GrpcClientFactory extends BasePooledObjectFactory<GrpcClient> { @Override
public GrpcClient create() throws Exception {
return new GrpcClient("localhost", );
} @Override
public PooledObject<GrpcClient> wrap(GrpcClient client) {
return new DefaultPooledObject<>(client);
} @Override
public void destroyObject(PooledObject<GrpcClient> p) throws Exception {
UtilFunctions.log.info("==== GrpcClientFactory#destroyObject ====");
p.getObject().shutdown();
super.destroyObject(p);
} }
2、连接池GrpcClientPool类
package com.oy.grpc; import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import com.oy.grpc.client.GrpcClient;
import com.oy.utils.UtilFunctions; public class GrpcClientPool { private static GenericObjectPool<GrpcClient> objectPool = null; static {
GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
// 池中的最大连接数
poolConfig.setMaxTotal(8);
// 最少的空闲连接数
poolConfig.setMinIdle(0);
// 最多的空闲连接数
poolConfig.setMaxIdle(8);
// 当连接池资源耗尽时,调用者最大阻塞的时间,超时时抛出异常 单位:毫秒数
poolConfig.setMaxWaitMillis(-1);
// 连接池存放池化对象方式,true放在空闲队列最前面,false放在空闲队列最后
poolConfig.setLifo(true);
// 连接空闲的最小时间,达到此值后空闲连接可能会被移除,默认即为30分钟
poolConfig.setMinEvictableIdleTimeMillis(1000L * 60L * 30L);// 连接耗尽时是否阻塞,默认为true
poolConfig.setBlockWhenExhausted(true);
objectPool = new GenericObjectPool<>(new GrpcClientFactory(), poolConfig);
} public static GrpcClient borrowObject() {
try {
GrpcClient client = objectPool.borrowObject();
UtilFunctions.log.info("=======total threads created: " + objectPool.getCreatedCount());
return client;
} catch (Exception e) {
UtilFunctions.log.error("objectPool.borrowObject error, msg:{}, exception:{}", e.toString(), e);
}
return createClient();
} public static void returnObject(GrpcClient client) {
try {
objectPool.returnObject(client);
} catch (Exception e) {
UtilFunctions.log.error("objectPool.returnObject error, msg:{}, exception:{}", e.toString(), e);
}
} private static GrpcClient createClient() {
return new GrpcClient("localhost", 23333);
} }
3、客户端程序
这里仅仅简单列出了客户端GrpcClient类的代码,其他代码包括服务端代码见另一篇博客grpc(一)之helloworld。
package com.oy.grpc.client; import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;
import com.oy.grpc.BookServiceGrpc;
import com.oy.grpc.GrpcClientPool;
import com.oy.grpc.GrpcLib.GrpcReply;
import com.oy.grpc.GrpcLib.addBookRequest;
import com.oy.grpc.GrpcLib.getUserByIdRequest;
import com.oy.grpc.UserServiceGrpc;
import com.oy.utils.UtilFunctions;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.StatusRuntimeException; public class GrpcClient {
public static String host = "localhost";
private final ManagedChannel channel;
private final UserServiceGrpc.UserServiceBlockingStub userBlockingStub;
private final BookServiceGrpc.BookServiceBlockingStub bookBlockingStub; public GrpcClient(String host, int port) {
channel = ManagedChannelBuilder.forAddress(host, port).usePlaintext().build();
userBlockingStub = UserServiceGrpc.newBlockingStub(channel);
bookBlockingStub = BookServiceGrpc.newBlockingStub(channel);
} public void shutdown() throws InterruptedException {
channel.shutdown().awaitTermination(, TimeUnit.SECONDS);
} @SuppressWarnings({ "rawtypes" })
public static Object call(String rpcMethoddName, Object... args) throws Exception {
UtilFunctions.log.info("=========== GrpcClient#call begin ===========");
GrpcClient client = null;
try {
client = GrpcClientPool.borrowObject();
// client = new GrpcClient(host, 23333); Class[] argsTypes = new Class[args.length];
for (int i = ; i < args.length; i++) {
UtilFunctions.log.info("args types: {}", args[i].getClass());
argsTypes[i] = args[i].getClass();
}
Method method = client.getClass().getMethod(rpcMethoddName, argsTypes);
Object result = method.invoke(client, args);
UtilFunctions.log.info("=========== GrpcClient#call end ===========");
return result;
} catch (Exception e) {
UtilFunctions.log.error("GrpcClient#call error, msg:{}, exception:{}", e.toString(), e);
return null;
} finally {
if (client != null) {
GrpcClientPool.returnObject(client);
// client.shutdown();
}
}
} // ============= User module =============
public Object getUserById(Integer id) {
UtilFunctions.log.info("=========== GrpcClient#getUserById begin ===========");
getUserByIdRequest request = getUserByIdRequest.newBuilder().setId(id).build();
GrpcReply response;
try {
response = userBlockingStub.getUserById(request);
UtilFunctions.log.info("GrpcClient#getUserById response, code:{}, data:{}", response.getCode(),
response.getData());
} catch (StatusRuntimeException e) {
UtilFunctions.log.error("GrpcClient#addBook error, msg:{}, exception:{}", e.toString(), e);
return null;
}
return response;
} // ============= Book module =============
public Object addBook(Integer id, String name, Double price) {
UtilFunctions.log.info("=========== GrpcClient#addBook begin ===========");
addBookRequest request = addBookRequest.newBuilder().setId(id).setName(name).setPrice(price).build();
GrpcReply response;
try {
response = bookBlockingStub.addBook(request);
UtilFunctions.log.info("GrpcClient#addBook response, code:{}, data:{}", response.getCode(),
response.getData());
UtilFunctions.log.info("=========== GrpcClient#addBook end ===========");
} catch (StatusRuntimeException e) {
UtilFunctions.log.error("GrpcClient#addBook error, msg:{}, exception:{}", e.toString(), e);
return null;
}
return response;
} }
4、客户端测试
package com.oy.grpc.client; import com.oy.grpc.GrpcClientPool;
import com.oy.grpc.GrpcLib.GrpcReply;
import com.oy.utils.UtilFunctions; public class TestService { public static void main(String[] args) throws Exception { for (int i = ; i < ; i++) {
new Thread(new Runnable() { @Override
public void run() {
GrpcReply result = null;
try {
// result = (GrpcReply) GrpcClient.call("getUserById", Integer.valueOf("1"));
// result = (GrpcReply) GrpcClient.call("getUserById", 2);
result = (GrpcReply) GrpcClient.call("addBook", , "thinking in java", 50.0);
} catch (Exception e) {
e.printStackTrace();
}
if (result != null) {
UtilFunctions.log.info("client call interface, get code:{}, data:{}", result.getCode(),
result.getData());
} // 如果注释掉下面两句,则客户端程序结束后,服务端报java.io.IOException: 远程主机强迫关闭了一个现有的连接。
// UtilFunctions.log.info("TestService#main: objectPool is closing...");
// GrpcClientPool.getObjectPool().close();
}
}).start();
}
}
}
运行testService类的main()方法,客户端能正常调用grpc server得到数据,但是grpc服务端报错:
2019-04-11 14:29:30.458 INFO 1192 --- [-worker-ELG-3-1] i.g.n.NettyServerTransport.connections : Transport failed
java.io.IOException: 远程主机强迫关闭了一个现有的连接。
出现这个问题的原因:客户端强制断开连接。参考https://stackoverflow.com/questions/46802521/io-grpc-netty-nettyservertransport-notifyterminated,

我在GrpcClientFactory里面也实现了销毁方法:
@Override
public void destroyObject(PooledObject<GrpcClient> p) throws Exception {
UtilFunctions.log.info("==== GrpcClientFactory#destroyObject ====");
p.getObject().shutdown();
super.destroyObject(p);
}
但是运行testService类的main()方法结束后服务端程序就结束了,程序没有主动调用destroyObject()方法销毁池子中的对象,所以grpcClient也没有shutdown,所以报错。
5、启动客户端springboot项目来测试
package com.oy; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.oy.grpc.client.TestService; @SpringBootApplication
public class Grpc007ClientMainApplication { public static void main(String[] args) throws Exception {
SpringApplication.run(Grpc007ClientMainApplication.class, args);
TestService.main(args);
} }
但是这样当关闭客户端程序,还是出现同样的问题。其实很好理解,因为关闭客户端程序时,池中的对象还处于空闲状态,没有销毁,destroyObject()方法没有调用,所以grpcClient也没有shutdown。
6、解决方法
客户端程序关闭时,池也要close。
package com.oy; import javax.annotation.PreDestroy;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.springframework.stereotype.Controller;
import com.oy.grpc.GrpcClientPool;
import com.oy.grpc.client.GrpcClient;
import com.oy.utils.UtilFunctions; @Controller
public class InitController { @PreDestroy
public void destroy() {
UtilFunctions.log.info("InitController#destroy running..."); GenericObjectPool<GrpcClient> objectPool = GrpcClientPool.getObjectPool();
UtilFunctions.log.info("InitController#destroy, total threads created: " + objectPool.getCreatedCount()); UtilFunctions.log.info("InitController#destroy objectPool is closing...");
objectPool.close();
}
}
grpc(三)之grpc客户端使用连接池的更多相关文章
- 三、redis学习(jedis连接池)
一.jedis连接池 二.jedis连接池+config配置文件 三.jedis连接池+config配置文件+util工具类 util类 public class JedisPoolUtils { / ...
- HttpClient实战三:Spring整合HttpClient连接池
简介 在微服务架构或者REST API项目中,使用Spring管理Bean是很常见的,在项目中HttpClient使用的一种最常见方式就是:使用Spring容器XML配置方式代替Java编码方式进行H ...
- HttpClient 4.3连接池参数配置及源码解读
目前所在公司使用HttpClient 4.3.3版本发送Rest请求,调用接口.最近出现了调用查询接口服务慢的生产问题,在排查整个调用链可能存在的问题时(从客户端发起Http请求->ESB-&g ...
- [转载] 基于zookeeper、连接池、Failover/LoadBalance等改造Thrift 服务化
转载自http://blog.csdn.net/zhu_tianwei/article/details/44115667 http://blog.csdn.net/column/details/sli ...
- 基于zookeeper、连接池、Failover/LoadBalance等改造Thrift 服务化
对于Thrift服务化的改造,主要是客户端,可以从如下几个方面进行: 1.服务端的服务注册,客户端自动发现,无需手工修改配置,这里我们使用zookeeper,但由于zookeeper本身提供的客户端使 ...
- HttpClient4.3 连接池参数配置及源码解读
目前所在公司使用HttpClient 4.3.3版本发送Rest请求,调用接口.最近出现了调用查询接口服务慢的生产问题,在排查整个调用链可能存在的问题时(从客户端发起Http请求->ESB-&g ...
- 转!数据库连接池概念、种类、配置(DBCP\C3P0\JndI与Tomact配置连接池)
数据库连接池概念.种类.配置(DBCP\C3P0\JndI与Tomact配置连接池) 一.DBCP 连接:DBCP 连接池是 Apache 软件基金组织下的一个开源连接池实现. 需要的 java 包c ...
- SQLSERVER连接池内部机制
前言介绍: 当应用程序运行的时候,会有一个连接池的管理控件运行在应用程序的进程里,统一管理应用程序和SQLSERVER建立的所有连接, 并且维护这些连接一直处于活动状态.当有用户发出一个connect ...
- 连接池--sp_reset_connection
--当客户端使用连接池访问数据库时,客户端使用OPEN来重用数据库连接,使用CLOSE来断开数据库连接,但并不物理上新建和断开连接,因此可以提高程序运行速度并降低性能损耗. --ADO和ADO.NET ...
随机推荐
- ES6 Reflect 与 Proxy
概述 Proxy 与 Reflect 是 ES6 为了操作对象引入的 API . Proxy 可以对目标对象的读取.函数调用等操作进行拦截,然后进行操作处理.它不直接操作对象,而是像代理模式,通过对象 ...
- Java学习-050-AES256 之 java.security.InvalidKeyException: Illegal key size or default parameters 解决方法
在进行 Java AES 加密测试时,出现如下错误信息: java.security.InvalidKeyException: Illegal key size or default paramete ...
- npm更新指定的组件
1.例如:react-router已经更新到4.x版本,想要下载2.x版本,可以通过下面命令 npm install --save-dev react-router@2.8.1 或 npm insta ...
- GitHub的操作
一.查看自己的信息:git config --list 修改config文件:01.输入vim ~/.gitconfig(回车) 02.点击 i.o或a 进入编辑模式 03.修改所要修改的信息 04. ...
- sublime设置tab为四个空格
在首选项->设置里: 添加: "tab_size": 4, "translate_tabs_to_spaces": true,
- 【转】jira插件Zephyr的具体使用
在工作中,我们通常是在excel表格中编写测试用例,增删改查功能都不错,但保存.管理.共享都不完美,为了让公司领导或其他同事方便查看测试执行情况和测试进度,我们引入了TestLink工具来编写测试用例 ...
- 基于ROS和beaglebone的串口通信方式,使用键盘控制移动机器人
一.所需工具包 1.ROS键盘包:teleop_twist_keyboard 2.ROS串口通讯包:serial $ cd ~/catkin_ws/src $ git clone https://g ...
- /* * 有五个学生,每个学生有3门课的成绩,从键盘输入以上数据 *(包括学生号,姓名,三门课成绩),计算出平均成绩, *将原有的数据和计算出的平均分数存放在磁盘文件"stud"中。 */
1.Student类:类中有五个变量,分别是学号,姓名,三门成绩 package test3; public class Student { private int num; private Stri ...
- Python3 批量更改文件后缀名
Python3 批量更改文件后缀名 示例: # coding:utf8 import os import sys def Rename(): #Path = "F:\\test\\" ...
- java.lang.IllegalArgumentException: An invalid domain [.test.com] was specified for this cookie解决方法
当项目中使用单点登录功能时,通常会使用cookie进行信息的保存,这样就可以在多个子域名上存取用户信息. 比如有三个domain分别为test.com,cml.test.com,b.test.com这 ...