java rmi

什么是RMI,请参考看RMI远程调用部分

额,很多人都说RMI没什么用,直接使用WebService就可以了。但是我觉得使用一些简单的,只用于自己开发的系列JAVA软件之间的远程调用的时候RMI还是具有自己的优势的,所以本人就做了一些研究,在网上参考了很多例子,想办法做到安全的RMI远程调用。

一、简单的例子,通过这个例子,首先可以使搭建一个简单的RMI的调用环境。

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package rmiproj.server;  
  2.   
  3. import java.io.Serializable;  
  4.   
  5. public class Channel implements Serializable {  
  6.   
  7.     /** 
  8.      * 用来测试的实体类,主要用来存放数据 
  9.      */  
  10.     private static final long serialVersionUID = 1L;  
  11.     private int id;  
  12.     private String name;  
  13.   
  14.     public int getId() {  
  15.         return id;  
  16.     }  
  17.   
  18.     public void setId(int id) {  
  19.         this.id = id;  
  20.     }  
  21.   
  22.     public String getName() {  
  23.         return name;  
  24.     }  
  25.   
  26.     public void setName(String name) {  
  27.         this.name = name;  
  28.     }  
  29.   
  30.     public Channel(int id, String name) {  
  31.         super();  
  32.         this.id = id;  
  33.         this.name = name;  
  34.     }  
  35.   
  36. }  


