Java應用Sping框架編寫RPC長途進程挪用辦事的教程。本站提示廣大學習愛好者:(Java應用Sping框架編寫RPC長途進程挪用辦事的教程)文章只能為提供參考,不一定能成為您想要的結果。以下是Java應用Sping框架編寫RPC長途進程挪用辦事的教程正文
RPC,即 Remote Procedure Call(長途進程挪用),說得淺顯一點就是:挪用長途盤算機上的辦事,就像挪用當地辦事一樣。
RPC 可基於 HTTP 或 TCP 協定,Web Service 就是基於 HTTP 協定的 RPC,它具有優越的跨平台性,但其機能卻不如基於 TCP 協定的 RPC。會兩方面會直接影響 RPC 的機能,一是傳輸方法,二是序列化。
盡人皆知,TCP 是傳輸層協定,HTTP 是運用層協定,而傳輸層較運用層加倍底層,在數據傳輸方面,越底層越快,是以,在普通情形下,TCP 必定比 HTTP 快。就序列化而言,Java 供給了默許的序列化方法,但在高並發的情形下,這類方法將會帶來一些機能上的瓶頸,因而市情上湧現了一系列優良的序列化框架,好比:Protobuf、Kryo、Hessian、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 特征,供給高效的序列化方法,同時也具有辦事注冊與發明的才能。
依據以上技巧需求,我們可以使用以下技巧選型:
相干 Maven 依附請見最初附錄。
第一步:編寫辦事接口
public interface HelloService { String hello(String name); }
將該接口放在自力的客戶端 jar 包中,以供給用應用。
第二步:編寫辦事接口的完成類
@RpcService(HelloService.class) // 指定長途接口 public class HelloServiceImpl implements HelloService { @Override public String hello(String name) { return "Hello! " + name; } }
應用RpcService注解界說在辦事接口的完成類上,須要對該完成類指定長途接口,由於完成類能夠會完成多個接口,必定要告知框架哪一個才是長途接口。
RpcService代碼以下:
@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Component // 注解可被 Spring 掃描 public @interface RpcService { Class<?> value(); }
該注解具有 Spring 的Component注解的特征,可被 Spring 掃描。
該完成類放在辦事端 jar 包中,該 jar 包還供給了一些辦事真個設置裝備擺設文件與啟動辦事的引誘法式。
第三步:設置裝備擺設辦事端
辦事端 Spring 設置裝備擺設文件名為spring.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>
詳細的設置裝備擺設參數在config.properties文件中,內容以下:
# ZooKeeper 辦事器 registry.address=127.0.0.1:2181 # RPC 辦事器 server.address=127.0.0.1:8000
以上設置裝備擺設注解:銜接當地的 ZooKeeper 辦事器,並在 8000 端口上宣布 RPC 辦事。
第四步:啟動辦事器並宣布辦事
為了加載 Spring 設置裝備擺設文件來宣布辦事,只需編寫一個引誘法式便可:
public class RpcBootstrap { public static void main(String[] args) { new ClassPathXmlApplicationContext("spring.xml"); } }
運轉RpcBootstrap類的main辦法便可啟動辦事端,但還有兩個主要的組件還沒有完成,它們分離是:ServiceRegistry與RpcServer,下文會給出詳細完成細節。
第五步:完成辦事注冊
應用 ZooKeeper 客戶端可輕松完成辦事注冊功效,ServiceRegistry代碼以下:
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); } } }
個中,經由過程Constant設置裝備擺設了一切的常量:
public interface Constant { int ZK_SESSION_TIMEOUT = 5000; String ZK_REGISTRY_PATH = "/registry"; String ZK_DATA_PATH = ZK_REGISTRY_PATH + "/data"; }
留意:起首須要應用 ZooKeeper 客戶端敕令行創立/registry永遠節點,用於寄存一切的辦事暫時節點。
第六步:完成 RPC 辦事器
應用 Netty 可完成一個支撐 NIO 的 RPC 辦事器,須要應用ServiceRegistry注冊辦事地址,RpcServer代碼以下:
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(); } } }
以上代碼中,有兩個主要的 POJO 須要描寫一下,它們分離是RpcRequest與RpcResponse。
應用RpcRequest封裝 RPC 要求,代碼以下:
public class RpcRequest { private String requestId; private String className; private String methodName; private Class<?>[] parameterTypes; private Object[] parameters; // getter/setter... }
應用RpcResponse封裝 RPC 呼應,代碼以下:
public class RpcResponse { private String requestId; private Throwable error; private Object result; // getter/setter... }
應用RpcDecoder供給 RPC 解碼,只需擴大 Netty 的ByteToMessageDecoder籠統類的decode辦法便可,代碼以下:
public class RpcDecoder extends ByteToMessageDecoder { private Class<?> genericClass; public RpcDecoder(Class<?> genericClass) { this.genericClass = genericClass; } @Override public void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { if (in.readableBytes() < 4) { return; } in.markReaderIndex(); int dataLength = in.readInt(); if (dataLength < 0) { ctx.close(); } if (in.readableBytes() < dataLength) { in.resetReaderIndex(); return; } byte[] data = new byte[dataLength]; in.readBytes(data); Object obj = SerializationUtil.deserialize(data, genericClass); out.add(obj); } }
應用RpcEncoder供給 RPC 編碼,只需擴大 Netty 的MessageToByteEncoder籠統類的encode辦法便可,代碼以下:
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); } } }
編寫一個SerializationUtil對象類,應用Protostuff完成序列化:
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); } } }
以上了應用 Objenesis 來實例化對象,它是比 Java 反射加倍壯大。
留意:如須要調換其它序列化框架,只需修正SerializationUtil便可。固然,更好的完成方法是供給設置裝備擺設項來決議應用哪一種序列化方法。
應用RpcHandler中處置 RPC 要求,只需擴大 Netty 的SimpleChannelInboundHandler籠統類便可,代碼以下:
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(); } }
為了不應用 Java 反射帶來的機能成績,我們可使用 CGLib 供給的反射 API,如下面用到的FastClass與FastMethod。
第七步:設置裝備擺設客戶端
異樣應用 Spring 設置裝備擺設文件來設置裝備擺設 RPC 客戶端,spring.xml代碼以下:
<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>
個中config.properties供給了詳細的設置裝備擺設:
# ZooKeeper 辦事器 registry.address=127.0.0.1:2181
第八步:完成辦事發明
異樣應用 ZooKeeper 完成辦事發明功效,見以下代碼:
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); } } }
第九步:完成 RPC 署理
這裡應用 Java 供給的靜態署理技巧完成 RPC 署理(固然也能夠應用 CGLib 來完成),詳細代碼以下:
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(); } } } ); } }
應用RpcClient類完成 RPC 客戶端,只需擴大 Netty 供給的SimpleChannelInboundHandler籠統類便可,代碼以下:
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(); } } }
第十步:發送 RPC 要求
應用 JUnit 聯合 Spring 編寫一個單位測試,代碼以下:
@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); } }
運轉以上單位測試,假如不出不測的話,您應當會看到綠條。
總結
本文經由過程 Spring + Netty + Protostuff + ZooKeeper 完成了一個輕量級 RPC 框架,應用 Spring 供給依附注入與參數設置裝備擺設,應用 Netty 完成 NIO 方法的數據傳輸,應用 Protostuff 完成對象序列化,應用 ZooKeeper 完成辦事注冊與發明。應用該框架,可將辦事安排到散布式情況中的隨意率性節點上,客戶端經由過程長途接口來挪用辦事真個詳細完成,讓辦事端與客戶真個開辟完整分別,為完成年夜范圍散布式運用供給了基本支撐。
附錄:Maven 依附
<!-- JUnit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <!-- SLF4J --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.7</version> </dependency> <!-- Spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>3.2.12.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>3.2.12.RELEASE</version> <scope>test</scope> </dependency> <!-- Netty --> <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.0.24.Final</version> </dependency> <!-- Protostuff --> <dependency> <groupId>com.dyuproject.protostuff</groupId> <artifactId>protostuff-core</artifactId> <version>1.0.8</version> </dependency> <dependency> <groupId>com.dyuproject.protostuff</groupId> <artifactId>protostuff-runtime</artifactId> <version>1.0.8</version> </dependency> <!-- ZooKeeper --> <dependency> <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> <version>3.4.6</version> </dependency> <!-- Apache Commons Collections --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-collections4</artifactId> <version>4.0</version> </dependency> <!-- Objenesis --> <dependency> <groupId>org.objenesis</groupId> <artifactId>objenesis</artifactId> <version>2.1</version> </dependency> <!-- CGLib --> <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>3.1</version> </dependency>