Java Rmi 远程方法调用

标签: javastringobjectimportclassinterface
1337人阅读 评论(1) 收藏 举报
分类:

一: 服务端  暴露服务

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();
	}
}


 

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:946707次
    • 积分:8291
    • 等级:
    • 排名:第2363名
    • 原创:83篇
    • 转载:10篇
    • 译文:6篇
    • 评论:329条
    博客专栏
    文章分类
    最新评论