RMI

  • 介绍
RMI是Java的一组拥护开发分布式应用程序的API。RMI使用Java语言接口定义了远程对象,它集合了Java序列化和Java远程方法协议(Java Remote Method Protocol)。简单地说,这样使原先的程序在同一操作系统的方法调用,变成了不同操作系统之间程序的方法调用,由于J2EE是分布式程序平台,它以RMI机制实现程序组件在不同操作系统之间的通信。比如,一个EJB可以通过RMI调用Web上另一台机器上的EJB远程方法。
  • 示例
[codesyntax lang="java" lines="normal"]
package org.suren;

import java.rmi.Naming;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.server.UnicastRemoteObject;

/**
 * @author suren
 * @date 2015-3-31
 *
 *       http://surenpi.com
 */
public class Main
{

	/**
	 * @param args
	 */
	public static void main(String[] args)
	{
		new Thread()
		{
			public void run()
			{
				try
				{
					OsgiServiceProxy osgiServiceProxy = new DefaultOsgiServiceProxy();
					LocateRegistry.createRegistry(8989);

					System.out.println("Prepare to Bind Proxy");

					Naming.bind("rmi://localhost:8989/"
							+ OsgiServiceProxy.class.getName(),
							osgiServiceProxy);
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
			}
		}.start();

		new Thread()
		{
			public void run()
			{
				while (true)
				{
					OsgiServiceProxy osgiServiceProxy = null;
					try
					{
						System.out
								.println("模拟客户端线程,获取Java远程对象osgiServiceProxy");

						osgiServiceProxy = (OsgiServiceProxy) Naming
								.lookup("rmi://localhost:8989/"
										+ OsgiServiceProxy.class.getName());

						if (osgiServiceProxy != null)
						{
							osgiServiceProxy.hello();

							break;
						}
						else
						{
							continue;
						}
					}
					catch (Exception e)
					{
						e.printStackTrace();
					}
				}

				System.exit(0);
			}
		}.start();
	}

}

/**
 * @author suren
 * @date 2015-3-31
 *
 *       http://surenpi.com
 */
interface OsgiServiceProxy extends Remote
{
	public void hello() throws RemoteException;
}

/**
 * @author suren
 * @date 2015-3-31
 *
 *       http://surenpi.com
 */
class DefaultOsgiServiceProxy extends UnicastRemoteObject implements
		OsgiServiceProxy
{

	/**
	 * @throws RemoteException
	 */
	protected DefaultOsgiServiceProxy() throws RemoteException
	{
		super();
	}

	private static final long	serialVersionUID	= 1L;

	public void hello() throws RemoteException
	{
		System.out.println("DefaultOsgiServiceProxy say hello.");
		System.out.println("来自遥远的RMI对象。");
	}

}
[/codesyntax]
  • 异常
no security manager: RMI class loader disabled 如果出现以上的异常信息,你可以考虑是不是类加载有问题。例如:你基于osgi开发的,而且要发布一个内部类,就可能会有这样的异常出现。 java.rmi.server.ExportException: internal error: ObjID already in use 如果你是在Linux环境下部署的,可以查看/etc/hosts文件中是不是把本地的ip地址配置错误了,如果是的话,修改后重启程序。
  • 参考
http://baike.baidu.com/link?url=OEqaBZJ_AvFb07SM2tqrm4_ETlAl_n9msSXvnieHpTxRhk74a6lC6hrWsqfqp999Q1JBtupHyJ44pY6IA8SSS_ http://lavasoft.blog.51cto.com/62575/91679/

你可能感兴趣的:(java,rmi)