上一篇用RMI完成了远程对像的访问. RMI其中一个重要用途就是建JDNI服务.
1.建JDNI服务
public
class JdniImpl {
@SuppressWarnings( "unchecked")
public static void main(String args[]) throws NamingException, RemoteException {
LocateRegistry.createRegistry(8888);
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.rmi.registry.RegistryContextFactory");
env.put(Context.PROVIDER_URL, "rmi://localhost:8888");
InfoServer server = new InfoServer();
InfoConsult consult = new InfoConsultImpl(server.getMockData());
InitialContext ctx = new InitialContext(env);
ctx.rebind("java:comp/env/test", consult);
}
}
@SuppressWarnings( "unchecked")
public static void main(String args[]) throws NamingException, RemoteException {
LocateRegistry.createRegistry(8888);
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.rmi.registry.RegistryContextFactory");
env.put(Context.PROVIDER_URL, "rmi://localhost:8888");
InfoServer server = new InfoServer();
InfoConsult consult = new InfoConsultImpl(server.getMockData());
InitialContext ctx = new InitialContext(env);
ctx.rebind("java:comp/env/test", consult);
}
}
2.访问JDNI服务
package rmi;
import java.rmi.RemoteException;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class School {
public static void main(String args[]) throws NamingException, RemoteException {
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.rmi.registry.RegistryContextFactory");
env.put(Context.PROVIDER_URL, "rmi://localhost:8888");
InitialContext ctx = new InitialContext(env);
System.out.println(((InfoConsult)ctx.lookup("java:comp/env/test")).getAge("baby"));
}
}
import java.rmi.RemoteException;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class School {
public static void main(String args[]) throws NamingException, RemoteException {
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.rmi.registry.RegistryContextFactory");
env.put(Context.PROVIDER_URL, "rmi://localhost:8888");
InitialContext ctx = new InitialContext(env);
System.out.println(((InfoConsult)ctx.lookup("java:comp/env/test")).getAge("baby"));
}
}
输出结果1. RMI只是JDNI的一种实现方式.据说JBOSS就是采用的RMI做为JDNI的服务,具体没做考证.
本文转自 anranran 51CTO博客,原文链接:http://blog.51cto.com/guojuanjun/270786