Java RMI HelloWorld

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, 然后就可以像调用本地方法一样直接用.

 

上一篇:用jquery实现复选框全选全不选问题(完整版),在网络上怎么也找不到完整的解决方案,重要搞全了


下一篇:举个栗子看如何做MySQL 内核深度优化