一个简单的rpc框架的实现


http://chenkangxian.iteye.com/blog/1531074


 

为了降低开发成本,提升已有系统的利用率,企业往往会构建自己的SOA体系结构,SOA构建的手段有多种,可以通过webservice,restful,rmi,socket等等,笔者通过java socket,来构建一个简单的SOA体系结构,以下代码仅供参考。

 

 

1.  需要实现SOA的服务接口

 

Java代码   收藏代码
  1. package com.chenkangxian.rpc.impl;  
  2.   
  3. /** 
  4.  * 
  5.  * @Author: chenkangxian 
  6.  * 
  7.  * @Annotation: 根据key取数据接口 
  8.  * 
  9.  * @Date:2012-5-13 
  10.  * 
  11.  * @Copyright: 2012 chenkangxian, All rights reserved. 
  12.  * 
  13.  */  
  14.   
  15. public interface DataService {  
  16.   
  17.     String getData(String key);  
  18.   
  19. }  

 

2.   接口的实现

 

 

Java代码   收藏代码
  1. package com.chenkangxian.rpc.impl;  
  2.   
  3. /** 
  4.  * 
  5.  * @Author: chenkangxian 
  6.  * 
  7.  * @Annotation: 根据key取数据服务实现 
  8.  * 
  9.  * @Date:2012-5-13 
  10.  * 
  11.  * @Copyright: 2012 chenkangxian, All rights reserved. 
  12.  * 
  13.  */  
  14. public class DataServiceImpl implements DataService {  
  15.   
  16.     public String getData(String key) {  
  17.           
  18.         return "this is the data when key = " + key ;  
  19.     }  
  20.   
  21. }  
 

 

3.  执行代理

 

 

Java代码   收藏代码
  1. /** 
  2.  *  
  3.  */  
  4. package com.chenkangxian.rpc.impl;  
  5.   
  6. import java.io.ObjectInputStream;  
  7. import java.io.ObjectOutputStream;  
  8. import java.lang.reflect.InvocationHandler;  
  9. import java.lang.reflect.Method;  
  10. import java.net.Socket;  
  11.   
  12. /** 
  13.  * @Author: chenkangxian 
  14.  * 
  15.  * @Annotation: 执行代理 
  16.  * 
  17.  * @Date:2012-5-15 
  18.  * 
  19.  * @Copyright: 2012 chenkangxian, All rights reserved. 
  20.  *  
  21.  */  
  22. public class InvocationProxy implements InvocationHandler{  
  23.   
  24.     private String host;  
  25.     private int port;  
  26.   
  27.     public InvocationProxy(String host, int port){  
  28.         this.host = host;  
  29.         this.port = port;  
  30.     }  
  31.   
  32.     public Object invoke(Object proxy, Method method, Object[] arguments) throws Throwable {  
  33.         Socket socket = new Socket(host, port);  
  34.         try {  
  35.             ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());  
  36.             try {  
  37.                 output.writeUTF(method.getName());  
  38.                 output.writeObject(method.getParameterTypes());  
  39.                 output.writeObject(arguments);  
  40.                 ObjectInputStream input = new ObjectInputStream(socket.getInputStream());  
  41.                 try {  
  42.                     Object result = input.readObject();  
  43.                     if (result instanceof Throwable) {  
  44.                         throw (Throwable) result;  
  45.                     }  
  46.                     return result;  
  47.                 } finally {  
  48.                     input.close();  
  49.                 }  
  50.             } finally {  
  51.                 output.close();  
  52.             }  
  53.         } finally {  
  54.             socket.close();  
  55.         }  
  56.     }  
  57. }  

 

4.    服务消费者

 

 

Java代码   收藏代码
  1. package com.chenkangxian.rpc.impl;  
  2.   
  3. /** 
  4.  * @Author: chenkangxian 
  5.  * 
  6.  * @Annotation: 服务消费者 
  7.  * 
  8.  * @Date:2012-5-13 
  9.  * 
  10.  * @Copyright: 2012 chenkangxian, All rights reserved. 
  11.  * 
  12.  */  
  13. public class RpcConsumer {  
  14.       
  15.     public static void main(String[] args) throws Exception {  
  16.         DataService service = RpcFramework.refer(DataService.class"127.0.0.1"1234);  
  17.         for (int i = 0; i < Integer.MAX_VALUE; i ++) {  
  18.             String value = service.getData("key_" + i);  
  19.             System.out.println(value);  
  20.             Thread.sleep(1000);  
  21.         }  
  22.     }  
  23.       
  24. }  

 

5.    远程调用框架

 

 

