学习别人的rpc框架
https://my.oschina.net/huangyong/blog/361751
https://gitee.com/huangyong/rpc
在此文基础上的另一个实现,解决了原文中一些问题,增加了一些功能
http://www.cnblogs.com/luxiaoxun/p/5272384.html
这一类同时可以参考hadoop的实现,纯异步,相当于更进一步
http://www.cnblogs.com/LBSer/p/4853234.html (๑•̀ㅂ•́)و✧
第一个链接为作者的描述,非常清晰,第二个为代码,包含以下几个功能包
自己的理解和摘取一些我认为值得记录的点
RPC:客户端发起请求,端封装请求,网络连接到某个服务端(服务治理),通过网络协议(tcp/http),序列化请求发送到服务端,服务端收到网络请求,反序列化请求本地服务,再将返回序列化,发送到客户端,客户端反序列化给本地展示结果。
http应用层协议,tcp为传输层协议,越上层的协议可能提供了越丰富的特性,越底层数据传输越快。
JAVA本身的序列化方式不管是性能还是序列化后的字节大小都不太好,所以需要根据实际情况集成其他序列化方式
服务被部署在不同的服务器节点上,需要服务发现提供注册和客户端发现功能
如何实现?通过启动类加载xml文件,启动相关组件
public static void main(String[] args) {
new ClassPathXmlApplicationContext("spring.xml");
}
<!-- lang: xml -->
<beans ...>
<context:component-scan base-package="com.xxx.rpc.sample.server"/> <context:property-placeholder location="classpath:config.properties"/> <!-- 配置服务注册组件 -->
<bean id="serviceRegistry" class="com.xxx.rpc.registry.ServiceRegistry">
<constructor-arg name="registryAddress" value="${registry.address}"/>
</bean> <!-- 配置 RPC 服务器 -->
<bean id="rpcServer" class="com.xxx.rpc.server.RpcServer">
<constructor-arg name="serverAddress" value="${server.address}"/>
<constructor-arg name="serviceRegistry" ref="serviceRegistry"/>
</bean>
</beans>
服务注解标签
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Component // 表明可被 Spring 扫描
public @interface RpcService { Class<?> value();
}
具体的服务实现类
@RpcService(HelloService.class) // 指定远程接口
public class HelloServiceImpl implements HelloService { @Override
public String hello(String name) {
return "Hello! " + name;
}
}
服务发现相关就是利用了zookeeper的znode/watcher
String ZK_REGISTRY_PATH = "/registry";
String ZK_DATA_PATH = ZK_REGISTRY_PATH + "/data";
public class ServiceRegistry { private static final Logger LOGGER = LoggerFactory.getLogger(ServiceRegistry.class); private CountDownLatch latch = new CountDownLatch(1); private String registryAddress; public ServiceRegistry(String registryAddress) {
this.registryAddress = registryAddress;
} public void register(String data) {
if (data != null) {
ZooKeeper zk = connectServer();
if (zk != null) {
createNode(zk, data);
}
}
} private ZooKeeper connectServer() {
ZooKeeper zk = null;
try {
zk = new ZooKeeper(registryAddress, Constant.ZK_SESSION_TIMEOUT, new Watcher() {
@Override
public void process(WatchedEvent event) {
if (event.getState() == Event.KeeperState.SyncConnected) {
latch.countDown();
}
}
});
latch.await();
} catch (IOException | InterruptedException e) {
LOGGER.error("", e);
}
return zk;
} private void createNode(ZooKeeper zk, String data) {
try {
byte[] bytes = data.getBytes();
String path = zk.create(Constant.ZK_DATA_PATH, bytes, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
LOGGER.debug("create zookeeper node ({} => {})", path, data);
} catch (KeeperException | InterruptedException e) {
LOGGER.error("", e);
}
}
}
下面是NIO rpc的实现 implements ApplicationContextAware, InitializingBean
setApplicationContext处理类处理了注解指出的服务类
afterPropertiesSet 开启了服务并向注册中心注册
public class RpcServer implements ApplicationContextAware, InitializingBean { private static final Logger LOGGER = LoggerFactory.getLogger(RpcServer.class); private String serverAddress;
private ServiceRegistry serviceRegistry; private Map<String, Object> handlerMap = new HashMap<>(); // 存放接口名与服务对象之间的映射关系 public RpcServer(String serverAddress) {
this.serverAddress = serverAddress;
} public RpcServer(String serverAddress, ServiceRegistry serviceRegistry) {
this.serverAddress = serverAddress;
this.serviceRegistry = serviceRegistry;
} @Override
public void setApplicationContext(ApplicationContext ctx) throws BeansException {
Map<String, Object> serviceBeanMap = ctx.getBeansWithAnnotation(RpcService.class); // 获取所有带有 RpcService 注解的 Spring Bean
if (MapUtils.isNotEmpty(serviceBeanMap)) {
for (Object serviceBean : serviceBeanMap.values()) {
String interfaceName = serviceBean.getClass().getAnnotation(RpcService.class).value().getName();
handlerMap.put(interfaceName, serviceBean);
}
}
} @Override
public void afterPropertiesSet() throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel channel) throws Exception {
channel.pipeline()
.addLast(new RpcDecoder(RpcRequest.class)) // 将 RPC 请求进行解码(为了处理请求)
.addLast(new RpcEncoder(RpcResponse.class)) // 将 RPC 响应进行编码(为了返回响应)
.addLast(new RpcHandler(handlerMap)); // 处理 RPC 请求
}
})
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true); String[] array = serverAddress.split(":");
String host = array[0];
int port = Integer.parseInt(array[1]); ChannelFuture future = bootstrap.bind(host, port).sync();
LOGGER.debug("server started on port {}", port); if (serviceRegistry != null) {
serviceRegistry.register(serverAddress); // 注册服务地址
} future.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
}
public class RpcEncoder extends MessageToByteEncoder { private Class<?> genericClass; public RpcEncoder(Class<?> genericClass) {
this.genericClass = genericClass;
} @Override
public void encode(ChannelHandlerContext ctx, Object in, ByteBuf out) throws Exception {
if (genericClass.isInstance(in)) {
byte[] data = SerializationUtil.serialize(in);
out.writeInt(data.length);
out.writeBytes(data);
}
}
}
请求
public class RpcRequest { private String requestId;
private String className;
private String methodName;
private Class<?>[] parameterTypes;
private Object[] parameters; // getter/setter...
}
响应
public class RpcResponse { private String requestId;
private Throwable error;
private Object result; // getter/setter...
}
这里将序列化和反序列化方法集中在序列化工具中,可以自由替换成其他
public class SerializationUtil { private static Map<Class<?>, Schema<?>> cachedSchema = new ConcurrentHashMap<>(); private static Objenesis objenesis = new ObjenesisStd(true); private SerializationUtil() {
} @SuppressWarnings("unchecked")
private static <T> Schema<T> getSchema(Class<T> cls) {
Schema<T> schema = (Schema<T>) cachedSchema.get(cls);
if (schema == null) {
schema = RuntimeSchema.createFrom(cls);
if (schema != null) {
cachedSchema.put(cls, schema);
}
}
return schema;
} @SuppressWarnings("unchecked")
public static <T> byte[] serialize(T obj) {
Class<T> cls = (Class<T>) obj.getClass();
LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
try {
Schema<T> schema = getSchema(cls);
return ProtostuffIOUtil.toByteArray(obj, schema, buffer);
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
} finally {
buffer.clear();
}
} public static <T> T deserialize(byte[] data, Class<T> cls) {
try {
T message = (T) objenesis.newInstance(cls);
Schema<T> schema = getSchema(cls);
ProtostuffIOUtil.mergeFrom(data, message, schema);
return message;
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
}
请求处理类handler,为了避免使用 Java 反射带来的性能问题,我们可以使用 CGLib 提供的反射 API,如下面用到的FastClass
与FastMethod
。
意思都一样,就是根据请求拿出请求相关信息,然后反射调用拿到结果构造返回
这里hadoop用的动态代理,跟这篇文章描述的这样 http://www.cnblogs.com/LBSer/p/4853234.html
public class RpcHandler extends SimpleChannelInboundHandler<RpcRequest> { private static final Logger LOGGER = LoggerFactory.getLogger(RpcHandler.class); private final Map<String, Object> handlerMap; public RpcHandler(Map<String, Object> handlerMap) {
this.handlerMap = handlerMap;
} @Override
public void channelRead0(final ChannelHandlerContext ctx, RpcRequest request) throws Exception {
RpcResponse response = new RpcResponse();
response.setRequestId(request.getRequestId());
try {
Object result = handle(request);
response.setResult(result);
} catch (Throwable t) {
response.setError(t);
}
ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
} private Object handle(RpcRequest request) throws Throwable {
String className = request.getClassName();
Object serviceBean = handlerMap.get(className); Class<?> serviceClass = serviceBean.getClass();
String methodName = request.getMethodName();
Class<?>[] parameterTypes = request.getParameterTypes();
Object[] parameters = request.getParameters(); /*Method method = serviceClass.getMethod(methodName, parameterTypes);
method.setAccessible(true);
return method.invoke(serviceBean, parameters);*/ FastClass serviceFastClass = FastClass.create(serviceClass);
FastMethod serviceFastMethod = serviceFastClass.getMethod(methodName, parameterTypes);
return serviceFastMethod.invoke(serviceBean, parameters);
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
LOGGER.error("server caught exception", cause);
ctx.close();
}
}
客户端配置
<!-- lang: java -->
<beans ...>
<context:property-placeholder location="classpath:config.properties"/> <!-- 配置服务发现组件 -->
<bean id="serviceDiscovery" class="com.xxx.rpc.registry.ServiceDiscovery">
<constructor-arg name="registryAddress" value="${registry.address}"/>
</bean> <!-- 配置 RPC 代理 -->
<bean id="rpcProxy" class="com.xxx.rpc.client.RpcProxy">
<constructor-arg name="serviceDiscovery" ref="serviceDiscovery"/>
</bean>
</beans>
服务发现
public class ServiceDiscovery { private static final Logger LOGGER = LoggerFactory.getLogger(ServiceDiscovery.class); private CountDownLatch latch = new CountDownLatch(1); private volatile List<String> dataList = new ArrayList<>(); private String registryAddress; public ServiceDiscovery(String registryAddress) {
this.registryAddress = registryAddress; ZooKeeper zk = connectServer();
if (zk != null) {
watchNode(zk);
}
} public String discover() {
String data = null;
int size = dataList.size();
if (size > 0) {
if (size == 1) {
data = dataList.get(0);
LOGGER.debug("using only data: {}", data);
} else {
data = dataList.get(ThreadLocalRandom.current().nextInt(size));
LOGGER.debug("using random data: {}", data);
}
}
return data;
} private ZooKeeper connectServer() {
ZooKeeper zk = null;
try {
zk = new ZooKeeper(registryAddress, Constant.ZK_SESSION_TIMEOUT, new Watcher() {
@Override
public void process(WatchedEvent event) {
if (event.getState() == Event.KeeperState.SyncConnected) {
latch.countDown();
}
}
});
latch.await();
} catch (IOException | InterruptedException e) {
LOGGER.error("", e);
}
return zk;
} private void watchNode(final ZooKeeper zk) {
try {
List<String> nodeList = zk.getChildren(Constant.ZK_REGISTRY_PATH, new Watcher() {
@Override
public void process(WatchedEvent event) {
if (event.getType() == Event.EventType.NodeChildrenChanged) {
watchNode(zk);
}
}
});
List<String> dataList = new ArrayList<>();
for (String node : nodeList) {
byte[] bytes = zk.getData(Constant.ZK_REGISTRY_PATH + "/" + node, false, null);
dataList.add(new String(bytes));
}
LOGGER.debug("node data: {}", dataList);
this.dataList = dataList;
} catch (KeeperException | InterruptedException e) {
LOGGER.error("", e);
}
}
}
代理实现,构建服务请求信息,然后注册的服务里找一个,客户端netty将请求发送到服务端
public class RpcProxy { private String serverAddress;
private ServiceDiscovery serviceDiscovery; public RpcProxy(String serverAddress) {
this.serverAddress = serverAddress;
} public RpcProxy(ServiceDiscovery serviceDiscovery) {
this.serviceDiscovery = serviceDiscovery;
} @SuppressWarnings("unchecked")
public <T> T create(Class<?> interfaceClass) {
return (T) Proxy.newProxyInstance(
interfaceClass.getClassLoader(),
new Class<?>[]{interfaceClass},
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
RpcRequest request = new RpcRequest(); // 创建并初始化 RPC 请求
request.setRequestId(UUID.randomUUID().toString());
request.setClassName(method.getDeclaringClass().getName());
request.setMethodName(method.getName());
request.setParameterTypes(method.getParameterTypes());
request.setParameters(args); if (serviceDiscovery != null) {
serverAddress = serviceDiscovery.discover(); // 发现服务
} String[] array = serverAddress.split(":");
String host = array[0];
int port = Integer.parseInt(array[1]); RpcClient client = new RpcClient(host, port); // 初始化 RPC 客户端
RpcResponse response = client.send(request); // 通过 RPC 客户端发送 RPC 请求并获取 RPC 响应 if (response.isError()) {
throw response.getError();
} else {
return response.getResult();
}
}
}
);
}
}
客户端简单实现
public class RpcClient extends SimpleChannelInboundHandler<RpcResponse> { private static final Logger LOGGER = LoggerFactory.getLogger(RpcClient.class); private String host;
private int port; private RpcResponse response; private final Object obj = new Object(); public RpcClient(String host, int port) {
this.host = host;
this.port = port;
} @Override
public void channelRead0(ChannelHandlerContext ctx, RpcResponse response) throws Exception {
this.response = response; synchronized (obj) {
obj.notifyAll(); // 收到响应,唤醒线程
}
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
LOGGER.error("client caught exception", cause);
ctx.close();
} public RpcResponse send(RpcRequest request) throws Exception {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group).channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel channel) throws Exception {
channel.pipeline()
.addLast(new RpcEncoder(RpcRequest.class)) // 将 RPC 请求进行编码(为了发送请求)
.addLast(new RpcDecoder(RpcResponse.class)) // 将 RPC 响应进行解码(为了处理响应)
.addLast(RpcClient.this); // 使用 RpcClient 发送 RPC 请求
}
})
.option(ChannelOption.SO_KEEPALIVE, true); ChannelFuture future = bootstrap.connect(host, port).sync();
future.channel().writeAndFlush(request).sync(); synchronized (obj) {
obj.wait(); // 未收到响应,使线程等待
} if (response != null) {
future.channel().closeFuture().sync();
}
return response;
} finally {
group.shutdownGracefully();
}
}
}
客户端发送测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring.xml")
public class HelloServiceTest { @Autowired
private RpcProxy rpcProxy; @Test
public void helloTest() {
HelloService helloService = rpcProxy.create(HelloService.class);
String result = helloService.hello("World");
Assert.assertEquals("Hello! World", result);
}
}
学习别人的rpc框架的更多相关文章
- 大数据学习——hadoop的RPC框架
项目结构 服务端代码 test-hadoop-rpc pom.xml <?xml version="1.0" encoding="UTF-8"?> ...
- 简易RPC框架-学习使用
*:first-child { margin-top: 0 !important; } body>*:last-child { margin-bottom: 0 !important; } /* ...
- 一个入门rpc框架的学习
一个入门rpc框架的学习 参考 huangyong-rpc 轻量级分布式RPC框架 该程序是一个短连接的rpc实现 简介 RPC,即 Remote Procedure Call(远程过程调用),说得通 ...
- rpc框架dubbo学习入门及环境搭建(spring boot+Kotlin)
学习之前,确保有以下知识基础: Java网络编程 Socket传输数据 IO流 rpc简介及实现 rpc是remote procedure call的简写,意思为远程过程调用. rpc应用较多的情景是 ...
- 学习写简单的RPC框架demo
学习实现一个简单的RPC框架. 工程主要目录分级结构: rpc-common: 公共基础包,能力提供包 rpc-provider: 服务提供者 rpc-consumer:服务消费者 rpc-servi ...
- RPC框架学习+小Demo实例
一.什么是RPC协议? 全称:远程过程调度协议 效果:使消费者向调用本地方法一样调用远程服务方法,对使用者透明 目前常用:Dubbo.Thirft.Sofa.... 功能: 建立远程通信(socket ...
- RPC 框架要实现这个功能,我们可以使用泛化调用。那什么是泛化调用呢?我们带着这个问题,先学习下如何在没有接口的情况下进行 RPC 调用。
RPC 框架要实现这个功能,我们可以使用泛化调用.那什么是泛化调用呢?我们带着这个问题,先学习下如何在没有接口的情况下进行 RPC 调用.
- rpc框架之gRPC 学习 - hello world
grpc是google在github于2015年开源的一款RPC框架,虽然protobuf很早google就开源了,但是google一直没推出正式的开源框架,导致github上基于protobuf的r ...
- rpc框架之 thrift 学习 1 - 安装 及 hello world
thrift是一个facebook开源的高效RPC框架,其主要特点是跨语言及二进制高效传输(当然,除了二进制,也支持json等常用序列化机制),官网地址:http://thrift.apache.or ...
随机推荐
- go语言学习--go的临时对象池--sync.Pool
一个sync.Pool对象就是一组临时对象的集合.Pool是协程安全的. Pool用于存储那些被分配了但是没有被使用,而未来可能会使用的值,以减小垃圾回收的压力.一个比较好的例子是fmt包,fmt包总 ...
- [UE4]一分钟实现聊天系统
天系统:客户端发消息到服务器端,服务器端把收到的消息广播到所有客户端. 由于聊天对象需要支持“可复制”和每个客户端都发给一个,所以GameInstance.GameModeGameState都不适合存 ...
- win10家庭版怎么开启Administrator超级管理员帐户
一.win10家庭版开启administrator方法: 1.通过Cortana搜索cmd,匹配出“命令提示符”,右键以管理员身份运行: 2.在打开的命令提示符窗口输入net user admin ...
- 基于 MBTiles 规范扩展的缓存文件格式说明
MBTiles 是由 MapBox 制定的一种将瓦片地图数据存储到SQLite数据库中并可快速使用,管理和分享的规范.该规范由MapBox制定,详见http://mapbox.com/mbtiles- ...
- (error) MOVED 5798 172.17.0.3:6379
登录没有启动集群模式(即缺少了那个"-c"): redis-cli -c -h yourhost -p yourpost
- 解决在word中不能使用输入法
打开一个Word文档-------------->单击 文件---->选项---->高级---->取消什么?看图 然后重新启动word
- JavaScript、CSS样式收集
JS集: //给from一个名字然后在JavaScript的地方就可以用form的名字来调用form表单里input元素的value属性可以得到值 var val=form_name.input_na ...
- 用tmux工具给linux命令行分栏
介绍 有时候我们需要在命令行里同时开多个程序,但是每个程序都会占用命令行,这时候可以用tmux,给命令行界面分栏. 基本概念 tmux是分多层的 会话>窗口(我下文称作:页)>面板(或者叫 ...
- webpack实现scss编译配置
1.webpack.start.js: var webpack = require('webpack'); var SpritesmithPlugin = require('webpack-sprit ...
- 在Raid模式下装Win10找不到固态硬盘怎么办
现在新出厂的笔记本电脑中,系统的BIOS内,SATA Controller Mode默认设置的是为Intel RST Premium模式,该模式会将硬盘组成磁盘阵列的模式(Raid模式),而原版的Wi ...