RpcFramework

 /*
* Copyright 2011 Alibaba.com All right reserved. This software is the
* confidential and proprietary information of Alibaba.com ("Confidential
* Information"). You shall not disclose such Confidential Information and shall
* use it only in accordance with the terms of the license agreement you entered
* into with Alibaba.com.
*/
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.ServerSocket;
import java.net.Socket; /**
* RpcFramework
*
* @author william.liangf
*/
public class RpcFramework { /**
* 暴露服务
*
* @param service 服务实现
* @param port 服务端口
* @throws Exception
*/
public static void export(final Object service, int port) throws Exception {
if (service == null)
throw new IllegalArgumentException("service instance == null");
if (port <= 0 || port > 65535)
throw new IllegalArgumentException("Invalid port " + port);
System.out.println("Export service " + service.getClass().getName() + " on port " + port);
ServerSocket server = new ServerSocket(port);
for(;;) {
try {
final Socket socket = server.accept();
new Thread(new Runnable() {
@Override
public void run() {
try {
try {
ObjectInputStream input = new ObjectInputStream(socket.getInputStream());
try {
String methodName = input.readUTF();
Class<?>[] parameterTypes = (Class<?>[])input.readObject();
Object[] arguments = (Object[])input.readObject();
ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
try {
Method method = service.getClass().getMethod(methodName, parameterTypes);
Object result = method.invoke(service, arguments);
output.writeObject(result);
} catch (Throwable t) {
output.writeObject(t);
} finally {
output.close();
}
} finally {
input.close();
}
} finally {
socket.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
} catch (Exception e) {
e.printStackTrace();
}
}
} /**
* 引用服务
*
* @param <T> 接口泛型
* @param interfaceClass 接口类型
* @param host 服务器主机名
* @param port 服务器端口
* @return 远程服务
* @throws Exception
*/
@SuppressWarnings("unchecked")
public static <T> T refer(final Class<T> interfaceClass, final String host, final int port) throws Exception {
if (interfaceClass == null)
throw new IllegalArgumentException("Interface class == null");
if (! interfaceClass.isInterface())
throw new IllegalArgumentException("The " + interfaceClass.getName() + " must be interface class!");
if (host == null || host.length() == 0)
throw new IllegalArgumentException("Host == null!");
if (port <= 0 || port > 65535)
throw new IllegalArgumentException("Invalid port " + port);
System.out.println("Get remote service " + interfaceClass.getName() + " from server " + host + ":" + port);
return (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class<?>[] {interfaceClass}, new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] arguments) throws Throwable {
Socket socket = new Socket(host, port);
try {
ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
try {
output.writeUTF(method.getName());
output.writeObject(method.getParameterTypes());
output.writeObject(arguments);
ObjectInputStream input = new ObjectInputStream(socket.getInputStream());
try {
Object result = input.readObject();
if (result instanceof Throwable) {
throw (Throwable) result;
}
return result;
} finally {
input.close();
}
} finally {
output.close();
}
} finally {
socket.close();
}
}
});
} }

RpcFramework

RpcProvider

 public class RpcProvider {
public static void main(String[] args) throws Exception {
HelloService service = new HelloServiceImpl();
RpcFramework.export(service, 1234);
}
}

RpcProvider

HelloService

 public interface HelloService {
String hello(String name);
}

HelloService

HelloServiceImpl

 /*
* Copyright 2011 Alibaba.com All right reserved. This software is the
* confidential and proprietary information of Alibaba.com ("Confidential
* Information"). You shall not disclose such Confidential Information and shall
* use it only in accordance with the terms of the license agreement you entered
* into with Alibaba.com.
*/
/**
* HelloServiceImpl
*
* @author william.liangf
*/
public class HelloServiceImpl implements HelloService { public String hello(String name) {
return "Hello " + name;
} }

HelloServiceImpl

RpcConsumer

 /*
* Copyright 2011 Alibaba.com All right reserved. This software is the
* confidential and proprietary information of Alibaba.com ("Confidential
* Information"). You shall not disclose such Confidential Information and shall
* use it only in accordance with the terms of the license agreement you entered
* into with Alibaba.com.
*/ /**
* RpcConsumer
*
* @author william.liangf
*/
public class RpcConsumer { public static void main(String[] args) throws Exception {
HelloService service = RpcFramework.refer(HelloService.class, "127.0.0.1", 1234);
for (int i = 0; i < Integer.MAX_VALUE; i ++) {
String hello = service.hello("World" + i);
System.out.println(hello);
Thread.sleep(1000);
}
} }

RpcConsumer

实际上,RPC的原理其实很简单: 
服务器启动了一个线程监听 Socket 端口, 
有Socket访问了, 反序列化解析出
调用哪个Service 哪个 方法, 以及传入的 参数,
再用Socket 写回去.

客户端 利用 Jdk 的Proxy 生成了一个代理类,
在创建 Proxy 时建立与服务器的Socket连接.
调用 Proxy 的方法时, 向服务器发送数据, 等待结果返回.

rpc 小例子的更多相关文章

  1. Hadoop中RPC协议小例子报错java.lang.reflect.UndeclaredThrowableException解决方法

    最近在学习传智播客吴超老师的Hadoop视频,里面他在讲解RPC通信原理的过程中给了一个RPC的小例子,但是自己编写的过程中遇到一个小错误,整理如下: log4j:WARN No appenders ...

  2. 在开发环境中,自己搭建一个ssl环境(小例子)

    做项目的时候自己总结的一些小例子 public class Test { public static void setSSLProperty() { Security.addProvider(new  ...

  3. springmvc入门的第一个小例子

    今天我们探讨一下springmvc,由于是初学,所以简单的了解一下 springmvc的流程,后续会持续更新... 由一个小例子来简单的了解一下 springmvc springmvc是spring框 ...

  4. java即时通信小例子

    学习java一段时间了,今天写来一个即时通信的小例子练手在其过程中也学到了一些知识拿出来和大家分享,请路过的各位大神多多赐教... 好了下面讲一下基本的思路: 首先,编写服务器端的程序,简单点说吧就是 ...

  5. Runtime的几个小例子(含Demo)

    一.什么是runtime(也就是所谓的“运行时”,因为是在运行时实现的.)           1.runtime是一套底层的c语言API(包括很多强大实用的c语言类型,c语言函数);  [runti ...

  6. bootstrap 模态 modal 小例子

    bootstrap 模态 modal  小例子 <html> <head> <meta charset="utf-8" /> <title ...

  7. INI配置文件分析小例子

    随手写个解析INI配置字符串的小例子 带测试 #include <iostream> #include <map> #include <string> #inclu ...

  8. JavaScript小例子:复选框全选

    JavaScript小例子:复选框全选 这只是一个小例子,很简单,但是这个功能还是很常用的: 实现后效果如图: JavaScript代码: <script type="text/jav ...

  9. 【zTree】 zTree使用的 小例子

    使用zTree树不是第一次了  但是 还是翻阅着之前做的 对照着 使用起来比较方便  这里就把小例子列出来   总结一下使用步骤 这样方便下次使用起来方便一点 使用zTree树的步骤: 1.首先  在 ...

随机推荐

  1. 在EF的code frist下写稳健的权限管理系统:仓储设计(三)

    public class BaseRepository<T>:IBaseRepository<T> where T : class { protected EfConnecti ...

  2. WPF工作笔记:本地化支持、主进程通知、两种最常用异步编程方式

    1.本地化支持 (1)重写控件默认的依赖属性LanguageProperty FrameworkElement.LanguageProperty.OverrideMetadata( typeof(Fr ...

  3. hdu 4631Sad Love Story<计算几何>

    链接:http://acm.hdu.edu.cn/showproblem.php?pid=4631 题意:依次给你n个点,每次求出当前点中的最近点对,输出所有最近点对的和: 思路:按照x排序,然后用s ...

  4. SQL中的内连接外连接和交叉连接是什么意思?

    内连接又分为等值连接.自然连接和不等连接三种. 外连接分为左外连接(LEFT OUTER JOIN或LEFT JOIN).右外连接(RIGHT OUTER JOIN或RIGHT JOIN)和全外连接( ...

  5. UIButton之Block回调

    本文主要介绍了两种改写UIButton的点击事件方法——继承UIButton跟给UIButton添加一个分类.附代码 方法一:继承UIButton UIButtonBlock.h文件 如下 #impo ...

  6. MYSQL主键存在则更新,不存在则插入的解决方案(ON DUPLICATE KEY UPDATE)

    经常我们使用的最简单的数据库操作就是数据的更新,删除和插入,对于批量删除和插入的方法相信大家都很清楚,那么批量更新估计有的人就不知道了,并且还有批量插入,在插入时若有主键冲突则更新的操作,这在EAV模 ...

  7. json 读写 swift

    // // ViewController.swift // json读写 // // Created by mac on 15/7/14. // Copyright (c) 2015年 fangyuh ...

  8. loadView, viewDidLoad 快速使用

    一  loadView: 在每次访问 UIViewController时,且其 view = nil 时,会调用这个方法,所以大家在开发中想自己设置 view 的可以用这个方法,在这个方法中自定义 v ...

  9. BICEP单元测试计划——四则运算Ⅱ

    一.测试方法(Right-BICEP) 6个值得测试的具体部位: Right-结果是否正确? B-是否所有的边界条件都是正确的? I-能查一下反向关联吗? C-能用其他手段交叉检查一下结果吗? E-你 ...

  10. CRT团队组员博客地址统计

    CRT团队GitHub地址:https://github.com/CoffeeRobotTeam/Coffee-Robot-System 洪超 http://www.cnblogs.com/chaoh ...