`
Technoboy
  • 浏览: 154018 次
  • 性别: Icon_minigender_1
  • 来自: 大连
社区版块
存档分类
最新评论

Java RMI (2)

    博客分类:
  • J2SE
阅读更多
8. Activation
  通过调用UnicastRemoteObject.exportObject()方法发布的远程对象的生命周期是从发布起,一直到所在应用停止为止。RMI的activation机制允许在rmid中发布可激活的激活描述符,只有当客户端发起远程调用时才真正构造远程对象。

8.1 MyRemote类
public interface MyRemote extends Remote{
	
	public Product getProduct(int productId) throws RemoteException;
}

8.2 Product实现了Serializable
 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();
	}
}



8.3 RmiUtil工具类
 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);
	}
}



8.4 MyRemoteImpl实现类
public class MyRemoteImpl implements MyRemote{

	@Override
	public 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");
	}

}


8.5 Client客户端

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());
	}
}


9. 垃圾回收
   RMI采用其分布式垃圾回收功能收集不再被网络中任何客户程序所引用的远程服务对象。当前的分布式垃圾回收采用的是引用计数的方式(类似于Modula-3's Network Objects),因此无法检测到循环引用的情况,这要求程序员打破循环引用,以便无用的对象可以被回收。RMI运行时通过WeakReference引用远程对象,当某个远程对象不再被任何客户端引用时,JVM会对其进行垃圾回收。
2
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics