Spring+Netty+Protostuff+ZooKeeper实现轻量级RPC服务(一)

释放双眼,带上耳机,听听看~!

【转】Spring+Netty+Protostuff+ZooKeeper实现轻量级RPC服务(一)

转载地址:https://my.oschina.net/Listening/blog/682124

转载地址:http://www.jb51.net/article/87079.htm

RPC,即Remote Procedure Call(远程过程调用),说得通俗一点就是:调用远程计算机上的服务,就像调用本地服务一样。

RPC可基于HTTP 或 TCP 协议,Web Service就是基于HTTP 协议的RPC ,它具有良好的跨平台性,但其性能却不如基于 TCP 协议的RPC 。 两方面会直接影响 RPC 的性能,一是传输方式,二是序列化。

众所周知,TCP是传输层协议,HTTP是应用层协议,而传输层较应用层更底层,在数据传输方面,越底层越快,因此,在一般情况下,TCP一定比 HTTP快。就序列化而言,Java提供了默认的序列化方式,但在高并发的情况下,这种方式将会带来一些性能上的瓶颈,于是市面上出现了一系列优秀的序列化的框架,比如:Protobuf、Kryo、Hession、Jackson等,它们可以取代Java默认的序列化,从而提供更高效的性能。

为了支持高并发,传统的阻塞式IO 显然不太合适,因此我们需要异步的IO ,即NIO 。Java提供了 NIO 的解决方案,Java 7 也提供了更优秀的 NIO.2支持,用Java实现 NIO并不是遥不可及的事情,只是需要我们熟悉 NIO的技术细节。

我们需要将服务部署在分布环境下的不同节点上,通过服务注册的方式,让客户端来自动发现当前可用的服务,并调用这些服务。这需要一种服务注册表(Service Registry)的组件,让它来注册分布环境下有的服务地址(包括:主机名和端口号)。

应用、服务、服务注册表之间的关系如下图:

每台Server 上可发布多个Service ,这些Service 共用一个 host 与 port ,在分布式环境下会提供 Server 共同对外提供 Service 。此外,为防止 Service Registry 出现单点故障,因此需要将其搭建为集群环境。

本文将为你揭晓开发轻量级分布式 RPC 框架的具体过程,该框架基于 TCP 协议,提供了 NIO 特性,提供高效的序列化方式,同时也具备服务注册与发现的能力。

根据以上技术需求,我们可使用如下技术选型:

  • Spring:它是最强大的依赖注入框架,也是业界的权威标准
  • Netty:它使 NIO 编程更加容易,屏蔽了Java底层的 NIO 细节
  • Protostuff:它基于 Protobuf 序列化框架,面向 POJO ,无需编写 .proto文件
  • ZooKeeper:提供服务注册与发现功能,开发分布式系统的必备的选择,同时它也具备天生的集群能力。

先介绍本例的大致步骤,相关源码会在文章后面详细列出来

本例的步骤介绍

第一步:编写服务接口


1
2
3
4
1public interface HelloService {
2  String hello(String name);
3}
4

第二步:编写服务接口的实现类


1
2
3
4
5
6
7
8
1@RpcService(HelloService.class) // 指定远程接口
2public class HelloServiceImpl implements HelloService {
3  @Override
4  public String hello(String name) {
5    return "Hello! " + name;
6  }
7}
8

使用RpcService 注解定义在服务接口的实现类上,需要对该实现类指定远程接口,因为实现类可能会实现多个接口,一定要告诉框架那个才是远程接口。

RpcService 代码如下:


1
2
3
4
5
6
7
1@Target({ElementType.TYPE})
2@Retention(RetentionPolicy.RUNTIME)
3@Component // 表明可被 Spring 扫描
4public @interface RpcService {
5  Class<?> value();
6}
7

该注解具备 Spring 的 Component 注解的特性,可被Spring扫描。 
该实现类放在服务端的 jar包中,该 jar包还提供了一些服务端的配置文件与启动服务的引导程序。

第三步:配置服务端

服务端 Spring 配置文件名为 applicationContext.xml ,内容如下:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
1<beans ...>
2  <context:component-scan base-package="com.xxx.server"/>
3
4  <context:property-placeholder location="classpath:config.properties"/>
5
6  <!-- 配置服务注册组件 -->
7  <bean id="serviceRegistry" class="com.xxx.registry.ServiceRegistry">
8    <constructor-arg name="registryAddress" value="${registry.address}"/>
9  </bean>
10
11  <!-- 配置 RPC 服务器 -->
12  <bean id="rpcServer" class="com.xxx.server.RpcServer">
13    <constructor-arg name="serverAddress" value="${server.address}"/>
14    <constructor-arg name="serviceRegistry" ref="serviceRegistry"/>
15  </bean>
16</beans>
17

具体的配置参数在 config.properties 文件中,内容如下:


1
2
3
4
5
6
1# ZooKeeper 服务器
2registry.address=127.0.0.1:2181
3
4# RPC 服务器
5server.address=127.0.0.1:8000
6

以上配置表明:连接本地的 ZooKeeper 服务器,并在8000 端口发布RPC 服务。

第四步:启动服务器端发布服务

为了加载 Spring 配置文件来发布服务,只需要编写一个引导程序即可:


1
2
3
4
5
6
7
1public class RpcBootstrap {
2
3  public static void main(String[] args) {
4    new ClassPathXmlApplicationContext("applicationContext.xml");
5  }
6}
7

运行RpcBootstrap 类的main方法即可启动服务端,但还有两个重要的组件尚未实现,它们分别是: ServiceRegistry 与 RpcServer,下文会给出具体实现细节。

第五步:实现服务注册

