RMI入门实例

RMI是JavaEE的核心组件,是分布式开发的基础。下面通过一个例子来展示RMI的应用过程:

  • 建立业务接口

提供RMI服务的接口类必须继承java.rmi.Remote接口,同时所有的业务方法必须抛出RemoteException。

PerfectTime.java

package com.adams.rmi;

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

public interface PerfectTime extends Remote {
	public String getPerfectTime(int i) throws RemoteException;
}
  • 实现业务接口

实现PerfectTime接口的类必须继承UnicastRemoteObject类java.rmi.server.UnicastRemoteObject。

PerfectTimeImpl.java

package com.adams.rmi;

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

public class PerfectTimeImpl extends UnicastRemoteObject implements PerfectTime {

	private static final long serialVersionUID = -4970146374243011725L;

	protected PerfectTimeImpl() throws RemoteException {
		// super();
	}

	@Override
	public String getPerfectTime(int i) throws RemoteException {
		return "hello,Adams!This is RMI Example.===" + i;
	}

}
  • 创建服务端,注册业务实例,启动服务

RemoteServer.java

package com.adams.rmi;

import java.net.MalformedURLException;
import java.rmi.AlreadyBoundException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;

public class RemoteServer {
	private String ip = "localhost";
	private int port = 8019;
	public void init() {
		try {
			LocateRegistry.createRegistry(port);
			PerfectTime pt = new PerfectTimeImpl();
			Naming.bind("//" + ip + ":" + port + "/PerfectTime", pt);
		} catch(RemoteException e) {
			e.printStackTrace();
		} catch(MalformedURLException e) {
			e.printStackTrace();
		} catch(AlreadyBoundException e) {
			e.printStackTrace();
		}
	}
	
	public String getIp() {
		return ip;
	}

	public static void main(String[] args) {
		RemoteServer rs = new RemoteServer();
		/*//服务器有多个ip的时候,就要指明rmi服务ip
		System.setProperty("java.rmi.server.hostname", rs.getIp());  */
		System.out.println("RMI服务初始化...");
		rs.init();
		System.out.println("RMI服务初始化完毕.");
	}

}
  • 建立客户端,并通过客户端调用RMI接口

RemoteClient.java

package com.adams.rmi;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;

public class RemoteClient {
	private String ip = "localhost";
	private int port = 8019;
	private PerfectTime perfectTime;
	
	public RemoteClient() {
		try {
			perfectTime = (PerfectTime)Naming.lookup("rmi://" + ip + ":" + port + "/PerfectTime");
		} catch(MalformedURLException e) {
			e.printStackTrace();
		} catch(RemoteException e) {
			e.printStackTrace();
		} catch(NotBoundException e) {
			e.printStackTrace();
		}
	}
	
	public String getTime(int i) {
		String ret = "";
		try {
			ret = perfectTime.getPerfectTime(i);
		} catch(RemoteException e) {
			e.printStackTrace();
		}
		return ret;
	}

	public static void main(String[] args) {
		RemoteClient rc = new RemoteClient();
		System.out.println(rc.getTime(198));
	}

}

执行结果:

hello,Adams!This is RMI Example.===198

 

你可能感兴趣的:(JavaEE,string,javaee,class,interface,服务器)