码迷,mamicode.com
首页 > 编程语言 > 详细

java socket 简单实现的rpc

时间:2015-08-03 20:35:23      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:

关于rpc的介绍就不多说了,不了解可以问问度娘。。。直接上代码

rpc基本框架实现类:

  1 package rpc;
  2 import java.io.ObjectInputStream;
  3 import java.io.ObjectOutputStream;
  4 import java.lang.reflect.InvocationHandler;
  5 import java.lang.reflect.Method;
  6 import java.lang.reflect.Proxy;
  7 import java.net.ServerSocket;
  8 import java.net.Socket;
  9 
 10 /**
 11  * RpcFramework
 12  * 
 13  */
 14 public class RpcFramework {
 15 
 16     /**
 17      * 暴露服务
 18      * 
 19      * @param service 服务实现
 20      * @param port 服务端口
 21      * @throws Exception
 22      */
 23     public static void export(final Object service, int port) throws Exception {
 24         if (service == null)
 25             throw new IllegalArgumentException("service instance == null");
 26         if (port <= 0 || port > 65535)
 27             throw new IllegalArgumentException("Invalid port " + port);
 28         System.out.println("Export service " + service.getClass().getName() + " on port " + port);
 29         ServerSocket server = new ServerSocket(port);
 30         for(;;) {
 31             try {
 32                 final Socket socket = server.accept();
 33                 new Thread(new Runnable() {
 34                     @Override
 35                     public void run() {
 36                         try {
 37                             try {
 38                                 ObjectInputStream input = new ObjectInputStream(socket.getInputStream());
 39                                 try {
 40                                     String methodName = input.readUTF();
 41                                     Class<?>[] parameterTypes = (Class<?>[])input.readObject();
 42                                     Object[] arguments = (Object[])input.readObject();
 43                                     ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
 44                                     try {
 45                                         Method method = service.getClass().getMethod(methodName, parameterTypes);
 46                                         Object result = method.invoke(service, arguments);
 47                                         output.writeObject(result);
 48                                     } catch (Throwable t) {
 49                                         output.writeObject(t);
 50                                     } finally {
 51                                         output.close();
 52                                     }
 53                                 } finally {
 54                                     input.close();
 55                                 }
 56                             } finally {
 57                                 socket.close();
 58                             }
 59                         } catch (Exception e) {
 60                             e.printStackTrace();
 61                         }
 62                     }
 63                 }).start();
 64             } catch (Exception e) {
 65                 e.printStackTrace();
 66             }
 67         }
 68     }
 69 
 70     /**
 71      * 引用服务
 72      * 
 73      * @param <T> 接口泛型
 74      * @param interfaceClass 接口类型
 75      * @param host 服务器主机名
 76      * @param port 服务器端口
 77      * @return 远程服务
 78      * @throws Exception
 79      */
 80     @SuppressWarnings("unchecked")
 81     public static <T> T refer(final Class<T> interfaceClass, final String host, final int port) throws Exception {
 82         if (interfaceClass == null)
 83             throw new IllegalArgumentException("Interface class == null");
 84         if (! interfaceClass.isInterface())
 85             throw new IllegalArgumentException("The " + interfaceClass.getName() + " must be interface class!");
 86         if (host == null || host.length() == 0)
 87             throw new IllegalArgumentException("Host == null!");
 88         if (port <= 0 || port > 65535)
 89             throw new IllegalArgumentException("Invalid port " + port);
 90         System.out.println("Get remote service " + interfaceClass.getName() + " from server " + host + ":" + port);
 91         return (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class<?>[] {interfaceClass}, new InvocationHandler() {
 92             public Object invoke(Object proxy, Method method, Object[] arguments) throws Throwable {
 93                 Socket socket = new Socket(host, port);
 94                 try {
 95                     ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
 96                     try {
 97                         output.writeUTF(method.getName());
 98                         output.writeObject(method.getParameterTypes());
 99                         output.writeObject(arguments);
100                         ObjectInputStream input = new ObjectInputStream(socket.getInputStream());
101                         try {
102                             Object result = input.readObject();
103                             if (result instanceof Throwable) {
104                                 throw (Throwable) result;
105                             }
106                             return result;
107                         } finally {
108                             input.close();
109                         }
110                     } finally {
111                         output.close();
112                     }
113                 } finally {
114                     socket.close();
115                 }
116             }
117         });
118     }
119 
120 }

2.定义接口服务

package rpc;

/**
 * HelloService
 * 

 */
public interface HelloService {

    String hello(String name);

}

3.实现服务 

package rpc;

/**
 * HelloServiceImpl
 * 
 */
public class HelloServiceImpl implements HelloService {

    public String hello(String name) {
        return "Hello " + name;
    }

}

4.暴露服务 

package rpc;


/**
 * RpcProvider
 * 
 */
public class RpcProvider {

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

}

5. 引用服务 

package rpc;

/**
 * RpcConsumer
 * 
 */
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);
        }
    }
    
}

 

java socket 简单实现的rpc

标签:

原文地址:http://www.cnblogs.com/wzw1989/p/4700082.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!