Spring实现RMI调用
传统的实现RMI,需要
1.服务接口必须从Remote派生,每个方法抛出RemoteException
2.实现类必须从UnicastRemoteObject派生
3.所有方法的参数和返回值,必须是基本类型,或者实现了Serializable接口
public class User implements Serializable { private String username; private String password; public User(String username, String password) { this.username = username; this.password = password; } public String getUsername() { return username; } public String getPassword() { return password; }}public interface RmiUserService extends Remote { User login(String username, String password) throws RemoteException; void create(String username, String password) throws RemoteException;}public class RmiUserServiceImpl extends UnicastRemoteObject implements RmiUserService { protected RmiUserServiceImpl() throws RemoteException { } private Map<String, String> users = new HashMap<String, String>(); public void create(String username, String password) { if (username == null || password == null) throw new IllegalArgumentException("Invalid args."); if (users.get(username) != null) throw new RuntimeException("User exist!"); users.put(username, password); } public User login(String username, String password) { if (username == null || password == null) throw new IllegalArgumentException("Invalid args."); if (password.equals(users.get(username))) return new User(username, password); throw new RuntimeException("Login failed."); } public static void main(String[] args) throws RemoteException, MalformedURLException, AlreadyBoundException { LocateRegistry.createRegistry(1099); Naming.bind("rmi://localhost:1099/UserService", new RmiUserServiceImpl()); }}public class Client { public static void main(String[] args) throws RemoteException, MalformedURLException, NotBoundException { RmiUserService service = (RmiUserService) Naming.lookup("rmi://localhost:1099/UserService"); service.create("xace", "1"); System.out.println(service.login("xace", "1")); }}调用:>rmic RmiUserServiceImpl>java Client
<bean id="userService" /> <bean id="rmiService" value="UserService"/> <property name="service" ref="userService"/> <property name="serviceInterface" value="example.rmi.UserService"/> <property name="registryPort" value="1099"/> </bean>
public static void main(String[] args) { new ClassPathXmlApplicationContext("config.xml"); }
public class Client { public static void main(String[] args) throws Exception { RmiProxyFactoryBean factory = new RmiProxyFactoryBean(); factory.setServiceInterface(UserService.class); factory.setServiceUrl("rmi://localhost:1099/UserService"); factory.afterPropertiesSet(); UserService service = (UserService) factory.getObject(); service.create("test", "password"); System.out.println(service.login("test", "password")); try { service.login("test", "bad-password"); } catch (Exception e) { System.out.println(e.getMessage()); } }}
<bean id="userServiceRmi" value="rmi://localhost:1099/UserService" /> <property name="serviceInterface" value="example.rmi.UserService" /> </bean>