说说RMI远程调用

开发步骤:
1.写接口,继承java.rmi.Remote
2.写该接口的实现类,并注册,注册代码
LocateRegistry.createRegistry(1099);
Naming.rebind(“rmi://:1099/registryName”, serverName);
3.客户端调用
客户端写接口,并调用,调用代码
Server server = (Server) Naming.lookup(“rmi://127.0.0.1:1099/registryName”);

示例如下:
package app;

import java.rmi.Remote;
import java.rmi.RemoteException;

public interface Server extends Remote {

String helloWorld()throws RemoteException;

}

package app;

import java.rmi.Remote;
import java.rmi.RemoteException;

public interface Server1 extends Remote{
String getMes()throws RemoteException;
}

package app;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

public class Server1Iml extends UnicastRemoteObject implements Server1 {

protected Server1Iml() throws RemoteException {
}

public String getMes() throws RemoteException {
    return "成功调用server1";
}

}

package app;

import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.server.UnicastRemoteObject;

public class ServerIml extends UnicastRemoteObject implements Server {

protected ServerIml() throws RemoteException {
}

public String helloWorld() throws RemoteException {
    return "hello world";
}

public static void main(String[] args) throws Exception{
    Server server = new ServerIml();
    LocateRegistry.createRegistry(1099);
    Naming.rebind("rmi://:1099/crazyit", server);
    Server1 server1 = new Server1Iml();
    Naming.rebind("rmi://:1099/server1", server1);
}

}

package app;

import java.rmi.Naming;

public class RMIClient {

public static void main(String[] args) throws Exception{
    Server server = (Server) Naming.lookup("rmi://127.0.0.1:1099/crazyit");
    String ms = server.helloWorld();
    System.out.println(ms);

    Server1 server1 = (Server1) Naming.lookup("rmi://127.0.0.1:1099/server1");
    String mes = server1.getMes();
    System.out.println(mes);
}

}

先启动服务端,再启动客户端,控制台打印如下:
hello world
成功调用server1

原理与应用:
1.RMI是对socket的封装,省去了socket通信和多线程的管理
2.对于大型分布式系统,我们要使用远程的方法,只要把远程的方法注册下即可通过RMI进行调用,当然,当前restful框架很多,我们也可以用通过对RMI封装写出自己的库

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值