Java RMI (2)
8. Activation
通过调用UnicastRemoteObject.exportObject()方法发布的远程对象的生命周期是从发布起,一直到所在应用停止为止。RMI的activation机制允许在rmid中发布可激活的激活描述符,只有当客户端发起远程调用时才真正构造远程对象。
8.1 MyRemote类
public interface MyRemote extends Remote{public Product getProduct(int productId) throws RemoteException;} public class Product implements Serializable{private static final long serialVersionUID = 5206082551028038485L;private int id;private String name;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String toSring(){return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE).append("id").append("name").toString();}} public abstract class RmiUtil {public static int getRegistryPort(){return Registry.REGISTRY_PORT;}public static Registry getRegistry() throws Exception{return getRegistry(Registry.REGISTRY_PORT);}public static Registry getRegistry(int port) throws Exception{Registry reg = LocateRegistry.getRegistry(port);reg.list();return reg;}public static Registry getRegistry(String host) throws Exception{return LocateRegistry.getRegistry(host, Registry.REGISTRY_PORT);}public static Registry getRegistry(String host, int port) throws Exception{return LocateRegistry.getRegistry(host, port);}}public class MyRemoteImpl implements MyRemote{@Overridepublic Product getProduct(int productId) throws RemoteException {final Product product = new Product();product.setId(productId);product.setName("xiao");return product;}public static void main(String[] args) throws Exception{MyRemoteImpl remote = new MyRemoteImpl();MyRemote myRemote = (MyRemote)UnicastRemoteObject.exportObject(remote, 0);Registry reg = RmiUtil.getRegistry();reg.bind("MyRemote", myRemote);System.out.println("server started");}}public class Client {public static void main(String[] args) throws Exception {Registry reg = RmiUtil.getRegistry();MyRemote remote = (MyRemote)reg.lookup("MyRemote");System.out.println(" name = " + remote.getProduct(1).getName());}}