Rmi学习笔记2

上一篇用RMI完成了远程对像的访问. RMI其中一个重要用途就是建JDNI服务.
参考JAVA文档: http://java.sun.com/j2se/1.5.0/docs/guide/jndi/jndi-rmi.html
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);
  }
}
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"));
  }

}
输出结果1. RMI只是JDNI的一种实现方式.据说JBOSS就是采用的RMI做为JDNI的服务,具体没做考证.

你可能感兴趣的:(职场,JNDI,rmi,休闲)