RPC完成Registry服务注册

Registry 注册中心主要功能就是负责将所有Provider 的服务名称和服务引用地址注册到一个容器中,并对外发布。Registry 应该要启动一个对外的服务,很显然应该作为服务端,并提供一个对外可以访问的端口。先启动一个Netty服务,创建RpcRegistry 类,具体代码如下:

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
public class RpcRegistry {
	private int port;
	public RpcRegistry(int port){
		this.port = port;
	}
	public void start(){
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		try {
			ServerBootstrap b = new ServerBootstrap();
			b.group(bossGroup, workerGroup)
			.channel(NioServerSocketChannel.class)
			.childHandler(new ChannelInitializer<SocketChannel>() {
				@Override
				protected void initChannel(SocketChannel ch) throws Exception {
				ChannelPipeline pipeline = ch.pipeline();
				//自定义协议解码器
				/** 入参有5 个,分别解释如下
				maxFrameLength:框架的最大长度。如果帧的长度大于此值,则将抛出TooLongFrameException。
				lengthFieldOffset:长度字段的偏移量:即对应的长度字段在整个消息数据中得位置
				lengthFieldLength:长度字段的长度。如:长度字段是int 型表示,那么这个值就是4(long 型就是8)
				lengthAdjustment:要添加到长度字段值的补偿值
				initialBytesToStrip:从解码帧中去除的第一个字节数
				*/
				pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
				//自定义协议编码器
				pipeline.addLast(new LengthFieldPrepender(4));
				//对象参数类型编码器
				pipeline.addLast("encoder",new ObjectEncoder());
				//对象参数类型解码器
				pipeline.addLast("decoder",new ObjectDecoder(Integer.MAX_VALUE,
				ClassResolvers.cacheDisabled(null)));
				pipeline.addLast(new RegistryHandler());
				}
			})
			.option(ChannelOption.SO_BACKLOG, 128)
			.childOption(ChannelOption.SO_KEEPALIVE, true);
			ChannelFuture future = b.bind(port).sync();
			System.out.println("GP RPC Registry start listen at " + port );
			future.channel().closeFuture().sync();
		} catch (Exception e) {
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}
	public static void main(String[] args) throws Exception {
		new RpcRegistry(8080).start();
	}
}

在RegistryHandler 中实现注册的具体逻辑,上面的代码,主要实现服务注册和服务调用的功能。因为所有模块创建在同一个项目中,为了简化,服务端没有采用远程调用,而是直接扫描本地Class,然后利用反射调用。代码实现如下:

import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import com.gupaoedu.vip.netty.rpc.protocol.InvokerProtocol;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
public class RegistryHandler extends ChannelInboundHandlerAdapter {
	//用保存所有可用的服务
	public static ConcurrentHashMap<String, Object> registryMap = new ConcurrentHashMap<String,Object>();
	//保存所有相关的服务类
	private List<String> classNames = new ArrayList<String>();
	public RegistryHandler(){
		//完成递归扫描
		scannerClass("com.gupaoedu.vip.netty.rpc.provider");
		doRegister();
	}
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		Object result = new Object();
		InvokerProtocol request = (InvokerProtocol)msg;
		//当客户端建立连接时,需要从自定义协议中获取信息,拿到具体的服务和实参
		//使用反射调用
		if(registryMap.containsKey(request.getClassName())){
		Object clazz = registryMap.get(request.getClassName());
		Method method = clazz.getClass().getMethod(request.getMethodName(), request.getParames());
		result = method.invoke(clazz, request.getValues());
		}c
		tx.write(result);
		ctx.flush();
		ctx.close();
	}
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		ctx.close();
	}
	/*
	* 递归扫描
	*/
	private void scannerClass(String packageName){
		URL url = this.getClass().getClassLoader().getResource(packageName.replaceAll("\\.", "/"));
		File dir = new File(url.getFile());
		for (File file : dir.listFiles()) {
			//如果是一个文件夹,继续递归
			if(file.isDirectory()){
				scannerClass(packageName + "." + file.getName());
			}else{
				classNames.add(packageName + "." + file.getName().replace(".class", "").trim());
			}
		}
	}
	/**
	* 完成注册
	*/
	private void doRegister(){
		if(classNames.size() == 0){ return; }
		for (String className : classNames) {
			try {
				Class<?> clazz = Class.forName(className);
				Class<?> i = clazz.getInterfaces()[0];
				registryMap.put(i.getName(), clazz.newInstance());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}

至此,注册中心的基本功能就已完成,下面来看客户端的代码实现。

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值