New file |
| | |
| | | package com.dy.common.mw.channel.rmi; |
| | | |
| | | import java.io.IOException; |
| | | import java.rmi.registry.LocateRegistry; |
| | | import java.rmi.registry.Registry; |
| | | import java.rmi.server.UnicastRemoteObject; |
| | | |
| | | import com.dy.common.mw.UnitAdapterInterface; |
| | | import com.dy.common.mw.UnitInterface; |
| | | import com.dy.common.mw.UnitCallbackInterface; |
| | | |
| | | public class RmiUnit implements UnitInterface { |
| | | |
| | | private static RmiUnit instance = new RmiUnit() ; |
| | | private static boolean started = false ; |
| | | |
| | | private static RmiUnitAdapter adapter ; |
| | | |
| | | private static RmiFrameWork rmiFrm = null ; |
| | | |
| | | |
| | | private RmiUnit(){} |
| | | |
| | | public static RmiUnit getInstance(){ |
| | | return instance ; |
| | | } |
| | | |
| | | |
| | | @Override |
| | | public void setAdapter(UnitAdapterInterface adapter) throws Exception { |
| | | if(adapter == null){ |
| | | throw new Exception("Rmi模块适配器对象不能为空!") ; |
| | | } |
| | | RmiUnit.adapter = (RmiUnitAdapter)adapter ; |
| | | RmiConfigVo vo = RmiUnit.adapter.getConfig() ; |
| | | if(vo == null){ |
| | | throw new Exception("Rmi模块属性配置对象不能为空!") ; |
| | | } |
| | | if(vo.port == null){ |
| | | throw new Exception("Rmi模块port属性值不能为空!") ; |
| | | } |
| | | if(vo.context == null || vo.context.trim().equals("")){ |
| | | throw new Exception("Rmi模块context属性值不能为空!") ; |
| | | } |
| | | } |
| | | /** |
| | | * 启动模块 |
| | | */ |
| | | public void start(UnitCallbackInterface callback) throws Exception { |
| | | if(!started){ |
| | | started = true ; |
| | | |
| | | RmiConfigVo vo = RmiUnit.adapter.getConfig() ; |
| | | |
| | | boolean isException = false ; |
| | | try { |
| | | |
| | | //改局域变量为静态全局变量,防止局域变量在无引用时被垃圾回收,从而客户端得不到RMI服务端 |
| | | if(rmiFrm == null){ |
| | | rmiFrm = new RmiFrameWorkImpl(RmiUnit.adapter); |
| | | } |
| | | |
| | | //连接到本地JNDI |
| | | Registry registry = LocateRegistry.createRegistry(vo.port); |
| | | |
| | | //解除注册 |
| | | UnicastRemoteObject.unexportObject(rmiFrm, true); |
| | | |
| | | //注册 |
| | | registry.bind(vo.context, UnicastRemoteObject.exportObject(rmiFrm, 0)); |
| | | |
| | | } catch (IOException e) { |
| | | e.printStackTrace(); |
| | | System.out.println("Rmi通信模块启动失败!"); |
| | | isException = true ; |
| | | } |
| | | |
| | | if(!isException){ |
| | | if(vo.showStartInfo != null && vo.showStartInfo){ |
| | | System.out.println("Rmi模块成功启动,端口:" + vo.port + ",上下文为:" + vo.context ); |
| | | } |
| | | } |
| | | callback.call(null); |
| | | } |
| | | } |
| | | |
| | | @Override |
| | | public void stop(UnitCallbackInterface callback) { |
| | | } |
| | | |
| | | |
| | | public static boolean isStarted() { |
| | | return started; |
| | | } |
| | | |
| | | public RmiUnitAdapter getAdapter() { |
| | | return adapter; |
| | | } |
| | | |
| | | |
| | | } |