Java Rmi 远程方法调用

一: 服务端  暴露服务

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

/**
 * 1.定义远程接口,必须继承Remote接口,
 * 2.远程调用的方法必须抛出RemoteException异常 
 */
public interface ISayHello extends Remote {
	
	/**
	 * @param name
	 * @return
	 * @throws RemoteException  远程调用方法必须抛出RemoteException
	 */
	public String doSayHello(String name) throws RemoteException;
}

 

import java.rmi.RemoteException;
import com.xx.service.ISayHello;

/**
 * 远程接口实现
 */
public class ChinaSayHello implements ISayHello {

	public String doSayHello(String name) throws RemoteException {
		return "您好," + name;
	}
}
import java.net.MalformedURLException;
import java.rmi.AlreadyBoundException;
import java.rmi.Naming;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.server.UnicastRemoteObject;

import com.xx.service.ISayHello;
import com.xx.service.impl.ChinaSayHello;

/**
 * 
 * 暴露远程服务
 */
public class ServerMain {
	
	public static void main(String[] args) {
		//创建远程对象
		ISayHello sayHello = new ChinaSayHello();
		//url
		String serviceUrl = "//localhost:9999/sayhello";
		//java 默认对口是1099
		final int registryPort = 9999;
		//暴露服务
		exporter(sayHello, registryPort, serviceUrl);
	}
	
	/**
	 * 暴露服务
	 * @param object
	 * @param registryPort
	 * @param serviceUrl
	 */
	public static void exporter(Remote object,int registryPort, String serviceUrl) {
		int servicePort = 0;
		try {
			UnicastRemoteObject.exportObject(object, servicePort);
			LocateRegistry.createRegistry(registryPort);
			Naming.bind(serviceUrl, object);
			System.out.println("绑定成功.");
		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (AlreadyBoundException e) {
			e.printStackTrace();
		}
	}
}


二:客户端  远程方法调用

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

import com.xx.service.ISayHello;

/**
 * 客户端
 */
public class ClientMain {
	
	public static void main(String[] args) throws RemoteException {
		// 查找远程对象 
		ISayHello sayHello= getObject(ISayHello.class, "rmi://localhost:9999/sayhello");
		// 远程方法调用
		System.out.println(sayHello.doSayHello("张三"));
	}
	
	public static <T> T getObject(Class<T> clazs, String serviceUrl) {
		try {
			Object object = Naming.lookup(serviceUrl);
			return clazs.cast(object);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (NotBoundException e) {
			e.printStackTrace();
		}
		throw new RuntimeException();
	}
}


 

你可能感兴趣的:(java,String,object,Class,import,interface)