[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package rmiproj.server;  
  2.   
  3. import java.rmi.Remote;  
  4. import java.rmi.RemoteException;  
  5. import java.util.List;  
  6.   
  7. /*这个接口是用来将远程端可以执行的方法暴露给客户端的,该接口必须继承Remote接口,并且接口中的每一个方法都必须抛出RemoteException*/  
  8. public interface ChannelManager extends Remote {  
  9.   
  10.     public List<Channel> getChannels() throws RemoteException;  
  11.   
  12. }  


[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package rmiproj.server;  
  2.   
  3. import java.rmi.RemoteException;  
  4. import java.rmi.server.UnicastRemoteObject;  
  5. import java.util.ArrayList;  
  6. import java.util.Date;  
  7. import java.util.List;  
  8.   
  9. /** 
  10.  * @author Administrator 
  11.  *  
  12.  *         这个类是ChannelManager的实现类,同时继承了UnicastRemoteObject,根据我的理解, 
  13.  *         继承了UnicastRemoteObject以后,该类就可以直接绑定到Registry上暴露自己的相关行为了, 
  14.  *         不需要在使用UnicastRemoteObject中的exportObject来暴露了 
  15.  * 
  16.  */  
  17. public class ChannelManagerImpl extends UnicastRemoteObject implements  
  18.         ChannelManager {  
  19.     private static final Object lock = new Object();  
  20.     private static ChannelManager instance;  
  21.   
  22.     protected ChannelManagerImpl() throws RemoteException {  
  23.         super();  
  24.     }  
  25.   
  26.     /** 
  27.      * 默认的id,因为继承了UnicastRemoteObject的原因,实现了Serializable接口 
  28.      */  
  29.     private static final long serialVersionUID = 1L;  
  30.   
  31.     /* 使用单例模式来获得该类的对象 */  
  32.     public static ChannelManager getInstance() throws RemoteException {  
  33.         if (instance == null) {  
  34.             synchronized (lock) {  
  35.                 if (instance == null)  
  36.                     instance = new ChannelManagerImpl();  
  37.             }  
  38.         }  
  39.         return instance;  
  40.     }  
  41.   
  42.     @Override  
  43.     public List<Channel> getChannels() throws RemoteException {  
  44.         List<Channel> channels = new ArrayList<Channel>();  
  45.         channels.add(new Channel(1"java"));  
  46.         channels.add(new Channel(2"php"));  
  47.         channels.add(new Channel(3"C"));  
  48.         channels.add(new Channel(4"ASP"));  
  49.         System.out.println(new Date() + " getChannels method called!");  
  50.         return channels;  
  51.     }  
  52.   
  53. }  

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package rmiproj.server;  
  2.   
  3. import java.net.MalformedURLException;  
  4. import java.rmi.Naming;  
  5. import java.rmi.RemoteException;  
  6. import java.rmi.registry.LocateRegistry;  
  7.   
  8. public class RMIServer {  
  9.   
  10.     /** 
  11.      * @param args 
  12.      */  
  13.     public static void main(String[] args) {  
  14.         System.out.println("RMI Server Starting...");  
  15.   
  16.         if (System.getSecurityManager() == null) {  
  17.             //这个方法是用来设置在远程调用的过程中使用的securityManager的,后面会用到  
  18.         }  
  19.   
  20.         try {  
  21.             //在1099端口上建立一个registry来供远程客户端调用,默认端口就是1099  
  22.             LocateRegistry.createRegistry(1099);  
  23.             //把要暴露给远程客户端的实体对象绑定一个特定的名字以后,绑定到1099端口的Registry上  
  24.             Naming.rebind("ChannelManager", ChannelManagerImpl.getInstance());  
  25.   
  26.         } catch (RemoteException e) {  
  27.             // TODO Auto-generated catch block  
  28.             e.printStackTrace();  
  29.         } catch (MalformedURLException e) {  
  30.             // TODO Auto-generated catch block  
  31.             e.printStackTrace();  
  32.         }  
  33.   
  34.         System.out.println("RMI Server ready...");  
  35.   
  36.     }  
  37. }  

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package rmiproj.client;  
  2.   
  3. import java.rmi.Naming;  
  4. import java.rmi.Remote;  
  5. import java.rmi.RemoteException;  
  6. import java.util.List;  
  7.   
  8. import rmiproj.server.Channel;  
  9. import rmiproj.server.ChannelManager;  
  10.   
  11. public class ClientUtil {  
  12.     /** 
  13.      * @param args 
  14.      */  
  15.     public static void main(String[] args) {  
  16.         // 这里的ChannelManager我使用的是服务器包里面的,在实际环境中,远程端要使用RMI,那么服务器端的接口远程段必须自己持有一份,这可能就是rmi的弊端之一  
  17.         ChannelManager cm = (ChannelManager) ClientUtil  
  18.                 .renewRMI("ChannelManager");  
  19.         List<Channel> channels;  
  20.   
  21.         try {  
  22.             channels = cm.getChannels();  
  23.             for (int i = 0; i < channels.size(); i++) {  
  24.                 Channel c = channels.get(i);  
  25.                 System.out.println(c.getId() + "-" + c.getName());  
  26.             }  
  27.         } catch (RemoteException e) {  
  28.             // TODO Auto-generated catch block  
  29.             e.printStackTrace();  
  30.         }  
  31.   
  32.     }  
  33.   
  34.     public static Remote renewRMI(String name) {  
  35.         try {  
  36.             if (System.getSecurityManager() == null) {  
  37.             }  
  38.             // 就是在这里,通过Naming。lookup,在指定的服务端获得了远程调用对象  
  39.             return Naming.lookup("rmi://127.0.0.1:1099/" + name);  
  40.         } catch (Exception re) {  
  41.             throw new IllegalStateException("bind " + name + " failure . ");  
  42.         }  
  43.     }  
  44. }  



测试结果:

服务器端启动:



客户端:



客户端调用后服务器端的信息:



到这里简单的例子就介绍完了,内容很简单,网上我也找到了很多这样的例子,就不多说了,我也是参考了别人的例子做出来。有这个例子,我们可以证实的一点就是,我们可以搭建RMI环境了。

二、在第二个例子中,加入一些安全措施,使用java的securityManager来做一些访问的限制。

项目的结构:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package rmiproj.myserver;  
  2.   
  3. import java.rmi.Remote;  
  4. import java.rmi.RemoteException;  
  5.   
  6. /** 这个接口还是我们要暴露的远程方法的接口,同样的这个接口要继承Remote,并且接口中的所有方法都要抛出RemoteException */  
  7. public interface MyCalculater extends Remote {  
  8.   
  9.     public long plus(long num1, long num2) throws RemoteException;  
  10.   
  11.     public long minus(long num1, long num2) throws RemoteException;  
  12.   
  13.     public long multi(long num1, long num2) throws RemoteException;  
  14.   
  15.     public long division(long num1, long num2) throws RemoteException;  
  16. }  

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package rmiproj.myserver;  
  2.   
  3. import java.rmi.RemoteException;  
  4. import java.rmi.server.UnicastRemoteObject;  
  5.   
  6. /** 
  7.  * MyCalculater的实现类,同样继承了UnicastRemoteObject 
  8.  *  
  9.  * */  
  10. public class MyCalculaterImpl extends UnicastRemoteObject implements  
  11.         MyCalculater {  
  12.   
  13.     protected MyCalculaterImpl() throws RemoteException {  
  14.         super();  
  15.     }  
  16.   
  17.     /** 
  18.      *  
  19.      */  
  20.     private static final long serialVersionUID = 1L;  
  21.     private static final Object lock = new Object();  
  22.     private static MyCalculater instance;  
  23.   
  24.     @Override  
  25.     public long plus(long num1, long num2) throws RemoteException {  
  26.         System.out.println(System.currentTimeMillis() + "服务器运行加法");  
  27.         System.out.println(Thread.currentThread().getId() + ":"  
  28.                 + Thread.currentThread().getName());  
  29.         return num1 + num2;  
  30.     }  
  31.   
  32.     @Override  
  33.     public long minus(long num1, long num2) throws RemoteException {  
  34.         System.out.println(System.currentTimeMillis() + "服务器运行减法");  
  35.         System.out.println(Thread.currentThread().getId() + ":"  
  36.                 + Thread.currentThread().getName());  
  37.         return num1 - num2;  
  38.     }  
  39.   
  40.     @Override  
  41.     public long multi(long num1, long num2) throws RemoteException {  
  42.         System.out.println(System.currentTimeMillis() + "服务器运行乘法");  
  43.         System.out.println(Thread.currentThread().getId() + ":"  
  44.                 + Thread.currentThread().getName());  
  45.         return num1 * num2;  
  46.     }  
  47.   
  48.     @Override  
  49.     public long division(long num1, long num2) throws RemoteException {  
  50.         System.out.println(System.currentTimeMillis() + "服务器运行除法");  
  51.         System.out.println(Thread.currentThread().getId() + ":"  
  52.                 + Thread.currentThread().getName());  
  53.         return num1 / num2;  
  54.     }  
  55.   
  56.     public static MyCalculater getInstance() throws RemoteException {  
  57.         if (null == instance) {  
  58.             synchronized (lock) {  
  59.                 instance = new MyCalculaterImpl();  
  60.             }  
  61.         }  
  62.         return instance;  
  63.     }  
  64.   
  65. }  


[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package rmiproj.myserver;  
  2.   
  3. import java.net.MalformedURLException;  
  4. import java.rmi.Naming;  
  5. import java.rmi.RemoteException;  
  6. import java.rmi.registry.LocateRegistry;  
  7.   
  8. public class MyServer {  
  9.     public static void main(String[] args) {  
  10.         /** 
  11.          * 这里是这个server的重点,这里我们把系统的java.security.policy设置为我们自己定义的一个client.policy, 
  12.          * 在client。policy中我们定义了一个访问规则 
  13.          * */  
  14.         System.setProperty("java.security.policy",  
  15.                 MyServer.class.getResource("client.policy").toString());  
  16.   
  17.         if (System.getSecurityManager() == null) {  
  18.             /* 使用了我们定义的policy文件以后,就要定义一个有效的SecurityManager来保证系统正确的应用了我们的规则 */  
  19.             System.setSecurityManager(new SecurityManager());  
  20.         }  
  21.   
  22.         try {  
  23.             /* 这里和第一个例子一样,就是绑定我们提供的远程方法了 */  
  24.             LocateRegistry.createRegistry(1099);  
  25.             Naming.rebind("cul", MyCalculaterImpl.getInstance());  
  26.             System.out.println(Thread.currentThread().getName());  
  27.         } catch (RemoteException e) {  
  28.             // TODO Auto-generated catch block  
  29.             e.printStackTrace();  
  30.         } catch (MalformedURLException e) {  
  31.             // TODO Auto-generated catch block  
  32.             e.printStackTrace();  
  33.         }  
  34.     }  
  35. }  

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package rmiproj.myclient;  
  2.   
  3. import java.net.MalformedURLException;  
  4. import java.rmi.Naming;  
  5. import java.rmi.NotBoundException;  
  6. import java.rmi.RemoteException;  
  7.   
  8. import rmiproj.myserver.MyCalculater;  
  9.   
  10. /** 用来测试的客户端 */  
  11. public class Test {  
  12.     public static void main(String[] args) {  
  13.         try {  
  14.             MyCalculater my = (MyCalculater) Naming  
  15.                     .lookup("rmi://localhost:1099/" + "cul");  
  16.             System.out.println(my.plus(12));  
  17.             Thread.sleep(5000);  
  18.             System.out.println(my.minus(12));  
  19.             Thread.sleep(5000);  
  20.             System.out.println(my.multi(26));  
  21.             Thread.sleep(5000);  
  22.             System.out.println(my.division(12));  
  23.             Thread.sleep(5000);  
  24.         } catch (MalformedURLException e) {  
  25.             e.printStackTrace();  
  26.         } catch (RemoteException e) {  
  27.             e.printStackTrace();  
  28.         } catch (NotBoundException e) {  
  29.             e.printStackTrace();  
  30.         } catch (InterruptedException e) {  
  31.             e.printStackTrace();  
  32.         }  
  33.     }  
  34. }  


client.policy的内容如下:



测试结果:

服务器启动结果:


客户端测试结果:

(1)当policy文件的内容如上所示为

grant{
permission java.net.SocketPermission "*:1024-65535","accept,connect,listen";
};的时候表示的是允许任意ip的1024-65535端口进行socket的accept,connect,listen动作,这时候客户端肯定是可以调用方法的


可以看到在客户端我们成功的完成了四则运算。

同时在服务器端,我们也看到了调用的记录



这是我修改了policy文件的内容,内容如下

grant{
permission java.net.SocketPermission "192.168.1.210:1024-65535","accept,connect,listen";
}; 这时候只允许192.168.1.210来进行socket的各个动作了,这时候在进行测试

客户端:


异常了··nested exception``被服务器拒绝了,

服务器端:


服务器端也是这样的,在127.0.0.1:57304套接字处的链接被拒绝了

这时我修改一下客户端的测试代码,把localhost换成192.168.1.210,再进行测试

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package rmiproj.myclient;  
  2.   
  3. import java.net.MalformedURLException;  
  4. import java.rmi.Naming;  
  5. import java.rmi.NotBoundException;  
  6. import java.rmi.RemoteException;  
  7.   
  8. import rmiproj.myserver.MyCalculater;  
  9.   
  10. /** 用来测试的客户端 */  
  11. public class Test {  
  12.     public static void main(String[] args) {  
  13.         try {  
  14.             MyCalculater my = (MyCalculater) Naming  
  15.                     .lookup("rmi://192.168.1.210:1099/" + "cul");  
  16.             System.out.println(my.plus(12));  
  17.             Thread.sleep(5000);  
  18.             System.out.println(my.minus(12));  
  19.             Thread.sleep(5000);  
  20.             System.out.println(my.multi(26));  
  21.             Thread.sleep(5000);  
  22.             System.out.println(my.division(12));  
  23.             Thread.sleep(5000);  
  24.         } catch (MalformedURLException e) {  
  25.             e.printStackTrace();  
  26.         } catch (RemoteException e) {  
  27.             e.printStackTrace();  
  28.         } catch (NotBoundException e) {  
  29.             e.printStackTrace();  
  30.         } catch (InterruptedException e) {  
  31.             e.printStackTrace();  
  32.         }  
  33.     }  
  34. }  
测试结果

客户端:


客户端的测试是成功的,完成了四则运算。

服务端:


服务器端也打印了相应的记录哦。

三、简化调用过程?其实就是利用反射使用统一的excute方法来支持指定类中的方法

这里先讨论一下从别人那里参考过来的简化方法。

项目的结构如下,只看展开的就可以了


先看看服务端是个什么样子的吧。。。。。

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package rmiproj.newserver;  
  2.   
  3. /* 
  4.  * 这个是一个操作接口,变化很大的,什么都不需要继承和扩展了,他出现的唯一的原因就是我要使用反射 
  5.  * */  
  6. public interface MyCalculater {  
  7.   
  8.     public long plus(long num1, long num2);  
  9.   
  10.     public long minus(long num1, long num2);  
  11.   
  12.     public long multi(long num1, long num2);  
  13.   
  14.     public long division(long num1, long num2);  
  15. }  

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package rmiproj.newserver;  
  2.   
  3. /*上面那个接口的实现类*/  
  4. public class MyCalculaterImpl implements MyCalculater {  
  5.   
  6.     private static final long serialVersionUID = 1L;  
  7.     private static final Object lock = new Object();  
  8.     private static MyCalculater instance;  
  9.   
  10.     @Override  
  11.     public long plus(long num1, long num2) {  
  12.         System.out.println(System.currentTimeMillis() + "服务器运行加法");  
  13.         return num1 + num2;  
  14.     }  
  15.   
  16.     @Override  
  17.     public long minus(long num1, long num2) {  
  18.         System.out.println(System.currentTimeMillis() + "服务器运行减法");  
  19.         return num1 - num2;  
  20.     }  
  21.   
  22.     @Override  
  23.     public long multi(long num1, long num2) {  
  24.         System.out.println(System.currentTimeMillis() + "服务器运行乘法");  
  25.         return num1 * num2;  
  26.     }  
  27.   
  28.     @Override  
  29.     public long division(long num1, long num2) {  
  30.         System.out.println(System.currentTimeMillis() + "服务器运行除法");  
  31.         return num1 / num2;  
  32.     }  
  33.   
  34.     public static MyCalculater getInstance() {  
  35.         if (null == instance) {  
  36.             synchronized (lock) {  
  37.                 instance = new MyCalculaterImpl();  
  38.             }  
  39.         }  
  40.         return instance;  
  41.     }  
  42.   
  43. }  


[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package rmiproj.newserver;  
  2.   
  3. import java.rmi.Remote;  
  4. import java.rmi.RemoteException;  
  5.   
  6. /* 
  7.  * 我们要暴露的统一接口方法,继承了Remote,方法抛出了RemoteException 
  8.  *  
  9.  * 看看这个方法,第一个参数是要调用的service的名字,然后是方法的名字,然后就是要传入的参数 
  10.  * 标准的反射调用 
  11.  *  
  12.  * */  
  13. public interface CommonRmiService extends Remote {  
  14.     public Object execute(String serviceName, String methodName, Object[] args)  
  15.             throws RemoteException;  
  16. }  


[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package rmiproj.newserver;  
  2.   
  3. import java.lang.reflect.InvocationTargetException;  
  4. import java.rmi.RemoteException;  
  5. import java.rmi.server.UnicastRemoteObject;  
  6.   
  7. /*就是上面的那个接口的实现类,继承了UnicastRemoteObject*/  
  8. public class CommonRmiServiceImpl extends UnicastRemoteObject implements  
  9.         CommonRmiService {  
  10.   
  11.     protected CommonRmiServiceImpl() throws RemoteException {  
  12.         super();  
  13.     }  
  14.   
  15.     /** 
  16.      *  
  17.      */  
  18.     private static final long serialVersionUID = 1L;  
  19.   
  20.     @Override  
  21.     public Object execute(String serviceName, String methodName, Object[] args)  
  22.             throws RemoteException {  
  23.         //这段代码就是通过反射调用方法了,这个是反射的内容我就不多介绍了  
  24.         Class<?> clazz = null;  
  25.         try {  
  26.             clazz = Class.forName(serviceName);  
  27.         } catch (ClassNotFoundException e1) {  
  28.             System.out.println(e1.getMessage());  
  29.         }  
  30.         try {  
  31.             return ReflectUtil  
  32.                     .execMethod(clazz.newInstance(), methodName, args);  
  33.         } catch (NoSuchMethodException e) {  
  34.             System.out.println(e.getMessage());  
  35.             return null;  
  36.         } catch (IllegalArgumentException e) {  
  37.             System.out.println(e.getMessage());  
  38.             return null;  
  39.         } catch (IllegalAccessException e) {  
  40.             System.out.println(e.getMessage());  
  41.             return null;  
  42.         } catch (InvocationTargetException e) {  
  43.             System.out.println(e.getMessage());  
  44.             return null;  
  45.         } catch (InstantiationException e) {  
  46.             System.out.println(e.getMessage());  
  47.             return null;  
  48.         }  
  49.     }  
  50.   
  51. }  

这里面用到了一个ReflectUtil,也是早就写好的一个工具类了,做了一些精简,我就不多做注释了,代码如下

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package rmiproj.newserver;  
  2.   
  3. import java.lang.reflect.InvocationTargetException;  
  4. import java.lang.reflect.Method;  
  5. import java.util.ArrayList;  
  6. import java.util.List;  
  7.   
  8. public class ReflectUtil {  
  9.     public static Object execMethod(Object obj, String methodName,  
  10.             Object... params) throws NoSuchMethodException,  
  11.             IllegalArgumentException, IllegalAccessException,  
  12.             InvocationTargetException {  
  13.         Object result = null;  
  14.         Class<?> c = obj.getClass();  
  15.         Class<?>[] parameterTypes = new Class<?>[] {};  
  16.   
  17.         if (params != null) {  
  18.             parameterTypes = new Class<?>[params.length];  
  19.             for (int i = 0; i < params.length; i++) {  
  20.                 parameterTypes[i] = params[i].getClass();  
  21.             }// for  
  22.         }// if  
  23.   
  24.         Method m = getMethod(c, methodName, parameterTypes);  
  25.         result = m.invoke(obj, params);  
  26.         return result;  
  27.     }  
  28.   
  29.     public static <T extends Object> Method getMethod(Class<T> clazz,  
  30.             String methodName, Class<?>[] parameterTypes)  
  31.             throws NoSuchMethodException {  
  32.   
  33.         Method[] allMethods = clazz.getMethods(); // 找到所有方法  
  34.   
  35.         int parameterLen = parameterTypes.length; // 实参个数  
  36.         List<Method> similarMethodList = new ArrayList<Method>(); // 所有能够执行parameterTypes实参的方法  
  37.         for (Method method : allMethods) {  
  38.             if (!method.getName().equals(methodName)) {  
  39.                 continue;  
  40.             }  
  41.             if (method.getParameterTypes().length == parameterLen) {  
  42.                 boolean isSimilarType = true;  
  43.                 Class<?>[] formaParameterTypes = method.getParameterTypes(); // 得到形参  
  44.                 for (int i = 0; i < parameterLen; i++) {  
  45.                     if (!isSameOrSupperType(formaParameterTypes[i],  
  46.                             parameterTypes[i])) {  
  47.                         isSimilarType = false;  
  48.                         break;  
  49.                     }  
  50.                 }  
  51.                 if (isSimilarType) {  
  52.                     similarMethodList.add(method);  
  53.                 }  
  54.             }// if  
  55.         }  
  56.   
  57.         if (similarMethodList.isEmpty()) {  
  58.             StringBuilder sb = new StringBuilder();  
  59.             sb.append(methodName);  
  60.             sb.append("(");  
  61.             if (null != parameterTypes) {  
  62.                 StringBuilder parameterTypeBuilder = new StringBuilder();  
  63.                 for (Class<?> parameterType : parameterTypes) {  
  64.                     parameterTypeBuilder.append(parameterType.getName())  
  65.                             .append(",");  
  66.                 }  
  67.                 if (parameterTypeBuilder  
  68.                         .charAt(parameterTypeBuilder.length() - 1) == ',') {  
  69.                     parameterTypeBuilder = parameterTypeBuilder  
  70.                             .deleteCharAt(parameterTypeBuilder.length() - 1);  
  71.                 }  
  72.                 sb.append(parameterTypeBuilder);  
  73.             }  
  74.             sb.append(")");  
  75.             throw new NoSuchMethodException("没有这样的方法.   " + sb.toString());  
  76.         }  
  77.   
  78.         List<Integer> parameterMatchingCountList = new ArrayList<Integer>(); // 存放各个能够执行parameterTypes形参的方法对形参的严格匹配个数  
  79.         for (Method method : similarMethodList) {  
  80.             int parameterMatchingCount = 0;  
  81.             Class<?>[] formaParameterTypes = method.getParameterTypes();  
  82.             for (int i = 0; i < parameterLen; i++) {  
  83.                 if (formaParameterTypes[i].getName().equals(  
  84.                         parameterTypes[i].getName())) {  
  85.                     parameterMatchingCount++;  
  86.                 }  
  87.             }  
  88.             parameterMatchingCountList.add(parameterMatchingCount);  
  89.         }  
  90.         int maxMatchingCountIndex = 0;  
  91.         for (int i = 1; i < parameterMatchingCountList.size(); i++) {  
  92.             if (parameterMatchingCountList.get(maxMatchingCountIndex)  
  93.                     .intValue() < parameterMatchingCountList.get(i).intValue()) {  
  94.                 maxMatchingCountIndex = i;  
  95.             }  
  96.         }  
  97.         return similarMethodList.get(maxMatchingCountIndex); //  
  98.     }  
  99.   
  100.     public static boolean isSameOrSupperType(Class<?> clsA, Class<?> clsB) {  
  101.         if (!clsA.isPrimitive() && !clsB.isPrimitive()) {  
  102.             return clsA.isAssignableFrom(clsB);  
  103.         }  
  104.         return isSameBasicType(clsA, clsB);  
  105.     }  
  106.   
  107.     public static boolean isSameBasicType(Class<?> clsA, Class<?> clsB) {  
  108.         if (isIntType(clsA) && isIntType(clsB)) {  
  109.             return true;  
  110.         }  
  111.         if (isLongType(clsA) && isLongType(clsB)) {  
  112.             return true;  
  113.         }  
  114.         if (isBooleanType(clsA) && isBooleanType(clsB)) {  
  115.             return true;  
  116.         }  
  117.         if (isByteType(clsA) && isByteType(clsB)) {  
  118.             return true;  
  119.         }  
  120.         if (isCharType(clsA) && isCharType(clsB)) {  
  121.             return true;  
  122.         }  
  123.         if (isFloatType(clsA) && isFloatType(clsB)) {  
  124.             return true;  
  125.         }  
  126.         if (isDoubleType(clsA) && isDoubleType(clsB)) {  
  127.             return true;  
  128.         }  
  129.         if (isShortType(clsA) && isShortType(clsB)) {  
  130.             return true;  
  131.         }  
  132.         return false;  
  133.     }  
  134.   
  135.     public static boolean isCharType(Class<?> clazz) {  
  136.         return Character.class.isAssignableFrom(clazz)  
  137.                 || Character.TYPE.isAssignableFrom(clazz);  
  138.     }  
  139.   
  140.     public static boolean isBooleanType(Class<?> clazz) {  
  141.         return Boolean.class.isAssignableFrom(clazz)  
  142.                 || Boolean.TYPE.isAssignableFrom(clazz);  
  143.     }  
  144.   
  145.     public static boolean isIntType(Class<?> clazz) {  
  146.         return Integer.class.isAssignableFrom(clazz)  
  147.                 || Integer.TYPE.isAssignableFrom(clazz);  
  148.     }  
  149.   
  150.     public static boolean isLongType(Class<?> clazz) {  
  151.         return Long.class.isAssignableFrom(clazz)  
  152.                 || Long.TYPE.isAssignableFrom(clazz);  
  153.     }  
  154.   
  155.     public static boolean isFloatType(Class<?> clazz) {  
  156.         return Float.class.isAssignableFrom(clazz)  
  157.                 || Float.TYPE.isAssignableFrom(clazz);  
  158.     }  
  159.   
  160.     public static boolean isDoubleType(Class<?> clazz) {  
  161.         return Double.class.isAssignableFrom(clazz)  
  162.                 || Double.TYPE.isAssignableFrom(clazz);  
  163.     }  
  164.   
  165.     public static boolean isByteType(Class<?> clazz) {  
  166.         return Byte.class.isAssignableFrom(clazz)  
  167.                 || Byte.TYPE.isAssignableFrom(clazz);  
  168.     }  
  169.   
  170.     public static boolean isShortType(Class<?> clazz) {  
  171.         return Short.class.isAssignableFrom(clazz)  
  172.                 || Short.TYPE.isAssignableFrom(clazz);  
  173.     }  
  174. }  
服务端:
[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package rmiproj.newserver;  
  2.   
  3. import java.net.MalformedURLException;  
  4. import java.rmi.Naming;  
  5. import java.rmi.RemoteException;  
  6. import java.rmi.registry.LocateRegistry;  
  7.   
  8. /** 
  9.  * 使用了统一的暴露接口以后,服务端就不用在修修改改了,永远都是暴露CommonRmiServiceImpl,不管新增什么方法都是一样滴调用这个接口来执行 
  10.  * 其实,spring中的rmi道理也是一样滴 
  11.  * */  
  12. public class Server {  
  13.     public static void main(String[] args) {  
  14.         try {  
  15.             LocateRegistry.createRegistry(1099);  
  16.             Naming.rebind("service"new CommonRmiServiceImpl());  
  17.             System.out.println(LocateRegistry.getRegistry());  
  18.         } catch (RemoteException e) {  
  19.             e.printStackTrace();  
  20.         } catch (MalformedURLException e) {  
  21.             e.printStackTrace();  
  22.         }  
  23.     }  
  24. }  
用来测试的客户端:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package rmiproj.newclient;  
  2.   
  3. import java.net.MalformedURLException;  
  4. import java.rmi.Naming;  
  5. import java.rmi.NotBoundException;  
  6. import java.rmi.RemoteException;  
  7.   
  8. public class Test {  
  9.     public static void main(String[] args) {  
  10.         try {  
  11.             rmiproj.newserver.CommonRmiService my = (rmiproj.newserver.CommonRmiService) Naming  
  12.                     .lookup("rmi://localhost:1099/" + "service");  
  13.             System.out.println(my.execute("rmiproj.newserver.MyCalculaterImpl",  
  14.                     "plus"new Object[] { 1L, 2L }));  
  15.         } catch (MalformedURLException e) {  
  16.             e.printStackTrace();  
  17.         } catch (RemoteException e) {  
  18.             e.printStackTrace();  
  19.         } catch (NotBoundException e) {  
  20.             e.printStackTrace();  
  21.         }  
  22.     }  
  23.   
  24. }  

测试结果:

服务器端启动:


客户端测试结果:


服务器端显示的内容:



这个例子其实也没有什么,就是把暴露的方法改为了一个通过反射来执行服务器端的其他方法的方法了,在这种方式下,服务器端书写代码会变的简单,不用在管什么Remote和UnicastRemoteObject了,按照平时的接口----》实现类书写就可以了,同时服务器端的server代码也不用变了。但是问题是客户端要知道要调用的类的全名,方法的名称以及参数的相关信息。

四、使用sll的双向认证的rmi(个人感觉很高级了··信息是安全的,访问也是安全的)

在例子二里面初步的考虑了安全问题,但是我个人不喜欢,也不熟悉那个policy文件的配置,而且感觉和很多框架要使用的securityManager会有冲突,而且也有更好的更安全的办法。就是这里介绍给大家了

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package rmiproj.ssl_1;  
  2.   
  3. import java.rmi.Remote;  
  4. import java.rmi.RemoteException;  
  5.   
  6. /*本人比较懒惰了··这里就写个hello吧,还是那一套继承Remote,方法中需要抛出RemoteException*/  
  7. public interface Hello extends Remote {  
  8.     public String sayHello() throws RemoteException;  
  9. }  

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package rmiproj.ssl_1;  
  2.   
  3. import java.io.FileInputStream;  
  4. import java.rmi.RemoteException;  
  5. import java.rmi.registry.LocateRegistry;  
  6. import java.rmi.registry.Registry;  
  7. import java.rmi.server.UnicastRemoteObject;  
  8. import java.security.KeyStore;  
  9. import java.security.SecureRandom;  
  10.   
  11. import javax.net.ssl.KeyManagerFactory;  
  12. import javax.net.ssl.SSLContext;  
  13. import javax.net.ssl.TrustManagerFactory;  
  14. import javax.rmi.ssl.SslRMIServerSocketFactory;  
  15.   
  16. /** 
  17.  * 这个是hello的实现类,在构造方法和getCntext那里有些幺蛾子,需要细细看看,其他没什么了 
  18.  *  
  19.  * */  
  20. public class HelloImpl_1 extends UnicastRemoteObject implements Hello {  
  21.   
  22.     protected HelloImpl_1() throws IllegalArgumentException, Exception {  
  23.         /** 
  24.          * 这个构造方法需要细细的说道一下了 
  25.          * 先说super 
  26.          *  
  27.          * 第一个参数指明了这个remoteObject接受请求的端口,我就设置成了0; 
  28.          *  
  29.          * 第二个参数设置客户端要使用的套接字工厂,我设置了自己实现的MySslRMIClientSocketFactory,这个具体是什么,后面介绍 
  30.          *  
  31.          * 第三个参数设置了服务端要是用的套接字工场,我是用了SslRMIServerSocketFactory;其中getContext在后面说, 
  32.          * new String[] { "SSL_RSA_WITH_RC4_128_MD5" }是加密算法,new String[] { "TLSv1" }使用的协议。 
  33.          *  
  34.          * 第四个参数是是否开启对客户端的验证,要做双向验证必然是true了 
  35.          *  
  36.          * */  
  37.         super(0new MySslRMIClientSocketFactory(),  
  38.                 new SslRMIServerSocketFactory(getContext(),  
  39.                         new String[] { "SSL_RSA_WITH_RC4_128_MD5" },  
  40.                         new String[] { "TLSv1" }, true));  
  41.     }  
  42.   
  43.     /** 
  44.      *  
  45.      */  
  46.     private static final long serialVersionUID = 1L;  
  47.   
  48.     @Override  
  49.     public String sayHello() throws RemoteException {  
  50.         //在这里我没什么好说的··  
  51.         return "Hello World";  
  52.     }  
  53.   
  54.     public static SSLContext getContext() throws Exception {  
  55.         String key = "d:/keys/m.jks";//服务器端的秘钥  
  56.         String trust = "d:keys/trustclient.jks";//服务器端信任的证书  
  57.         KeyStore keyStore = KeyStore.getInstance("JKS");//使用JKS的keyStore  
  58.         /*加载服务器的秘钥开始*/  
  59.         keyStore.load(new FileInputStream(key), "123456".toCharArray());  
  60.         KeyStore trustStore = KeyStore.getInstance("JKS");  
  61.         /*加载服务器的秘钥结束*/  
  62.         /*加载服务器信任的证书开始*/  
  63.         trustStore.load(new FileInputStream(trust), "123456".toCharArray());  
  64.         /*加载服务器信任的证书结束*/  
  65.           
  66.         KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory  
  67.                 .getDefaultAlgorithm());//创建了秘钥管理工厂  
  68.         kmf.init(keyStore, "mipengcheng".toCharArray());//用服务器的秘钥来初始化秘钥工厂  
  69.         TrustManagerFactory tmf = TrustManagerFactory  
  70.                 .getInstance(TrustManagerFactory.getDefaultAlgorithm());//建立了信任证书工厂  
  71.         tmf.init(trustStore);//用服务器信任的证书来初始化  
  72.         SSLContext sslc = SSLContext.getInstance("TLSv1");//获得context实例  
  73.         sslc.init(kmf.getKeyManagers(), tmf.getTrustManagers(),  
  74.                 new SecureRandom());//初始化context  
  75.         return sslc;  
  76.     }  
  77.   
  78.     /** 
  79.      * 在这里我不使用Naming了,而是直接使用registry来绑定,其实功能是一样的,但是这个方式更适合不指定url的访问方式 
  80.      * */  
  81.     public static void main(String[] args) throws Exception {  
  82.         //获得注册的registry,因为我注册的registry也使用了sll,所以这里也要在参数中加入new MySslRMIClientSocketFactory()  
  83.         Registry registry = LocateRegistry.getRegistry(null3000new MySslRMIClientSocketFactory());  
  84.         HelloImpl_1 helloImpl = new HelloImpl_1();  
  85.         //绑定  
  86.         registry.bind("HelloServer", helloImpl);  
  87.         System.out.println("HelloServer bound in registry");  
  88.     }  
  89. }  

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package rmiproj.ssl_1;  
  2.   
  3. import java.io.FileInputStream;  
  4. import java.rmi.registry.LocateRegistry;  
  5. import java.security.KeyStore;  
  6. import java.security.SecureRandom;  
  7.   
  8. import javax.net.ssl.KeyManagerFactory;  
  9. import javax.net.ssl.SSLContext;  
  10. import javax.net.ssl.TrustManagerFactory;  
  11. import javax.rmi.ssl.SslRMIServerSocketFactory;  
  12.   
  13. public class RmiRegistry {  
  14.     public static void main(String[] args) throws Exception {  
  15.         String key = "d:/keys/m.jks";  
  16.         String trust = "d:keys/trustclient.jks";  
  17.         KeyStore keyStore = KeyStore.getInstance("JKS");  
  18.         keyStore.load(new FileInputStream(key), "123456".toCharArray());  
  19.         KeyStore trustStore = KeyStore.getInstance("JKS");  
  20.         trustStore.load(new FileInputStream(trust), "123456".toCharArray());  
  21.         KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory  
  22.                 .getDefaultAlgorithm());  
  23.         kmf.init(keyStore, "mipengcheng".toCharArray());  
  24.         TrustManagerFactory tmf = TrustManagerFactory  
  25.                 .getInstance(TrustManagerFactory.getDefaultAlgorithm());  
  26.         tmf.init(trustStore);  
  27.         SSLContext sslc = SSLContext.getInstance("SSLv3");  
  28.         sslc.init(kmf.getKeyManagers(), tmf.getTrustManagers(),  
  29.                 new SecureRandom());  
  30.         /*上面的一套代码就是生成一个指定了秘钥和信任证书的context,就不多说了*/  
  31.           
  32.         /*下面我们在300端口创建一个registry,并且指定了客户端套接字和服务端套接字,和HelloImpl_1中的很像*/  
  33.         LocateRegistry.createRegistry(3000new MySslRMIClientSocketFactory(),  
  34.                 new SslRMIServerSocketFactory(sslc,  
  35.                         new String[] { "SSL_RSA_WITH_RC4_128_MD5" },  
  36.                         new String[] { "TLSv1" }, true));  
  37.         System.out.println("RMI Registry running on port 3000");  
  38.         Object object = new Object();  
  39.         synchronized (object) {  
  40.             object.wait();  
  41.         }  
  42.   
  43.     }  
  44. }  


[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package rmiproj.ssl_1;  
  2.   
  3. import java.io.FileInputStream;  
  4. import java.io.IOException;  
  5. import java.net.Socket;  
  6. import java.security.KeyStore;  
  7. import java.security.SecureRandom;  
  8.   
  9. import javax.net.ssl.KeyManagerFactory;  
  10. import javax.net.ssl.SSLContext;  
  11. import javax.net.ssl.SSLSocket;  
  12. import javax.net.ssl.SSLSocketFactory;  
  13. import javax.net.ssl.TrustManagerFactory;  
  14. import javax.rmi.ssl.SslRMIClientSocketFactory;  
  15.   
  16. public class MySslRMIClientSocketFactory extends SslRMIClientSocketFactory {  
  17.   
  18.     /** 
  19.      *  
  20.      * 这个类继承了SslRMIClientSocketFactory,我也是看文档的, 
  21.      * 那个什么什么说SslRMIClientSocketFactory为了避免各种各种的问题 
  22.      * 都是使用默认的jre中配置的证书来创建socket,要是你自己的客户端能验证服务器 
  23.      * ,服务器验证你的客户端,而且是使用自己的证书,就重写一下createSocket这个方法。。。云云 那就重写吧 
  24.      */  
  25.     private static final long serialVersionUID = 1L;  
  26.   
  27.     public MySslRMIClientSocketFactory() {  
  28.         super();  
  29.     }  
  30.   
  31.     @Override  
  32.     public Socket createSocket(String host, int port) throws IOException {  
  33.         String key = "d:/keys/trustm.jks";  
  34.         String client = "d:/keys/client.jks";  
  35.         try {  
  36.             KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());  
  37.             keyStore.load(new FileInputStream(key), "123456".toCharArray());  
  38.             KeyStore clientStore = KeyStore.getInstance(KeyStore  
  39.                     .getDefaultType());  
  40.             clientStore.load(new FileInputStream(client),  
  41.                     "123456".toCharArray());  
  42.             TrustManagerFactory tmf = TrustManagerFactory  
  43.                     .getInstance(TrustManagerFactory.getDefaultAlgorithm());  
  44.             tmf.init(keyStore);  
  45.             KeyManagerFactory kmf = KeyManagerFactory  
  46.                     .getInstance(KeyManagerFactory.getDefaultAlgorithm());  
  47.             kmf.init(clientStore, "123456".toCharArray());  
  48.             SSLContext sslc = SSLContext.getInstance("TLSv1");  
  49.             sslc.init(kmf.getKeyManagers(), tmf.getTrustManagers(),  
  50.                     new SecureRandom());  
  51.             /*上面的没什么好说的了。。。就是要说说,证书换成了客户端要信任的证书和客户端的秘钥*/  
  52.               
  53.             SSLSocketFactory sslSocketFactory = sslc.getSocketFactory();//通过sslc获得socketFactory  
  54.             SSLSocket socket = (SSLSocket) sslSocketFactory.createSocket(host,  
  55.                     port);//建立socket  
  56.             return socket;  
  57.         } catch (Exception e) {  
  58.             e.printStackTrace();  
  59.             return null;  
  60.         }  
  61.   
  62.     }  
  63.   
  64.     @Override  
  65.     public int hashCode() {  
  66.         return super.hashCode();  
  67.     }  
  68.   
  69.     @Override  
  70.     public boolean equals(Object obj) {  
  71.         return super.equals(obj);  
  72.     }  
  73.   
  74. }  


[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package rmiproj.ssl_1;  
  2.   
  3. import java.rmi.registry.LocateRegistry;  
  4. import java.rmi.registry.Registry;  
  5.   
  6. /* 
  7.  * 测试的客户端 
  8.  * */  
  9. public class HelloClient {  
  10.     public static void main(String[] args) throws Exception {  
  11.         Registry registry = LocateRegistry.getRegistry("localhost"3000,  
  12.                 new MySslRMIClientSocketFactory());/* 
  13.                                                      * 这里要特别注意, 
  14.                                                      * 因为我在registry的服务端配置了要进行双向认证 
  15.                                                      * , 
  16.                                                      * 所以这里的registry在get的时候一定要添加参数MySslRMIClientSocketFactory 
  17.                                                      */  
  18.         Hello hello = (Hello) registry.lookup("HelloServer");  
  19.         System.out.println(hello.sayHello());  
  20.     }  
  21. }  


使用到的证书


测试结果

服务器端启动:

先运行RmiRegistry



再运行HelloImpl_1


运行客户端进行测试


这样在ssl上的RMI就配置完成了,测试也是通过的。错误的测试我就不做了。可以尝试客户端不传自己的证书,链接是否成功。也可以尝试服务器端不传证书,服务器端不信任客户端,客户端不信任服务器端等等的情况,我都测试过,都是无法建立链接的。

同时那几个证书的生成过程我也忽略了没有说,网上指导这些证书生成的博文很多,我就不细说了。

五、在spring中使用RMI。

spring最最重要的就是配置文件了,那么就直接看配置文件了

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <beans xmlns="http://www.springframework.org/schema/beans"  
  2.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"  
  3.     xmlns:context="http://www.springframework.org/schema/context"  
  4.     xmlns:util="http://www.springframework.org/schema/util" xmlns:jee="http://www.springframework.org/schema/jee"  
  5.     xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"  
  6.     xmlns:aop="http://www.springframework.org/schema/aop"  
  7.     xsi:schemaLocation="  
  8.         http://www.springframework.org/schema/util  
  9.         http://www.springframework.org/schema/util/spring-util-3.0.xsd  
  10.         http://www.springframework.org/schema/beans   
  11.         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  12.         http://www.springframework.org/schema/context   
  13.         http://www.springframework.org/schema/context/spring-context-3.0.xsd  
  14.         http://www.springframework.org/schema/tx   
  15.         http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  
  16.         http://www.springframework.org/schema/jee   
  17.         http://www.springframework.org/schema/jee/spring-jee-3.0.xsd  
  18.         http://www.springframework.org/schema/mvc  
  19.         http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd  
  20.         http://www.springframework.org/schema/aop   
  21.         http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"  
  22.     default-lazy-init="false">  
  23.   
  24.     <!-- 这个serviceExporter就是spring用来暴露RMI服务的bean -->  
  25.     <bean id="serviceExporter" class="org.springframework.remoting.rmi.RmiServiceExporter">  
  26.         <property name="serviceName" value="AccountService" /><!-- 配置暴露的服务名 -->  
  27.         <property name="service" ref="accountService" /><!-- 暴露的类 -->  
  28.         <property name="serviceInterface" value="com.mpc.test.inter.AccountService" /><!--暴露类的接口 -->  
  29.         <property name="registryPort" value="8080" /><!-- registry用的端口 -->  
  30.         <property name="servicePort" value="8088" /><!-- remoteObject通信用的接口 -->  
  31.         <property name="clientSocketFactory" ref="mySslRMIClientSocketFactory"></property><!-- 客户端用的socketFactory -->  
  32.         <property name="serverSocketFactory"><!-- 服务端用的socketfactory -->  
  33.             <!-- 偷懒一下··直接使用在类com.mpc.test.ContextUtil中 的getContext来获得这个属性了 -->  
  34.             <bean  
  35.                 class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">  
  36.                 <property name="targetClass" value="com.mpc.test.ContextUtil" />  
  37.                 <property name="targetMethod" value="getContext" />  
  38.             </bean>  
  39.         </property>  
  40.         <!-- 配置拦截器,用来对这些方法做一些aop上的操作,我这里就做了ip的限制。 要注意的是,如果你暴露的服务没有实现Remote接口,那么spring会用他的代理来操作你的暴露的服务,这种情况下这个配置再回生效。当然一般是不会有人放着简单的不用,自己做复杂的东西的 -->  
  41.         <property name="interceptors">  
  42.             <list>  
  43.                 <ref bean="securityInterceptor" />  
  44.             </list>  
  45.         </property>  
  46.     </bean>  
  47.     <!-- 客户端的socketFactory -->  
  48.     <bean id="mySslRMIClientSocketFactory" class="com.mpc.test.MySslRMIClientSocketFactory"></bean>  
  49.   
  50.     <!-- 用来处理ip的拦截器 -->  
  51.     <bean id="securityInterceptor" class="com.mpc.test.SecurityInterceptor">  
  52.         <property name="allowed">  
  53.             <set>  
  54.                 <value>192.168.1.210</value>  
  55.             </set>  
  56.         </property>  
  57.     </bean>  
  58.   
  59.     <!-- 要暴露的服务 -->  
  60.     <bean id="accountService" class="com.mpc.test.clazz.AccountServiceImpl" />  
  61. </beans>  


[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.mpc.test;  
  2.   
  3. import java.io.FileInputStream;  
  4. import java.io.IOException;  
  5. import java.net.Socket;  
  6. import java.security.KeyStore;  
  7. import java.security.SecureRandom;  
  8.   
  9. import javax.net.ssl.KeyManagerFactory;  
  10. import javax.net.ssl.SSLContext;  
  11. import javax.net.ssl.SSLSocket;  
  12. import javax.net.ssl.SSLSocketFactory;  
  13. import javax.net.ssl.TrustManagerFactory;  
  14. import javax.rmi.ssl.SslRMIClientSocketFactory;  
  15.   
  16. /*在例四中已经使用过了,我就不多说了*/  
  17. public class MySslRMIClientSocketFactory extends SslRMIClientSocketFactory {  
  18.   
  19.     /** 
  20.      *  
  21.      */  
  22.     private static final long serialVersionUID = 1L;  
  23.   
  24.     public MySslRMIClientSocketFactory() {  
  25.         super();  
  26.     }  
  27.   
  28.     @Override  
  29.     public Socket createSocket(String host, int port) throws IOException {  
  30.         String key = "d:/keys/trustm.jks";  
  31.         String client = "d:/keys/client.jks";  
  32.         try {  
  33.             KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());  
  34.             keyStore.load(new FileInputStream(key), "123456".toCharArray());  
  35.             KeyStore clientStore = KeyStore.getInstance(KeyStore  
  36.                     .getDefaultType());  
  37.             clientStore.load(new FileInputStream(client),  
  38.                     "123456".toCharArray());  
  39.             TrustManagerFactory tmf = TrustManagerFactory  
  40.                     .getInstance(TrustManagerFactory.getDefaultAlgorithm());  
  41.             tmf.init(keyStore);  
  42.             KeyManagerFactory kmf = KeyManagerFactory  
  43.                     .getInstance(KeyManagerFactory.getDefaultAlgorithm());  
  44.             kmf.init(clientStore, "123456".toCharArray());  
  45.             SSLContext sslc = SSLContext.getInstance("TLSv1");  
  46.             sslc.init(kmf.getKeyManagers(), tmf.getTrustManagers(),  
  47.                     new SecureRandom());  
  48.   
  49.             SSLSocketFactory sslSocketFactory = sslc.getSocketFactory();  
  50.             SSLSocket socket = (SSLSocket) sslSocketFactory.createSocket(host,  
  51.                     port);  
  52.             return socket;  
  53.         } catch (Exception e) {  
  54.             e.printStackTrace();  
  55.             return null;  
  56.         }  
  57.   
  58.     }  
  59.   
  60.     @Override  
  61.     public int hashCode() {  
  62.         return super.hashCode();  
  63.     }  
  64.   
  65.     @Override  
  66.     public boolean equals(Object obj) {  
  67.         return super.equals(obj);  
  68.     }  
  69.   
  70. }  

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.mpc.test;  
  2.   
  3. import java.io.FileInputStream;  
  4. import java.security.KeyStore;  
  5. import java.security.SecureRandom;  
  6.   
  7. import javax.net.ssl.KeyManagerFactory;  
  8. import javax.net.ssl.SSLContext;  
  9. import javax.net.ssl.TrustManagerFactory;  
  10. import javax.rmi.ssl.SslRMIServerSocketFactory;  
  11.   
  12.   
  13. /*在例四中也是使用过的*/  
  14. public class ContextUtil {  
  15.     public static SslRMIServerSocketFactory getContext() throws Exception {  
  16.         String key = "d:/keys/m.jks";  
  17.         String trust = "d:keys/trustclient.jks";  
  18.         KeyStore keyStore = KeyStore.getInstance("JKS");  
  19.         keyStore.load(new FileInputStream(key), "123456".toCharArray());  
  20.         KeyStore trustStore = KeyStore.getInstance("JKS");  
  21.         trustStore.load(new FileInputStream(trust), "123456".toCharArray());  
  22.         KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory  
  23.                 .getDefaultAlgorithm());  
  24.         kmf.init(keyStore, "mipengcheng".toCharArray());  
  25.         TrustManagerFactory tmf = TrustManagerFactory  
  26.                 .getInstance(TrustManagerFactory.getDefaultAlgorithm());  
  27.         tmf.init(trustStore);  
  28.         SSLContext sslc = SSLContext.getInstance("SSLv3");  
  29.         sslc.init(kmf.getKeyManagers(), tmf.getTrustManagers(),  
  30.                 new SecureRandom());  
  31.         return new SslRMIServerSocketFactory(sslc,  
  32.                 new String[] { "SSL_RSA_WITH_RC4_128_MD5" },  
  33.                 new String[] { "TLSv1" }, true);  
  34.     }  
  35. }  

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.mpc.test;  
  2.   
  3. import java.rmi.server.RemoteServer;  
  4. import java.util.Set;  
  5.   
  6. import org.aopalliance.intercept.MethodInterceptor;  
  7. import org.aopalliance.intercept.MethodInvocation;  
  8.   
  9. public class SecurityInterceptor implements MethodInterceptor {  
  10.     private Set<String> allowed;  
  11.   
  12.     /** 定义的拦截器,用来处理ip的问题 */  
  13.     public Object invoke(MethodInvocation methodInvocation) throws Throwable {  
  14.         String cilentHost = RemoteServer.getClientHost();  
  15.         if (allowed != null && allowed.contains(cilentHost)) {  
  16.             return methodInvocation.proceed();  
  17.         } else {  
  18.             throw new SecurityException("非法访问。");  
  19.         }  
  20.     }  
  21.   
  22.     public void setAllowed(Set<String> allowed) {  
  23.         this.allowed = allowed;  
  24.     }  
  25.   
  26. }  

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.mpc.test;  
  2.   
  3. import org.springframework.context.ApplicationContext;  
  4. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  5.   
  6. import junit.framework.Test;  
  7. import junit.framework.TestCase;  
  8. import junit.framework.TestSuite;  
  9.   
  10. /** 
  11.  * Unit test for simple App. 
  12.  * 测试··服务器端 
  13.  */  
  14. public class AppTest extends TestCase {  
  15.     public static void main(String[] args) throws Exception {  
  16.         ApplicationContext context = new ClassPathXmlApplicationContext(  
  17.                 "application-context.xml");  
  18.   
  19.         Object lock = new Object();  
  20.         synchronized (lock) {  
  21.             lock.wait();  
  22.         }  
  23.     }  
  24.   
  25.     /** 
  26.      * Create the test case 
  27.      * 
  28.      * @param testName 
  29.      *            name of the test case 
  30.      *  
  31.      *  
  32.      *  
  33.      */  
  34.     public AppTest(String testName) throws Exception {  
  35.     }  
  36.   
  37.     /** 
  38.      * @return the suite of tests being tested 
  39.      */  
  40.     public static Test suite() {  
  41.         return new TestSuite(AppTest.class);  
  42.     }  
  43.   
  44.     /** 
  45.      * Rigourous Test :-) 
  46.      */  
  47.     public void testApp() {  
  48.         assertTrue(true);  
  49.     }  
  50. }  


客户端的xml配置文件

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <beans xmlns="http://www.springframework.org/schema/beans"  
  2.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"  
  3.     xmlns:context="http://www.springframework.org/schema/context"  
  4.     xmlns:util="http://www.springframework.org/schema/util" xmlns:jee="http://www.springframework.org/schema/jee"  
  5.     xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"  
  6.     xmlns:aop="http://www.springframework.org/schema/aop"  
  7.     xsi:schemaLocation="  
  8.         http://www.springframework.org/schema/util  
  9.         http://www.springframework.org/schema/util/spring-util-3.0.xsd  
  10.         http://www.springframework.org/schema/beans   
  11.         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  12.         http://www.springframework.org/schema/context   
  13.         http://www.springframework.org/schema/context/spring-context-3.0.xsd  
  14.         http://www.springframework.org/schema/tx   
  15.         http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  
  16.         http://www.springframework.org/schema/jee   
  17.         http://www.springframework.org/schema/jee/spring-jee-3.0.xsd  
  18.         http://www.springframework.org/schema/mvc  
  19.         http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd  
  20.         http://www.springframework.org/schema/aop   
  21.         http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"  
  22.     default-lazy-init="false">  
  23.     <!-- 这个就是spring用来调用远程方法的bean没什么好说的-->  
  24.     <bean id="accountService" class="org.springframework.remoting.rmi.RmiProxyFactoryBean">  
  25.         <!-- 请求的地址 -->  
  26.         <property name="serviceUrl" value="rmi://192.168.1.210:8080/AccountService" />  
  27.         <!-- 绑定的接口 -->  
  28.         <property name="serviceInterface" value="com.mpc.test.inter.AccountService" />  
  29.     </bean>  
  30. </beans>  


[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.mpc.test;  
  2.   
  3. import org.springframework.context.ApplicationContext;  
  4. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  5.   
  6. import com.mpc.test.inter.AccountService;  
  7.   
  8. /*测试类*/  
  9. public class TestClient {  
  10.     public static void main(String[] args) throws Exception {  
  11.   
  12.         int i = 1;  
  13.         while (i < 2048) {  
  14.             i <<= 1;  
  15.             new MyThread().start();  
  16.             Thread.sleep(10000);  
  17.         }  
  18.   
  19.     }  
  20.   
  21.     static class MyThread extends Thread {  
  22.   
  23.         @Override  
  24.         public void run() {  
  25.             ApplicationContext ctx = new ClassPathXmlApplicationContext(  
  26.                     "client.xml");  
  27.             AccountService accountService = (AccountService) ctx  
  28.                     .getBean("accountService");  
  29.             String result = accountService.shoopingPayment(  
  30.                     String.valueOf(System.currentTimeMillis()), (byte5);  
  31.             System.out.println(result);  
  32.         }  
  33.     }  
  34. }  

测试结果:

服务器端启动:


客户端测试


服务端的显示:



测试是成功的,这里我只配置了clientSocketFactory和serverSocketFactory,在spring中,同样可以为registry来配置端口的工厂,这两个属性分别是:

private RMIClientSocketFactory registryClientSocketFactory;


private RMIServerSocketFactory registryServerSocketFactory;


这里我没有配置,因为我感觉有一个就足够安全了,有兴趣的话,可以自己配置一下。

还有就是spring中的具体实现原理,大家有性趣可以看看源代码,我看了看也就是代理代理在代理····但是写的很好,篇幅所限就不做介绍了,网上也有人做这方面的介绍的。我提供一个网址大家可以看看:spring的rmi的类的内容

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值