本文转自Dubbo作者梁飞大神的CSDN(https://javatar.iteye.com/blog/1123915),代码简洁,五脏俱全.

1.首先实现RpcFramework,实现服务的暴露与引用功能.

 package com.zxd.dubbo.learning.rpc.framework;

 import java.io.IOException;
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; /**
* @Project DubboLearning
* @Package com.zxd.dubbo.learning.rpc.framework
* @Author:zouxiaodong
* @Description:
* @Date:Created in 14:32 2018/10/24.
*/
public class RpcFramework { /**
* @FileName RpcFramework.java
* @ClassName RpcFramework
* @MethodName export
* @Desc 暴露服务
* @author zouxiaodong
* @date 2018/10/24 15:06
* @Params [service 服务实现, port 服务端口]
* @return void
*/
public static void export(final Object service,int port) throws IOException {
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 serverSocket = new ServerSocket(port);
while (true){
try {
final Socket socket = serverSocket.accept();
new Thread(new Runnable() {
@Override
public void run() {
ObjectInputStream input = null;
ObjectOutputStream output = null;
try {
input = new ObjectInputStream(socket.getInputStream());
String methodName = input.readUTF();
Class<?>[] parameterTypes = (Class<?>[]) input.readObject();
Object[] arguments = (Object[]) input.readObject();
output = new ObjectOutputStream(socket.getOutputStream());
Method method = service.getClass().getMethod(methodName,parameterTypes);
Object result = method.invoke(service,arguments);
output.writeObject(result);
} catch (Exception e) {
System.err.println("1."+e.getMessage());
}finally {
try {
if(output != null){
output.close();
}
if(input != null){
input.close();
}
if(socket != null){
socket.close();
}
} catch (IOException e) {
System.err.println("2."+e.getMessage());
}
}
}
}).start();
}catch (Exception e){ }
}
} /**
* @FileName RpcFramework.java
* @ClassName RpcFramework
* @MethodName refer
* @Desc 引用服务
* @author zouxiaodong
* @date 2018/10/24 15:32
* @Params [interfaceClass 接口类型, host 服务器主机名, port 服务器端口]
* @return T 远程服务
*/
public static <T> T refer(final Class<T> interfaceClass,final String host,final int port){
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() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Socket socket = new Socket(host,port);
ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
output.writeUTF(method.getName());
output.writeObject(method.getParameterTypes());
output.writeObject(args);
ObjectInputStream input = new ObjectInputStream(socket.getInputStream());
try {
Object result = input.readObject();
if(result instanceof Throwable){
throw (Throwable)result;
}
return result;
}finally {
input.close();
output.close();
socket.close();
}
}
});
}
}

2.编写接口HelloService.java与实现类HelloServiceImpl.java

 package com.zxd.dubbo.learning.rpc.framework;

 /**
* @Project DubboLearning
* @Package com.zxd.dubbo.learning.rpc.framework.api
* @Author:zouxiaodong
* @Description:
* @Date:Created in 15:50 2018/10/24.
*/
public interface HelloService {
String hello(String name);
}
 package com.zxd.dubbo.learning.rpc.framework;

 /**
* @Project DubboLearning
* @Package com.zxd.dubbo.learning.rpc.framework.impl
* @Author:zouxiaodong
* @Description:
* @Date:Created in 15:51 2018/10/24.
*/
public class HelloServiceImpl implements HelloService {
@Override
public String hello(String name) {
return "Hello "+name;
}
}

3.编写提供者(暴露服务)

 package com.zxd.dubbo.learning.rpc.framework;

 import java.io.IOException;

 /**
* @Project DubboLearning
* @Package com.zxd.dubbo.learning.rpc.framework
* @Author:zouxiaodong
* @Description:
* @Date:Created in 15:54 2018/10/24.
*/
public class RpcProvider {
public static void main(String[] args) throws IOException {
HelloService helloService = new HelloServiceImpl();
RpcFramework.export(helloService,12345);
}
}

4.编写消费者(引用服务)

 package com.zxd.dubbo.learning.rpc.framework;

 /**
* @Project DubboLearning
* @Package com.zxd.dubbo.learning.rpc.framework
* @Author:zouxiaodong
* @Description:
* @Date:Created in 15:55 2018/10/24.
*/
public class RpcConsumer {
public static void main(String[] args){
HelloService helloService = RpcFramework.refer(HelloService.class,"127.0.0.1",12345);
String result = helloService.hello("CoderZZ");
System.out.println(result);
}
}

最新文章

  1. 关于JavaScript预编译和执行顺序以及函数引用类型的思考
  2. 关于Java占用内存的研究
  3. 第六百零九天 how can I 坚持
  4. 刚看到的感觉会用的到 收藏一下 常用的iOS第三方资源 (转)
  5. [问题2014A01] 复旦高等代数 I(14级)每周一题(第三教学周)
  6. Perl中的特殊内置变量详解
  7. 4、什么构成了我们Android应用程序?(七大件)
  8. [Linked List]Reverse Nodes in k-Group
  9. eclipse中console的输出行数控制
  10. [2017-08-07]ABP系列——QuickStartA:概述、思想、入门和HelloWorld
  11. 【Qt编程】基于Qt的词典开发系列&lt;五&gt;--无边框窗口的拖动
  12. Spring中使用的设计模式
  13. es6常用的
  14. Testner测试圈关于页面响应时间的测试行业标准
  15. 小程序[publib]:1 request:fail ssl hand shake error 如果用的是阿里云和宝塔那么如下解决
  16. Windows在当前目录打开cmd
  17. 在CentOS6.5上安装/启动PostgreSQL
  18. struts2系列(一):struts2入门(struts2的产生、struts2的工作流程、搭建struts2开发环境)
  19. idea中spring boot启动后无法访问jsp
  20. YARN与MapReduce1的对比

热门文章

  1. 设置Python打印格式
  2. 冲刺阶段——Day5
  3. H264基础简介
  4. getBoundingClientRect使用指南
  5. js常用时间转换函数
  6. 阶段5 3.微服务项目【学成在线】_day04 页面静态化_10-freemarker静态化测试-基于模板文件静态化
  7. REPLACE 语法
  8. 在MFC中添加OpenGL窗口
  9. kindeditor 在JSP 中上传文件的配置
  10. C#实现多线程的方式:Task——任务