Java RMI HelloWorld

时间:2021-07-18 00:53:16

Java RMI HelloWorld

 

RMI 远程方法调用. 顾名思义就是可以像调用本地程序方法一样调用远程(其他JVM)的程序方法.

 

分为3个部分:

Stub:中介,代理. 封装了远程对象的调用,客户端需要通过stub与server交流

RemoteServer,:远端服务提供者.也就是RemoteObject

Client:客户端

 

代码示意:

 

RemoteObject, 远程服务提供者, 我写了一个main方法,在本地6600端口启动这个服务,

想要启动服务,只要run即可

package demo2;

 

import java.rmi.Naming;

import java.rmi.RemoteException;

import java.rmi.registry.LocateRegistry;

import java.rmi.server.UnicastRemoteObject;

 

public
class
RemoteEchoServer
extends UnicastRemoteObject implements RemoteEcho {

 

    protected RemoteEchoServer() throws RemoteException {

        super();

    }

 

    @Override

    public Object echo(Object object) throws RemoteException {

        return
object;

    }

 

    public
static
void main(String[] args) throws Exception {

        RemoteEchoServer server = new RemoteEchoServer();

        LocateRegistry.createRegistry(6600);

        Naming.rebind("rmi://127.0.0.1:6600/RemoteEchoServer", server);

    }

 

}

 

 

Stub,代理,与RemoteObject交流均需要通过它

 

package demo2;

 

import java.rmi.Remote;

import java.rmi.RemoteException;

 

public
interface
RemoteEcho
extends Remote {

    Object echo(Object object) throws RemoteException;

}

 

对Stub的进一步封装,即如何得到Stub对象

package demo2;

 

import java.rmi.Naming;

 

public
class RemoteEchoFactory {

 

    public
static RemoteEcho getEcho() throws Exception {

        return (RemoteEcho) Naming.lookup("rmi://127.0.0.1:6600/RemoteEchoServer");

    }

}

 

 

下面就是Client, server启动后,就能正常跑下面这个程序

package demo2;

 

public
class RemoteEchoClient {

    public
static
void main(String[] args) throws Exception {

        long
start = System.currentTimeMillis();

        RemoteEcho echo = RemoteEchoFactory.getEcho();

        System.out.println(echo.echo("kiss u"));

        System.out.println(System.currentTimeMillis()-start);

    }

}

 

Client 通过本地的Factory得到封装好的Stub, 他指向了RemoteObject, 然后就可以像调用本地方法一样直接用.