使用 ZooKeeper 客户单可轻松实现服务注册功能, ServiceRegistry 代码如下:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
1public class ServiceRegistry {
2
3  private static final Logger LOGGER = LoggerFactory.getLogger(ServiceRegistry.class);
4
5  private CountDownLatch latch = new CountDownLatch(1);
6
7  private String registryAddress;
8
9  public ServiceRegistry(String registryAddress) {
10    this.registryAddress = registryAddress;
11  }
12
13  public void register(String data) {
14    if (data != null) {
15      ZooKeeper zk = connectServer();
16      if (zk != null) {
17        createNode(zk, data);
18      }
19    }
20  }
21
22  private ZooKeeper connectServer() {
23    ZooKeeper zk = null;
24    try {
25      zk = new ZooKeeper(registryAddress, Constant.ZK_SESSION_TIMEOUT, new Watcher() {
26        @Override
27        public void process(WatchedEvent event) {
28          if (event.getState() == Event.KeeperState.SyncConnected) {
29            latch.countDown();
30          }
31        }
32      });
33      latch.await();
34    } catch (IOException | InterruptedException e) {
35      LOGGER.error("", e);
36    }
37    return zk;
38  }
39
40  private void createNode(ZooKeeper zk, String data) {
41    try {
42      byte[] bytes = data.getBytes();
43      String path = zk.create(Constant.ZK_DATA_PATH, bytes, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
44      LOGGER.debug("create zookeeper node ({} => {})", path, data);
45    } catch (KeeperException | InterruptedException e) {
46      LOGGER.error("", e);
47    }
48  }
49}
50

其中,通过 Constant 配置了所有的常量:


1
2
3
4
5
6
7
8
1public interface Constant {
2
3  int ZK_SESSION_TIMEOUT = 5000;
4
5  String ZK_REGISTRY_PATH = "/registry";
6  String ZK_DATA_PATH = ZK_REGISTRY_PATH + "/data";
7}
8

注意:首先需要使用 ZooKeeper 客户端命令行创建 /registry 永久节点,用于存放所有的服务临时节点。

第六步:实现 RPC 服务器

使用 Netty 可实现一个支持 NIO 的 RPC 服务器,需要使用 ServiceRegistry 注册服务地址,RpcServer 代码如下:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
1public class RpcServer implements ApplicationContextAware, InitializingBean {
2
3  private static final Logger LOGGER = LoggerFactory.getLogger(RpcServer.class);
4
5  private String serverAddress;
6  private ServiceRegistry serviceRegistry;
7
8  private Map<String, Object> handlerMap = new HashMap<>(); // 存放接口名与服务对象之间的映射关系
9
10  public RpcServer(String serverAddress) {
11    this.serverAddress = serverAddress;
12  }
13
14  public RpcServer(String serverAddress, ServiceRegistry serviceRegistry) {
15    this.serverAddress = serverAddress;
16    this.serviceRegistry = serviceRegistry;
17  }
18
19  @Override
20  public void setApplicationContext(ApplicationContext ctx) throws BeansException {
21    Map<String, Object> serviceBeanMap = ctx.getBeansWithAnnotation(RpcService.class); // 获取所有带有 RpcService 注解的 Spring Bean
22    if (MapUtils.isNotEmpty(serviceBeanMap)) {
23      for (Object serviceBean : serviceBeanMap.values()) {
24        String interfaceName = serviceBean.getClass().getAnnotation(RpcService.class).value().getName();
25        handlerMap.put(interfaceName, serviceBean);
26      }
27    }
28  }
29
30  @Override
31  public void afterPropertiesSet() throws Exception {
32    EventLoopGroup bossGroup = new NioEventLoopGroup();
33    EventLoopGroup workerGroup = new NioEventLoopGroup();
34    try {
35      ServerBootstrap bootstrap = new ServerBootstrap();
36      bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
37        .childHandler(new ChannelInitializer<SocketChannel>() {
38          @Override
39          public void initChannel(SocketChannel channel) throws Exception {
40            channel.pipeline()
41              .addLast(new RpcDecoder(RpcRequest.class)) // 将 RPC 请求进行解码(为了处理请求)
42              .addLast(new RpcEncoder(RpcResponse.class)) // 将 RPC 响应进行编码(为了返回响应)
43              .addLast(new RpcHandler(handlerMap)); // 处理 RPC 请求
44          }
45        })
46        .option(ChannelOption.SO_BACKLOG, 128)
47        .childOption(ChannelOption.SO_KEEPALIVE, true);
48
49      String[] array = serverAddress.split(":");
50      String host = array[0];
51      int port = Integer.parseInt(array[1]);
52
53      ChannelFuture future = bootstrap.bind(host, port).sync();
54      LOGGER.debug("server started on port {}", port);
55
56      if (serviceRegistry != null) {
57        serviceRegistry.register(serverAddress); // 注册服务地址
58      }
59
60      future.channel().closeFuture().sync();
61    } finally {
62      workerGroup.shutdownGracefully();
63      bossGroup.shutdownGracefully();
64    }
65  }
66}
67

以上代码中,有两个重要的 POJO 需要描述一下,他们分别是 RpcRequest 与 RpcResponse 。 
使用 RpcRequest 封装 RPC 请求,代码如下:


1
2
3
4
5
6
7
8
9
10
11
1public class RpcRequest {
2
3  private String requestId;
4  private String className;
5  private String methodName;
6  private Class<?>[] parameterTypes;
7  private Object[] parameters;
8
9  // getter/setter...
10}
11

使用 RpcResponse 封装 RPC 响应,代码如下:


1
2
3
4
5
6
7
8
9
1public class RpcResponse {
2
3  private String requestId;
4  private Throwable error;
5  private Object result;
6
7  // getter/setter...
8}
9

使用 RpcDecoder 提供 RPC 解码,只需扩展 Netty 的 ByteToMessageDecoder抽象类的 decode 方法即可,代码如下:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
1public class RpcDecoder extends ByteToMessageDecoder {
2
3  private Class<?> genericClass;
4
5  public RpcDecoder(Class<?> genericClass) {
6    this.genericClass = genericClass;
7  }
8
9  @Override
10  public void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
11    if (in.readableBytes() < 4) {
12      return;
13    }
14    in.markReaderIndex();
15    int dataLength = in.readInt();
16    if (dataLength < 0) {
17      ctx.close();
18    }
19    if (in.readableBytes() < dataLength) {
20      in.resetReaderIndex();
21      return;
22    }
23    byte[] data = new byte[dataLength];
24    in.readBytes(data);
25
26    Object obj = SerializationUtil.deserialize(data, genericClass);
27    out.add(obj);
28  }
29}
30

使用 RpcEncoder 提供 RPC 编码 ,只需要扩展 Netty 的 MessageToByteEncoder 抽象类的 encode 方法即可,代码如下:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
1public class RpcEncoder extends MessageToByteEncoder {
2
3  private Class<?> genericClass;
4
5  public RpcEncoder(Class<?> genericClass) {
6    this.genericClass = genericClass;
7  }
8
9  @Override
10  public void encode(ChannelHandlerContext ctx, Object in, ByteBuf out) throws Exception {
11    if (genericClass.isInstance(in)) {
12      byte[] data = SerializationUtil.serialize(in);
13      out.writeInt(data.length);
14      out.writeBytes(data);
15    }
16  }
17}
18

