java 远程调用及动态代理的应用

来源:互联网 发布:mac选择office安装路径 编辑:程序博客网 时间:2024/05/29 15:09

动态代理:可以看看这篇文章

Java远程调用-实现一个简单的服务框架:可以看这篇文章

主要通过socket通讯传递系列化的参数类型和参数,客户端定义和服务器一样的接口,服务器端要实现接口,客户端调用本地接口通过动态代理把调用的方法名称、参数类型、参数发送到服务器,服务器根据参数获取实例指定方法执行并把执行结果发送给客户端。

下面是完整代码

服务器端代码:

MethodService.java

import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.lang.reflect.Method;import java.net.ServerSocket;import java.net.Socket;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import org.omg.CosNaming.NamingContextExtPackage.AddressHelper;public class MethodService {/**  * 发布服务  *   * @param service  *            服务实现  * @param port  *            服务端口  * @throws Exception  */  public static void export(final Object service, final 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);              /* 服务端socket,最多同时处理1000个服务请求 */      ServerSocket server = new ServerSocket(port, 1000);      ExecutorService executor = Executors.newCachedThreadPool();      ;      for (;;) {        try {            // 监听client socket请求              final Socket socket = server.accept();              executor.execute(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 {                            if (socket != null) {                                socket.close();                              }                        }                    } catch (Exception e) {                        e.printStackTrace();                      }                }            });        } catch (Exception e) {            e.printStackTrace();          }    }}public static void main(String[] args) {Service service = new Service();try {export(service, 1234);} catch (Exception e) {// TODO 自动生成的 catch 块e.printStackTrace();}}}
//远程调用的方法定义接口interface MethodInteface{public String sayHello(String name);public int add(int a, int b);}
//远程调用的方法定义接口实现
class Service implements MethodInteface{public String sayHello(String name) {return "Hello,"+name;}public int add(int a, int b){return a+b;}}


客户端代码:

RemoteCall.java

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.InetSocketAddress;import java.net.Socket;interface MethodInteface{public String sayHello(String name);public int add(int a, int b);}public class RemoteCall {public static void main(String[] args) {// TODO 自动生成的方法存根try {MethodInteface methodInteface = refer(MethodInteface.class, "127.0.0.1", 1234);System.out.println(methodInteface.sayHello("HeRui"));System.out.println(methodInteface.add(1223, 1001));} catch (Exception e) {// TODO 自动生成的 catch 块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 socket = new Socket(host, port);Socket socket = new Socket();// socket.close()执行时 若数据没有发送完成则阻塞 10秒socket.setSoLinger(true, 10);socket.connect(new InetSocketAddress(host, port));try {// 往socket写数据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 {if (output != null) {output.close();}}} finally {if (socket != null) {socket.close();}}}});}}