RMI的简单实现

RMI 是java实现透明远程调用的重要机制。在远程调用中,客户端仅有服务器端提供的接口。通过此接口实现对远程服务器端的调用。

Sun JDK 6.0以前版本中的RMI实现均基于TCP/IP+BIO方式。RMI要求服务器端的接口继承Remote接口,接口上的每种方法必须抛出RemoteException,服务器端业务类需实现此接口,然后通过调用UnicastRemoteObject.exportObject来将此对象帮定到某端口上,最后将此对象注册到本地的LocateRegistry上。

1.1  服务端代码

//服务端对外提供的接口

Public interface Hello extends Remote{

   

    public String sayHello(String name) throws RemoteException;

}

实现类有两种方式:

1.  创建实例对象时绑定到某端口.通过继承UnicastRemoteObject(也可以用组合的方式)来实现

Public class HelloImpl extends UnicastRemoteObject implements Hello{

    private static final long serialVersionUID = 1L;

 

    Public HelloImpl() throws RemoteException {

       super();

       // TODO Auto-generated constructor stub

    }

 

    public String sayHello(String name) throws RemoteException {

       // TODO Auto-generatedmethod stub

       return "welcome,"+name;

    }

}

启动的方式也有两种:

1)       通过java.rmi.Naming来启动

//使用默认端口

LocateRegistry.createRegistry(1099);

Naming.rebind("hello", new HelloImpl());

//使用不同的端口

LocateRegistry.createRegistry(8888);

Naming.rebind("rmi://10.225.112.86:8888/hello",new HelloImpl());

2)       通过java.rmi.registry.Registry来启动

//指定端口(默认端口是1099

LocateRegistry.createRegistry(1099);

registry.rebind("hello", new HelloImpl());

 

2.  手动绑定到某端口. UnicastRemoteObject.exportObject来实现

 

Public class OtherHelloImpl  implements Hello{

   

    private static final long serialVersionUID = 1L;

   

    public String sayHello(String name) throws RemoteException {

       // TODO Auto-generatedmethod stub

       return "welcome,"+name;

    }

   

}

启动的方式也有两种:

1)       通过java.rmi.Naming来启动

//手动绑定到某端口

OtherHelloImpl otherHelloImpl=new OtherHelloImpl();

UnicastRemoteObject.exportObject(otherHelloImpl, 0);

 

//使用默认端口

LocateRegistry.createRegistry(1099);

Naming.rebind("hello", new HelloImpl());

//使用不同的端口

LocateRegistry.createRegistry(8888);

Naming.rebind("rmi://10.225.112.86:8888/hello",new HelloImpl());

 

2)       通过java.rmi.registry.Registry来启动

//手动绑定到某端口

OtherHelloImpl otherHelloImpl=new OtherHelloImpl();

UnicastRemoteObject.exportObject(otherHelloImpl,0);

//指定端口(默认端口是1099

LocateRegistry.createRegistry(1099);

registry.rebind("hello", new HelloImpl());

1.2  客户端代码

1)       通过java.rmi.Naming来访问

Hello hello=(Hello)Naming.lookup("rmi://10.225.112.86:8888/hello");  hello.sayHello("呵呵");

2)       通过java.rmi.registry.Registry来访问

Registry registry=LocateRegistry.getRegistry("10.225.112.86",8888);

Hello  hello=(Hello)registry.lookup("hello");        

hello.sayHello("呵呵");

 

1.3  注意

1.   rebind方法和bind方法的区别:

Bind不允许重复绑定,而rebind可以。


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值