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

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会对其进行垃圾回收。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值