编写一个SerializationUtil工具类,使用Protostuff实现序列化:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
1public class SerializationUtil {
2
3  private static Map<Class<?>, Schema<?>> cachedSchema = new ConcurrentHashMap<>();
4
5  private static Objenesis objenesis = new ObjenesisStd(true);
6
7  private SerializationUtil() {
8  }
9
10  @SuppressWarnings("unchecked")
11  private static <T> Schema<T> getSchema(Class<T> cls) {
12    Schema<T> schema = (Schema<T>) cachedSchema.get(cls);
13    if (schema == null) {
14      schema = RuntimeSchema.createFrom(cls);
15      if (schema != null) {
16        cachedSchema.put(cls, schema);
17      }
18    }
19    return schema;
20  }
21
22  @SuppressWarnings("unchecked")
23  public static <T> byte[] serialize(T obj) {
24    Class<T> cls = (Class<T>) obj.getClass();
25    LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
26    try {
27      Schema<T> schema = getSchema(cls);
28      return ProtostuffIOUtil.toByteArray(obj, schema, buffer);
29    } catch (Exception e) {
30      throw new IllegalStateException(e.getMessage(), e);
31    } finally {
32      buffer.clear();
33    }
34  }
35
36  public static <T> T deserialize(byte[] data, Class<T> cls) {
37    try {
38      T message = (T) objenesis.newInstance(cls);
39      Schema<T> schema = getSchema(cls);
40      ProtostuffIOUtil.mergeFrom(data, message, schema);
41      return message;
42    } catch (Exception e) {
43      throw new IllegalStateException(e.getMessage(), e);
44    }
45  }
46}
47

以上使用了 Objenesis 来实例化对象,它是比Java反射更加强大。 
注意:如需要替换其他序列化框架,只需修改 SerializationUtil 即可。当然,更好的实现方式是提供配置项来决定使用哪种序列化方式。

使用RpcHandler 中处理 RPC 请求,只需扩展 Netty 的 SimpleChannelInboundHandler 抽象类即可,代码如下:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
1public class RpcHandler extends SimpleChannelInboundHandler<RpcRequest> {
2
3  private static final Logger LOGGER = LoggerFactory.getLogger(RpcHandler.class);
4
5  private final Map<String, Object> handlerMap;
6
7  public RpcHandler(Map<String, Object> handlerMap) {
8    this.handlerMap = handlerMap;
9  }
10
11  @Override
12  public void channelRead0(final ChannelHandlerContext ctx, RpcRequest request) throws Exception {
13    RpcResponse response = new RpcResponse();
14    response.setRequestId(request.getRequestId());
15    try {
16      Object result = handle(request);
17      response.setResult(result);
18    } catch (Throwable t) {
19      response.setError(t);
20    }
21    ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
22  }
23
24  private Object handle(RpcRequest request) throws Throwable {
25    String className = request.getClassName();
26    Object serviceBean = handlerMap.get(className);
27
28    Class<?> serviceClass = serviceBean.getClass();
29    String methodName = request.getMethodName();
30    Class<?>[] parameterTypes = request.getParameterTypes();
31    Object[] parameters = request.getParameters();
32
33    /*Method method = serviceClass.getMethod(methodName, parameterTypes);
34    method.setAccessible(true);
35    return method.invoke(serviceBean, parameters);*/
36
37    FastClass serviceFastClass = FastClass.create(serviceClass);
38    FastMethod serviceFastMethod = serviceFastClass.getMethod(methodName, parameterTypes);
39    return serviceFastMethod.invoke(serviceBean, parameters);
40  }
41
42  @Override
43  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
44    LOGGER.error("server caught exception", cause);
45    ctx.close();
46  }
47}
48

为了避免使用 Java 反射带来的性能问题,我们可以使用 CGLib 提供的反射 API ,如上面用到的 FastClass 与 FastMethod 。

第七步:配置客户端

同样使用 Spring 配置文件来配置 RPC 客户端,applicationContext.xml代码如下:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
1<beans ...>
2  <context:property-placeholder location="classpath:config.properties"/>
3
4  <!-- 配置服务发现组件 -->
5  <bean id="serviceDiscovery" class="com.xxx.registry.ServiceDiscovery">
6    <constructor-arg name="registryAddress" value="${registry.address}"/>
7  </bean>
8
9  <!-- 配置 RPC 代理 -->
10  <bean id="rpcProxy" class="com.xxx.client.RpcProxy">
11    <constructor-arg name="serviceDiscovery" ref="serviceDiscovery"/>
12  </bean>
13</beans>
14

其中 config.properties 提供了具体的配置:


1
2
3
1# ZooKeeper 服务器
2registry.address=127.0.0.1:2181
3

第八步:实现服务发现

同样使用 ZooKerper 实现服务发现功能,见如下代码:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
1public class ServiceDiscovery {
2
3  private static final Logger LOGGER = LoggerFactory.getLogger(ServiceDiscovery.class);
4
5  private CountDownLatch latch = new CountDownLatch(1);
6
7  private volatile List<String> dataList = new ArrayList<>();
8
9  private String registryAddress;
10
11  public ServiceDiscovery(String registryAddress) {
12    this.registryAddress = registryAddress;
13
14    ZooKeeper zk = connectServer();
15    if (zk != null) {
16      watchNode(zk);
17    }
18  }
19
20  public String discover() {
21    String data = null;
22    int size = dataList.size();
23    if (size > 0) {
24      if (size == 1) {
25        data = dataList.get(0);
26        LOGGER.debug("using only data: {}", data);
27      } else {
28        data = dataList.get(ThreadLocalRandom.current().nextInt(size));
29        LOGGER.debug("using random data: {}", data);
30      }
31    }
32    return data;
33  }
34
35  private ZooKeeper connectServer() {
36    ZooKeeper zk = null;
37    try {
38      zk = new ZooKeeper(registryAddress, Constant.ZK_SESSION_TIMEOUT, new Watcher() {
39        @Override
40        public void process(WatchedEvent event) {
41          if (event.getState() == Event.KeeperState.SyncConnected) {
42            latch.countDown();
43          }
44        }
45      });
46      latch.await();
47    } catch (IOException | InterruptedException e) {
48      LOGGER.error("", e);
49    }
50    return zk;
51  }
52
53  private void watchNode(final ZooKeeper zk) {
54    try {
55      List<String> nodeList = zk.getChildren(Constant.ZK_REGISTRY_PATH, new Watcher() {
56        @Override
57        public void process(WatchedEvent event) {
58          if (event.getType() == Event.EventType.NodeChildrenChanged) {
59            watchNode(zk);
60          }
61        }
62      });
63      List<String> dataList = new ArrayList<>();
64      for (String node : nodeList) {
65        byte[] bytes = zk.getData(Constant.ZK_REGISTRY_PATH + "/" + node, false, null);
66        dataList.add(new String(bytes));
67      }
68      LOGGER.debug("node data: {}", dataList);
69      this.dataList = dataList;
70    } catch (KeeperException | InterruptedException e) {
71      LOGGER.error("", e);
72    }
73  }
74}
75

第九步:实现 RPC 代理

这里使用 Java提供的动态代理技术实现 RPC 代理(当然也可以使用 CGLib来实现),具体代码如下:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
1public class RpcProxy {
2
3  private String serverAddress;
4  private ServiceDiscovery serviceDiscovery;
5
6  public RpcProxy(String serverAddress) {
7    this.serverAddress = serverAddress;
8  }
9
10  public RpcProxy(ServiceDiscovery serviceDiscovery) {
11    this.serviceDiscovery = serviceDiscovery;
12  }
13
14  @SuppressWarnings("unchecked")
15  public <T> T create(Class<?> interfaceClass) {
16    return (T) Proxy.newProxyInstance(
17      interfaceClass.getClassLoader(),
18      new Class<?>[]{interfaceClass},
19      new InvocationHandler() {
20        @Override
21        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
22          RpcRequest request = new RpcRequest(); // 创建并初始化 RPC 请求
23          request.setRequestId(UUID.randomUUID().toString());
24          request.setClassName(method.getDeclaringClass().getName());
25          request.setMethodName(method.getName());
26          request.setParameterTypes(method.getParameterTypes());
27          request.setParameters(args);
28
29          if (serviceDiscovery != null) {
30            serverAddress = serviceDiscovery.discover(); // 发现服务
31          }
32
33          String[] array = serverAddress.split(":");
34          String host = array[0];
35          int port = Integer.parseInt(array[1]);
36
37          RpcClient client = new RpcClient(host, port); // 初始化 RPC 客户端
38          RpcResponse response = client.send(request); // 通过 RPC 客户端发送 RPC 请求并获取 RPC 响应
39
40          if (response.isError()) {
41            throw response.getError();
42          } else {
43            return response.getResult();
44          }
45        }
46      }
47    );
48  }
49}
50