Java代码   收藏代码
  1. package com.chenkangxian.rpc.impl;  
  2.   
  3. import java.lang.reflect.Proxy;  
  4. import java.net.ServerSocket;  
  5. import java.net.Socket;  
  6.   
  7. /** 
  8.  * 
  9.  * @Author: chenkangxian 
  10.  * 
  11.  * @Annotation: 简单的远程调用框架实现 
  12.  * 
  13.  * @Date:2012-5-13 
  14.  * 
  15.  * @Copyright: 2012 chenkangxian, All rights reserved. 
  16.  * 
  17.  */  
  18. public class RpcFramework {  
  19.       
  20.     /** 
  21.      * 暴露服务 
  22.      *  
  23.      * Author: chenkangxian 
  24.      * 
  25.      * Last Modification Time: 2012-5-15 
  26.      * 
  27.      * @param service 服务实现 
  28.      * @param port 服务端口 
  29.      * @throws Exception 
  30.      */  
  31.     public static void export(final Object service, int port) throws Exception {  
  32.         if (service == null)  
  33.             throw new IllegalArgumentException("service instance == null");  
  34.         if (port <= 0 || port > 65535)  
  35.             throw new IllegalArgumentException("Invalid port " + port);  
  36.         System.out.println("Export service " + service.getClass().getName() + " on port " + port);  
  37.         ServerSocket server = new ServerSocket(port);  
  38.         for(;;) {  
  39.             try {  
  40.                 final Socket socket = server.accept();  
  41.                 ThreadPoolHelp.getExecutorInstance().execute(new WorkThread(service, socket));  
  42.             } catch (Exception e) {  
  43.                 e.printStackTrace();  
  44.             }  
  45.         }  
  46.     }  
  47.   
  48.     /** 
  49.      * 引用服务 
  50.      *  
  51.      * Author: chenkangxian 
  52.      * 
  53.      * Last Modification Time: 2012-5-15 
  54.      * 
  55.      * @param <T> 接口泛型 
  56.      * @param interfaceClass 接口类型 
  57.      * @param host 服务器主机名 
  58.      * @param port 服务器端口 
  59.      * @return 远程服务 
  60.      * @throws Exception 
  61.      */  
  62.     @SuppressWarnings("unchecked")  
  63.     public static <T> T refer(final Class<T> interfaceClass, final String host, final int port) throws Exception {  
  64.           
  65.         if (interfaceClass == null)  
  66.             throw new IllegalArgumentException("Interface class == null");  
  67.         if (! interfaceClass.isInterface())  
  68.             throw new IllegalArgumentException("The " + interfaceClass.getName() + " must be interface class!");  
  69.         if (host == null || host.length() == 0)  
  70.             throw new IllegalArgumentException("Host == null!");  
  71.         if (port <= 0 || port > 65535)  
  72.             throw new IllegalArgumentException("Invalid port " + port);  
  73.           
  74.         System.out.println("Get remote service " + interfaceClass.getName() + " from server " + host + ":" + port);  
  75.           
  76.         return (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class<?>[] {interfaceClass}, new InvocationProxy(host,port));  
  77.     }  
  78.   
  79. }  

 

 

6.    服务提供者

 

 

Java代码   收藏代码
  1. package com.chenkangxian.rpc.impl;  
  2.   
  3. /** 
  4.  * @Author: chenkangxian 
  5.  * 
  6.  * @Annotation: 服务提供者 
  7.  * 
  8.  * @Date:2012-5-13 
  9.  * 
  10.  * @Copyright: 2012 chenkangxian, All rights reserved. 
  11.  * 
  12.  */  
  13. public class RpcProvider {  
  14.   
  15.     public static void main(String[] args) throws Exception {  
  16.         DataService service = new DataServiceImpl();  
  17.         RpcFramework.export(service, 1234);  
  18.     }  
  19.   
  20. }  

 

7.    线程池帮助类

 

 

Java代码   收藏代码
  1. /** 
  2.  *  
  3.  */  
  4. package com.chenkangxian.rpc.impl;  
  5.   
  6. import java.util.concurrent.ExecutorService;  
  7. import java.util.concurrent.Executors;  
  8.   
  9. /** 
  10.  * @Author: chenkangxian 
  11.  * 
  12.  * @Annotation:  线程池帮助类 
  13.  * 
  14.  * @Date:2012-5-15 
  15.  * 
  16.  * @Copyright: 2012 chenkangxian, All rights reserved. 
  17.  *  
  18.  */  
  19. public class ThreadPoolHelp {  
  20.   
  21.     private static ExecutorService executor ;  
  22.       
  23.     static{  
  24.         executor = Executors.newFixedThreadPool(20);  
  25.     }  
  26.       
  27.     public static ExecutorService getExecutorInstance(){  
  28.         return executor;  
  29.     }  
  30. }  

 

 

8.    工作线程

 

 

Java代码   收藏代码
  1. /** 
  2.  *  
  3.  */  
  4. package com.chenkangxian.rpc.impl;  
  5.   
  6. import java.io.ObjectInputStream;  
  7. import java.io.ObjectOutputStream;  
  8. import java.lang.reflect.Method;  
  9. import java.net.Socket;  
  10.   
  11. /** 
  12.  * 
  13.  * @Author: chenkangxian 
  14.  * 
  15.  * @Annotation: 工作线程 
  16.  * 
  17.  * @Date:2012-5-15 
  18.  * 
  19.  * @Copyright: 2012 chenkangxian, All rights reserved. 
  20.  *  
  21.  */  
  22. public class WorkThread implements Runnable {  
  23.       
  24.     private Object service;  
  25.       
  26.     private Socket socket;  
  27.       
  28.     public WorkThread(Object service,Socket socket){  
  29.         this.service = service;  
  30.         this.socket = socket;  
  31.     }  
  32.   
  33.     @Override  
  34.     public void run() {  
  35.         try {  
  36.             try {  
  37.                 ObjectInputStream input = new ObjectInputStream(socket.getInputStream());  
  38.                 try {  
  39.                     String methodName = input.readUTF();  
  40.                     Class<?>[] parameterTypes = (Class<?>[])input.readObject();  
  41.                     Object[] arguments = (Object[])input.readObject();  
  42.                     ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());  
  43.                     try {  
  44.                         Method method = service.getClass().getMethod(methodName, parameterTypes);  
  45.                         Object result = method.invoke(service, arguments);  
  46.                         output.writeObject(result);  
  47.                     } catch (Throwable t) {  
  48.                         output.writeObject(t);  
  49.                     } finally {  
  50.                         output.close();  
  51.                     }  
  52.                 } finally {  
  53.                     input.close();  
  54.                 }  
  55.             } finally {  
  56.                 socket.close();  
  57.             }  
  58.         } catch (Exception e) {  
  59.             e.printStackTrace();  
  60.         }  
  61.     }  
  62.   
  63. }  
 

 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值