原文地址: haifeiWu和他朋友们的博客
博客地址:www.hchstudio.cn
欢迎转载,转载请注明作者及出处,谢谢!
服务端开发都会或多或少的涉及到 RPC 的使用,当然如果止步于会用,对自己的成长很是不利,所以楼主今天本着知其然,且知其所以然的精神来探讨一下 RPC 这个东西。
child-rpc模型
child-rpc 采用 socket 直连的方式来实现服务的远程调用,然后使用 jdk 动态代理的方式让调用者感知不到远程调用。
child-rpc 开箱使用
发布服务
RPC 服务类要监听指定IP端口,设置要发布的服务的实现及其接口的引用,并指定序列化的方式,目前 child-rpc 支持 Hessian,JACKSON 两种序列化方式。
/** * @author wuhf * @Date 2018/9/1 18:30 **/ public class ServerTest { public static void main(String[] args) { ServerConfig serverConfig = new ServerConfig(); serverConfig.setSerializer(Serializer.SerializeEnum.HESSIAN.serializer) .setPort(5201) .setInterfaceId(HelloService.class.getName()) .setRef(HelloServiceImpl.class.getName()); ServerProxy serverProxy = new ServerProxy(new NettyServer(),serverConfig); try { serverProxy.export(); while (true){ } } catch (Exception e) { e.printStackTrace(); } } }引用服务
RPC 客户端要链接远程 IP 端口,并注册要引用的服务,然后调用 sayHi 方法,输出结果
/** * @author wuhf * @Date 2018/9/1 18:31 **/ public class ClientTest { public static void main(String[] args) { ClientConfig clientConfig = new ClientConfig(); clientConfig.setHost("127.0.0.1") .setPort(5201) .setTimeoutMillis(100000) .setSerializer(Serializer.SerializeEnum.HESSIAN.serializer); ClientProxy clientProxy = new ClientProxy(clientConfig,new NettyClient(),HelloService.class); for (int i = 0; i < 10; i++) { HelloService helloService = (HelloService) clientProxy.refer(); System.out.println(helloService.sayHi()); } } }运行
server 端输出
client 端输出
child-rpc 具体实现
RPC 请求,响应消息实体定义
定义消息请求响应格式,消息类型、消息唯一 ID 和消息的 json 序列化字符串内容。消息唯一 ID 是用来客户端验证服务器请求和响应是否匹配。
// rpc 请求 public class RpcRequest implements Serializable {