使用 RpcClient 类来实现 RPC 客户端,只需要 Netty 提供的 SimpleChannelInboundHandler抽象类即可,代码如下:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
1public class RpcClient extends SimpleChannelInboundHandler<RpcResponse> {
2
3  private static final Logger LOGGER = LoggerFactory.getLogger(RpcClient.class);
4
5  private String host;
6  private int port;
7
8  private RpcResponse response;
9
10  private final Object obj = new Object();
11
12  public RpcClient(String host, int port) {
13    this.host = host;
14    this.port = port;
15  }
16
17  @Override
18  public void channelRead0(ChannelHandlerContext ctx, RpcResponse response) throws Exception {
19    this.response = response;
20
21    synchronized (obj) {
22      obj.notifyAll(); // 收到响应,唤醒线程
23    }
24  }
25
26  @Override
27  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
28    LOGGER.error("client caught exception", cause);
29    ctx.close();
30  }
31
32  public RpcResponse send(RpcRequest request) throws Exception {
33    EventLoopGroup group = new NioEventLoopGroup();
34    try {
35      Bootstrap bootstrap = new Bootstrap();
36      bootstrap.group(group).channel(NioSocketChannel.class)
37        .handler(new ChannelInitializer<SocketChannel>() {
38          @Override
39          public void initChannel(SocketChannel channel) throws Exception {
40            channel.pipeline()
41              .addLast(new RpcEncoder(RpcRequest.class)) // 将 RPC 请求进行编码(为了发送请求)
42              .addLast(new RpcDecoder(RpcResponse.class)) // 将 RPC 响应进行解码(为了处理响应)
43              .addLast(RpcClient.this); // 使用 RpcClient 发送 RPC 请求
44          }
45        })
46        .option(ChannelOption.SO_KEEPALIVE, true);
47
48      ChannelFuture future = bootstrap.connect(host, port).sync();
49      future.channel().writeAndFlush(request).sync();
50
51      synchronized (obj) {
52        obj.wait(); // 未收到响应,使线程等待
53      }
54
55      if (response != null) {
56        future.channel().closeFuture().sync();
57      }
58      return response;
59    } finally {
60      group.shutdownGracefully();
61    }
62  }
63}
64

第十步:发送 RPC 请求

使用 JUnit 结合 Spring 编写一个单元测试,代码如下:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
1@RunWith(SpringJUnit4ClassRunner.class)
2@ContextConfiguration(locations = "classpath:spring.xml")
3public class HelloServiceTest {
4
5  @Autowired
6  private RpcProxy rpcProxy;
7
8  @Test
9  public void helloTest() {
10    HelloService helloService = rpcProxy.create(HelloService.class);
11    String result = helloService.hello("World");
12    Assert.assertEquals("Hello! World", result);
13  }
14}
15

运行以上单元测试,如果不出意外的话,测试是可以通过的。

总结:

本文通过 Spring+Netty+ Protostuff+Zookeeper 实现了一个轻量级 RPC 框架,使用Spring 提供依赖注入与参数配置,使用 Netty 实现了 NIO 方式的数据传输,使用 Protostuff 实现对象序列化,使用 ZooKeeper 实现服务注册与发现。 使用该框架,可将服务部署到分布环境中的任意节点上,客户端通过远程接口来调用服务端的具体实现,让服务端与客户端的开发完全分离,为实现大规模分布式应用提供了技术支持。

给TA打赏
共{{data.count}}人
人已打赏
安全经验

独立博客怎样申请谷歌Adsense

2021-10-11 16:36:11

安全经验

安全咨询服务

2022-1-12 14:11:49

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索