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();
}
}
}