首页  

基于netty的 简单 rpc 框架     所属分类 netty 浏览量 264
基于netty 
不依赖spring 
序列化采用json
暂未实现注册中心


ServerHandler 注意加上 @Sharable
否则多个客户端连接时会报错
io.netty.channel.ChannelPipelineException: dyyx.simplerpc.ServerHandler is not a @Sharable handler, so can't be added or removed multiple times.

打成 fat jar
mvn package -f pom-jar.xml

java -cp .:simplerpc.jar dyyx.simplerpc.NettyServerMain
java -cp .:simplerpc.jar dyyx.simplerpc.NettyClientMain

java -cp .:simplerpc.jar -Dport=7777 dyyx.simplerpc.NettyServerMain
java -cp .:simplerpc.jar -Dip=127.0.0.1 -Dport=7777  dyyx.simplerpc.NettyClientMain

客户端异步转同步 DefaultFuture


ClientHandler

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof RpcResponse) {
        RpcResponse response = (RpcResponse) msg;
        DefaultFuture defaultFuture = futureMap.get(response.getRequestId());
        defaultFuture.setResponse(response);
    }
    super.channelRead(ctx, msg);
}

public RpcResponse getRpcResponse(String requestId) throws InterruptedException {
    try {
        DefaultFuture future = futureMap.get(requestId);
        return future.getRpcResponse(10);
    } finally {
        futureMap.remove(requestId);
    }
}

NettyClient

public RpcResponse send(final RpcRequest request) throws InterruptedException {
    channel.writeAndFlush(request).await();   
    return clientHandler.getRpcResponse(request.getRequestId());
}





完整代码
https://gitee.com/dyyx/demos/tree/master/simplerpc


maven-assembly-plugin 和 maven-shade-plugin

上一篇     下一篇
Dubbo中的netty使用

中年男人的西游记

dubbo XML Schema 扩展机制

dubbo 几个实用功能

Dubbo路由简介

geohash简介