描述
在企业级的项目中我们通常是由多个子项目组合而成,为了降低子项目之间的耦合性,从而产生了rpc这个东东
当然关于使用rpc除了降低代码的耦合性我认为还有一个比较好的地方就是后端版本发布的问题,各子项目分开,然后使用rpc可单独对某个功能进行升级,避免了因发版而让整个服务不可用(当然动态发布的时候是不需要考虑这个问题的)
技术描述
hprose
本文章使用的是hprose的tcp协议,通过监听端口,然后从接口中根据方法名进行方法的调用
注意:
关于hpross这个框架需要注意的一点就是若是python使用的话不可以使用tcp协议,到文章的书写时间,python版本的hprose暂时不支持
示例代码
添加依赖
<dependency>
<groupId>org.hprose</groupId>
<artifactId>hprose-java</artifactId>
<version>2.0.33</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>31.0.1-jre</version>
</dependency>
服务端
服务端分为以下几个步骤
- 构建service层的代码
- 对外暴露rpc
- service代码
public interface RpcService {
String rpcMethod();
}
@Service
public class RpcServiceImpl implements RpcService {
@Override
public String rpcMethod() {
System.out.println("这是通过rpc调用的服务");
return "rpcv服务返回的内容信息";
}
}
- 对外暴露接口
@Component
@Slf4j
public class RpcTcpServiceImpl {
//这里qingbuyao0使用硬编码的方式进行书写,请使用
private String port = "9091";
private final String threadName = "MyTcpHprose";
@Autowired
private RpcService rpcService;
@PostConstruct
public void init() {
String uri = String.format("tcp://0.0.0.0:%s", port);
log.info("begin init hprose");
HproseTcpServer server = null;
try {
server = new HproseTcpServer(uri);
//设置执行线程池;
ThreadPoolExecutor executor = new ThreadPoolExecutor(
5, 50, 1000, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>(100),
new ThreadFactoryBuilder().setNameFormat(threadName + "-%d").build(),
new ThreadPoolExecutor.CallerRunsPolicy()
);
server.setThreadPool(executor);
server.setThreadPoolEnabled(true);
server.setReactorThreads(20);
//这里将你通过rpc对外暴露的方法,这样方便对外调用
server.add("rpcMethod", rpcService);
server.start();
log.info("finished init hprose tcp server");
} catch (URISyntaxException | IOException e) {
log.warn("failure init hprose tcp server, {}", e.getMessage(), e);
}
}
}
通过以上两步,对服务端的对外暴露就完成啦
请求端
- 构建要请求的服务
- 使用返回内容
- 构建请求的服务
@Service
public class MyRpcService {
// 这个接口就是写你要需要的接口
//todo暂时未测试对同一个服务端的不同服务类;诶是否可以写在同一个接口内
interface RpcService{
String rpcMethod();
}
//具体的调用,若是有参数请在传递参数
public String rpcMethod(){
HproseTcpClient hproseTcpClient = new HproseTcpClient("tcp://localhost:9091/");
RpcService myService = hproseTcpClient.useService(RpcService.class);
return myService.rpcMethod();
}
}
- 使用
@Resource
private MyRpcService rpcService;
@Test
public void testRpc(){
System.out.println(rpcService.rpcMethod());
}
结语
在springboot中也可以使用webselvert来实现,这里就不多做介绍了,使用hprose还有一个好处就是在分布式的时候可以有效的接入到注册中心等,避免请求不到的问题等
有任何问题欢迎大家指出,(小白一枚