java netty rpc框架_netty之 -- 手写rpc框架

packagecom.yang.java.main.netty.rpc.netty;importio.netty.bootstrap.Bootstrap;importio.netty.channel.ChannelInitializer;importio.netty.channel.ChannelOption;importio.netty.channel.ChannelPipeline;importio.netty.channel.nio.NioEventLoopGroup;importio.netty.channel.socket.SocketChannel;importio.netty.channel.socket.nio.NioSocketChannel;importio.netty.handler.codec.string.StringDecoder;importio.netty.handler.codec.string.StringEncoder;importjava.lang.reflect.Proxy;importjava.util.concurrent.ExecutorService;importjava.util.concurrent.Executors;/*** Description:

*

*@authormark

* Date 2020/9/16*/

public classNettyClient {//创建线程池

private static ExecutorService executor =Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());private staticNettyClientHandler client;private int count = 0;public Object getBean(final Class>providerClass) {returnProxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),new Class>[]{providerClass}, (proxy, method, args) ->{

System.out.println("(proxy, method, args) come " + (++count) + "time");if (client == null) {

initClient();

}

client.setParas((String) args[0]);return executor.submit(client).get(); //这个其实就是调用call方法

});

}//初始化客户端

private static voidinitClient() {

client= newNettyClientHandler();//创建EventLoopGroup

NioEventLoopGroup group = newNioEventLoopGroup();

Bootstrap bootstrap= newBootstrap();

bootstrap.group(group)

.channel(NioSocketChannel.class)

.option(ChannelOption.TCP_NODELAY,true)

.handler(new ChannelInitializer() {

@Overrideprotected void initChannel(SocketChannel ch) throwsException {

ChannelPipeline pipeline=ch.pipeline();

pipeline.addLast(newStringDecoder());

pipeline.addLast(newStringEncoder());

pipeline.addLast(client);

}

}

);try{

bootstrap.connect("127.0.0.1", 7000).sync();

}catch(Exception e) {

e.printStackTrace();

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值