---
title: "一个简易RPC框架"
author: "windpoplar"
date: "2017-01-29T13:49:21Z"
tags: []
categories: ["互联网"]
slug: "rpc"
draft: false
lastmod: "2017-01-29T13:49:21Z"
id: 2354930
url: "https://windpoplar.iteye.com/blog/2354930"
---

转：javatar.iteye.com/blog/1123915

因为要给百技上实训课，让新同学们自行实现一个简易RPC框架，在准备PPT时，就想写个示例，发现原来一个RPC框架只要一个类，10来分钟就可以写完了，虽然简陋，也晒晒： 

Java代码  [![收藏代码](http://javatar.iteye.com/images/icon_star.png)]()

001. /*
002. * Copyright 2011 Alibaba.com All right reserved. This software is the
003. * confidential and proprietary information of Alibaba.com ("Confidential
004. * Information"). You shall not disclose such Confidential Information and shall
005. * use it only in accordance with the terms of the license agreement you entered
006. * into with Alibaba.com.
007. \*/
008. package com.alibaba.study.rpc.framework;
009. import java.io.ObjectInputStream;
010. import java.io.ObjectOutputStream;
011. import java.lang.reflect.InvocationHandler;
012. import java.lang.reflect.Method;
013. import java.lang.reflect.Proxy;
014. import java.net.ServerSocket;
015. import java.net.Socket;
016. /\**
017. * RpcFramework
018. \*
019. * @author william.liangf
020. \*/
021. public class RpcFramework {
022. /\**
023. * 暴露服务
024. \*
025. * @param service 服务实现
026. * @param port 服务端口
027. * @throws Exception
028. \*/
029. public static void export(final Object service, int port) throws Exception {
030. if (service == null)
031. throw new IllegalArgumentException("service instance == null");
032. if (port &lt;= 0 || port &gt; 65535)
033. throw new IllegalArgumentException("Invalid port " + port);
034. System.out.println("Export service " + service.getClass().getName() + " on port " + port);
035. ServerSocket server = new ServerSocket(port);
036. for(;;) {
037. try {
038. final Socket socket = server.accept();
039. new Thread(new Runnable() {
040. @Override
041. public void run() {
042. try {
043. try {
044. ObjectInputStream input = new ObjectInputStream(socket.getInputStream());
045. try {
046. String methodName = input.readUTF();
047. Class&lt;?&gt;\[] parameterTypes = (Class&lt;?&gt;\[])input.readObject();
048. Object\[] arguments = (Object\[])input.readObject();
049. ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
050. try {
051. Method method = service.getClass().getMethod(methodName, parameterTypes);
052. Object result = method.invoke(service, arguments);
053. output.writeObject(result);
054. } catch (Throwable t) {
055. output.writeObject(t);
056. } finally {
057. output.close();
058. }
059. } finally {
060. input.close();
061. }
062. } finally {
063. socket.close();
064. }
065. } catch (Exception e) {
066. e.printStackTrace();
067. }
068. }
069. }).start();
070. } catch (Exception e) {
071. e.printStackTrace();
072. }
073. }
074. }
075. /\**
076. * 引用服务
077. \*
078. * @param &lt;T&gt; 接口泛型
079. * @param interfaceClass 接口类型
080. * @param host 服务器主机名
081. * @param port 服务器端口
082. * @return 远程服务
083. * @throws Exception
084. \*/
085. @SuppressWarnings("unchecked")
086. public static &lt;T&gt; T refer(final Class&lt;T&gt; interfaceClass, final String host, final int port) throws Exception {
087. if (interfaceClass == null)
088. throw new IllegalArgumentException("Interface class == null");
089. if (! interfaceClass.isInterface())
090. throw new IllegalArgumentException("The " + interfaceClass.getName() + " must be interface class!");
091. if (host == null || host.length() == 0)
092. throw new IllegalArgumentException("Host == null!");
093. if (port &lt;= 0 || port &gt; 65535)
094. throw new IllegalArgumentException("Invalid port " + port);
095. System.out.println("Get remote service " + interfaceClass.getName() + " from server " + host + ":" + port);
096. return (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class&lt;?&gt;\[] {interfaceClass}, new InvocationHandler() {
097. public Object invoke(Object proxy, Method method, Object\[] arguments) throws Throwable {
098. Socket socket = new Socket(host, port);
099. try {
100. ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
101. try {
102. output.writeUTF(method.getName());
103. output.writeObject(method.getParameterTypes());
104. output.writeObject(arguments);
105. ObjectInputStream input = new ObjectInputStream(socket.getInputStream());
106. try {
107. Object result = input.readObject();
108. if (result instanceof Throwable) {
109. throw (Throwable) result;
110. }
111. return result;
112. } finally {
113. input.close();
114. }
115. } finally {
116. output.close();
117. }
118. } finally {
119. socket.close();
120. }
121. }
122. });
123. }
124. }

用起来也像模像样： 

**(1) 定义服务接口** 

Java代码  [![收藏代码](http://javatar.iteye.com/images/icon_star.png)]()

01. /*
02. * Copyright 2011 Alibaba.com All right reserved. This software is the
03. * confidential and proprietary information of Alibaba.com ("Confidential
04. * Information"). You shall not disclose such Confidential Information and shall
05. * use it only in accordance with the terms of the license agreement you entered
06. * into with Alibaba.com.
07. \*/
08. package com.alibaba.study.rpc.test;
09. /\**
10. * HelloService
11. \*
12. * @author william.liangf
13. \*/
14. public interface HelloService {
15. String hello(String name);
16. }

**(2) 实现服务** 

Java代码  [![收藏代码](http://javatar.iteye.com/images/icon_star.png)]()

01. /*
02. * Copyright 2011 Alibaba.com All right reserved. This software is the
03. * confidential and proprietary information of Alibaba.com ("Confidential
04. * Information"). You shall not disclose such Confidential Information and shall
05. * use it only in accordance with the terms of the license agreement you entered
06. * into with Alibaba.com.
07. \*/
08. package com.alibaba.study.rpc.test;
09. /\**
10. * HelloServiceImpl
11. \*
12. * @author william.liangf
13. \*/
14. public class HelloServiceImpl implements HelloService {
15. public String hello(String name) {
16. return "Hello " + name;
17. }
18. }

**(3) 暴露服务** 

Java代码  [![收藏代码](http://javatar.iteye.com/images/icon_star.png)]()

01. /*
02. * Copyright 2011 Alibaba.com All right reserved. This software is the
03. * confidential and proprietary information of Alibaba.com ("Confidential
04. * Information"). You shall not disclose such Confidential Information and shall
05. * use it only in accordance with the terms of the license agreement you entered
06. * into with Alibaba.com.
07. \*/
08. package com.alibaba.study.rpc.test;
09. import com.alibaba.study.rpc.framework.RpcFramework;
10. /\**
11. * RpcProvider
12. \*
13. * @author william.liangf
14. \*/
15. public class RpcProvider {
16. public static void main(String\[] args) throws Exception {
17. HelloService service = new HelloServiceImpl();
18. RpcFramework.export(service, 1234);
19. }
20. }

**(4) 引用服务** 

Java代码  [![收藏代码](http://javatar.iteye.com/images/icon_star.png)]()

01. /*
02. * Copyright 2011 Alibaba.com All right reserved. This software is the
03. * confidential and proprietary information of Alibaba.com ("Confidential
04. * Information"). You shall not disclose such Confidential Information and shall
05. * use it only in accordance with the terms of the license agreement you entered
06. * into with Alibaba.com.
07. \*/
08. package com.alibaba.study.rpc.test;
09. import com.alibaba.study.rpc.framework.RpcFramework;
10. /\**
11. * RpcConsumer
12. \*
13. * @author william.liangf
14. \*/
15. public class RpcConsumer {
16. public static void main(String\[] args) throws Exception {
17. HelloService service = RpcFramework.refer(HelloService.class, "127.0.0.1", 1234);
18. for (int i = 0; i &lt; Integer.MAX\_VALUE; i ++) {
19. String hello = service.hello("World" + i);
20. System.out.println(hello);
21. Thread.sleep(1000);
22. }
23. }
24. }

&lt;iframe id="aswift\_0" style="left: 0px; position: absolute; top: 0px;" name="aswift\_0" frameborder="0" marginwidth="0" marginheight="0" scrolling="no" width="728" height="90"&gt;&lt;/iframe&gt;