实现一个简单的rpc框架——simple-rpc
Posted 有意思的程序员
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了实现一个简单的rpc框架——simple-rpc相关的知识,希望对你有一定的参考价值。
代码链接
https://github.com/yutian1999/simple-rpc
rpc-server rpc服务端 服务的提供者依赖此模块 rpc-client rpc客户端 服务的调用者依赖此模块 rpc-common 公共模块 demo provider-demo 服务提供者示例 consumer-demo 服务调用者示例
技术分析
rpc远程调用的本质是对引用的依赖进行代理底层偷偷进行远程调用。
技术依赖
netty (通信,进行远程调用
cglb (代理,对本地方法调用代理成远程调用)
代码精剪
服务端
rpc服务端
public class NettyServer {
private static final Logger logger = LoggerFactory.getLogger(NettyServer.class);
private Integer port;
public NettyServer(Integer port) {
this.port = port;
}
private Map<String,Object> serviceMap = new HashMap();
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
public void addService(String interfaceName, String version, Object serviceBean) {
logger.info("Adding service, interface: {}, version: {}, bean:{}", interfaceName, version, serviceBean);
String serviceKey = ServiceUtil.makeServiceKey(interfaceName, version);
serviceMap.put(serviceKey, serviceBean);
}
public void start() {
new Thread(new Runnable() {
public void run() {
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workerGroup).channel(NioserverSocketChannel.class)
.childHandler(new RpcServerInitializer(serviceMap));
ChannelFuture future = bootstrap.bind(port).sync();
future.channel().closeFuture().sync();
logger.info("Server started on port {}", port);
} catch (Exception e) {
logger.error("Rpc server remoting server error", e);
} finally {
stop();
}
}
}).start();
}
public void stop() {
try {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
} catch (Exception ex) {
logger.error(ex.getMessage(), ex);
}
}
}
以上是关于实现一个简单的rpc框架——simple-rpc的主要内容,如果未能解决你的问题,请参考以下文章