JDK 5.0以后对RMI的改进

    技术2022-05-11  47

       RMI即远程方法调用,是JAVA调用远程对象方法的一种方式,网上很多经典的例子都是JDK 5.0以前较早版本的RMI,运行程序前运行rmiregistry命令为远程对象开启命名服务,有时还要设置codebase,尤其是codebase如果设置的不对的话,就会报错找不到XXX_Stub类的异常,感觉很麻烦。

        JDK 5.0以后对RMI进行了改进,只要在程序中修改一部分代码,就可以省略上面的步骤。具体的修改方式如下:

        较早版本的RMI:

    IRMIImpl impl = new IRMIImpl(); Naming.rebind("rmi://localhost:1111/mytask", impl);

     

        在新的版本中,使用java.rmi.registry.Registry接口处理对象的绑定:

    Registry registry = null; int port = 1111; try { registry = LocateRegistry.getRegistry("localhost", port); registry.list(); System.out.println("Register the exist server!"); } catch (final Exception e) { try { registry = LocateRegistry.createRegistry(port); System.out.println("Register the server!port=" + port); } catch (final Exception ee) { ee.printStackTrace(); } } try { IRMIImpl impl = new IRMIImpl(); registry.rebind("mytask", impl); System.out.println("mytask server start!"); } catch (Exception e) { e.printStackTrace(); }

        这段代码首先检测给定的IP及端口是否被使用,如未使用则新建一个registry。

        使用新版本的RMI后在一定程度上对RMI的配置有了一定的改进,减少了配置RMI的难度(本人是新手,如果有什么错误,欢迎指正O(∩_∩)O~)


    最新回复(0)