netty实现简单的rpc通信

公共接口

public interface HelloService {

String hello(String msg);
}
生产者

公共接口的实现

public class HelloServiceImpl implements HelloService {

@Override
public String hello(String msg) {
System.out.println(“收到客户端消息=” + msg);
//根据msg返回不同的结果
if(msg != null){
return “你好客户端,我已经收到你的消息[” + msg + “]”;
}else{
return “你好客户端,我已经收到你的消息了”;
}

}
}

自定义的业务处理器

public class NettyServerHandler extends ChannelInboundHandlerAdapter {

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println(“已接收到客户端发送数据”);
//获取客户端发送的消息 并调用服务
System.out.println(“msg:” + msg);
if(msg.toString().startsWith(“HelloService#hello#”)){
String resMsg = new HelloServiceImpl().hello(msg.toString().substring(msg.toString().lastIndexOf("#") + 1));
System.out.println(“服务端要返回的数据:” + resMsg);
ctx.writeAndFlush(resMsg);
}
}

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
super.exceptionCaught(ctx, cause);
}
}

NettyServer

public static void startServer(String host,int port) throws InterruptedException {
startServer0(host,port);
}

//编写一个方法 完成对nettyServer的初始化并启动
private static void startServer0(String host,int port) throws InterruptedException {
NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
NioEventLoopGroup workerGroup = new NioEventLoopGroup(8);
try{
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup,workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer() {
@Override
protected void initChannel(SocketChannel channel) throws Exception {
ChannelPipeline pipeline = channel.pipeline();
pipeline.addLast(new StringDecoder());
pipeline.addLast(new StringEncoder());
//自己的业务处理器
pipeline.addLast(new NettyServerHandler());
}
});
System.out.println(“服务提供方启动,开始监听”);
ChannelFuture channelFuture = serverBootstrap.bind(host, port).sync();
channelFuture.channel().closeFuture().sync();
}finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}

}

消费端

调用代码

public static void main(String[] args) {
//创建一个消费者
NettyClient custom = new NettyClient();
System.out.println(“消费者启动中~~~”);
HelloService service = (HelloService)custom.getBean(HelloService.class, providerName);
// System.out.println(“代理对象是:” + service);
//通过代理对象调用服务提供者的方法
String result = service.hello(“你好 dubbo”);
System.out.println(“服务器端调用的结果:” + result);
}

自定义处理器

public class NettyClientHandler extends ChannelInboundHandlerAdapter implements Callable {

private ChannelHandlerContext context;
private String result;
private String param; //客户端调用方法时候传入的参数

//与服务器的连接创建后被调用
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
this.context = ctx;

}

//收到服务器的数据后被调用
@Override
public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println(“客户端收到服务端消息,唤醒call方法”);
result = msg.toString();
System.out.println(“result:” +result);
notify();//唤醒等待的线程
}

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
}

//被代理对象调用 发送数据给服务器 并且等待被唤醒
@Override
public synchronized Object call() throws Exception {
context.writeAndFlush(param);
System.out.println(“回调方法发送数据,等待被唤醒”);
wait();
return result;
}

void setParam(String param){
this.param = param;
}
}

NettyClient

//创建线程池
private static ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

private static NettyClientHandler client;

//编写方法使用代理模式 获取一个代理对象
public Object getBean(final Class<?> serivceClass,final String providerName){
System.out.println(“生成代理对象”);
return Proxy.newProxyInstance(
Thread.currentThread().getContextClassLoader(),
new Class<?>[]{serivceClass},
(proxy,method,args) -> {
if(client == null){
System.out.println(“初始化client”);
initClient();
}
//设置参数
client.setParam(providerName + args[0]);
System.out.println(“提交任务执行”);
return executorService.submit(client).get();
});
}

//初始化客户端
private static void initClient() throws InterruptedException {
client = new NettyClientHandler();
NioEventLoopGroup group = new NioEventLoopGroup(8);
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group)
.channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY,true)
.handler(new ChannelInitializer() {
@Override
protected void initChannel(SocketChannel channel) throws Exception {
ChannelPipeline pipeline = channel.pipeline();
pipeline.addLast(new StringEncoder());
pipeline.addLast(new StringDecoder());
pipeline.addLast(client);
}
});

ChannelFuture channelFuture = bootstrap.connect(“127.0.0.1”, 7000).sync();
System.out.println(“消费端端口绑定”);
// channelFuture.channel().closeFuture().sync();
// System.out.println(“消费端监听端口关闭”);

猜你喜欢

转载自blog.csdn.net/qq_43504447/article/details/106422925