【Ice】【07】新建maven項目user-service 部署方式一:使用IceGrid + Ice Registry部署

參考文檔

https://blog.csdn.net/choumei1031/article/details/100746283

https://doc.zeroc.com/ice/3.6/ice-services/icegrid/getting-started-with-icegrid
https://doc.zeroc.com/ice/3.6/ice-services/icegrid/using-icegrid-deployment

在上一章的基礎上學習

1.配置啓動icegridregistry

mkdir -p /opt/ice_project/data/registry  /opt/ice_project/log/registry

vim /opt/ice_project/config/icegridregistry.conf

IceGrid.Registry.Client.Endpoints=tcp -p 4061 -h 192.168.1.25
IceGrid.Registry.Server.Endpoints=tcp
IceGrid.Registry.Internal.Endpoints=tcp
IceGrid.Registry.Data=/opt/ice_project/data/registry

IceGrid.Registry.PermissionsVerifier=IceGrid/NullPermissionsVerifier
IceGrid.Registry.AdminPermissionsVerifier=IceGrid/NullPermissionsVerifier

IceGrid.Registry.DynamicRegistration=1

Ice.LogFile=/opt/ice_project/log/registry/ice-registry.log

IceGrid.Registry.Trace.Locator=2

啓動

nohup icegridregistry --Ice.Config=/opt/ice_project/config/icegridregistry.conf  >/dev/null  2>&1 &

2.配置啓動icegridnode

mkdir -p /opt/ice_project/data/node1  /opt/ice_project/log/node1
 
vim /opt/ice_project/config/icegridnode.conf

Ice.Default.Locator=IceGrid/Locator:tcp -h 192.168.1.25 -p 4061

IceGrid.Node.Name=node1
IceGrid.Node.Endpoints=tcp
IceGrid.Node.Data=/opt/ice_project/data/node1

Ice.StdErr=/opt/ice_project/log/ice-StdErr.log
Ice.StdOut=/opt/ice_project/log/ice-StdOut.log

IceGrid.Node.Trace.Adapter=2

啓動

nohup  icegridnode --Ice.Config=/opt/ice_project/config/icegridnode.conf  >/dev/null  2>&1 &

3.在/opt/ice_project/app/userservice/config新建配置app_user_service.xml


vim /opt/ice_project/app/userservice/config/app_user_service.xml 

<icegrid>
  <application name="UserService">
	<server-template id="UserServiceTemp">
	<parameter name="id"/>
	<icebox id="UserService${id}" exe="java" activation="on-demand">
		<option>IceBox.Server</option>
		<env>CLASSPATH=/opt/ice_project/app/userservice/lib/*</env>
		<service name="UserService" entry="com.yinzhen.demo.ice.userservice.UserServiceServerIceBox">
			<adapter name="UserService" id="UserService${id}" replica-group="UserServiceGroup"/>
		</service>
	</icebox>
	</server-template>
	
	<replica-group id="UserServiceGroup">
		<load-balancing type="round-robin" n-replicas="0"/>
		<object identity="UserService" type="::user::UserService"/>
	</replica-group>
	
	<node name="node1">
	<server-instance template="UserServiceTemp" id="1"/>
	</node>
	
  </application>
</icegrid>

4.配置啓動icegridadmin

vim /opt/ice_project/config/icegridadmin.conf

Ice.Default.Locator=IceGrid/Locator:tcp -h 192.168.1.25 -p 4061

啓動 用戶名密碼任意
icegridadmin -u test -p test --Ice.Config=/opt/ice_project/config/icegridadmin.conf

application add "/opt/ice_project/app/userservice/config/app_user_service.xml"

查看
application list

如果修改了app_user_service.xml需要更新
application update --no-restart "/opt/ice_project/app/userservice/config/app_user_service.xml"

application update "/opt/ice_project/app/userservice/config/app_user_service.xml"

查看文件修改內容
application diff --servers "/opt/ice_project/app/userservice/config/app_user_service.xml"

5.啓動server UserService1是inbox的id

server start UserService1

查看
server list

6.客戶端訪問工具類IceClientUtil

public class IceClientUtil {
 
    private static Logger LOG = LoggerFactory.getLogger(IceClientUtil.class);
 
    private static volatile Ice.Communicator communicator = null;
 
    private static Map<Class, ObjectPrx> classObjectPrxMap = new HashMap<Class, ObjectPrx>();
 
    private static volatile long lastAccessTimestamp;
    private static volatile MonitorThread monitorThread;
    private static long idleTimeOutSeconds = 0;
    private static String iceLocator = null;
    private static final String locatorKey = "--Ice.Default.Locator";
 
    //延遲加載Communicator
    public static Ice.Communicator getIceCommuicator(){
        if(communicator == null){
            synchronized (IceClientUtil.class){
                if(communicator == null){
				
				    iceLocator = "IceGrid/Locator:tcp -h 192.168.1.25 -p 4061";
                    idleTimeOutSeconds = 50000;
					//可以使用配置文件優化
                    //ResourceBundle resourceBundle = ResourceBundle.getBundle("iceclient", Locale.ENGLISH);
                    //iceLocator = resourceBundle.getString(locatorKey);
                    //idleTimeOutSeconds = Integer.parseInt(resourceBundle.getString("idleTimeOutSeconds"));
                    System.out.println("Ice Client's locator is "+iceLocator + " proxy cache time out seconds :"+idleTimeOutSeconds);
                    String[] initParams = new String[]{locatorKey+"="+iceLocator};
                    communicator = Ice.Util.initialize(initParams);
                    createMonitorThread();
                }
            }
        }
        lastAccessTimestamp = System.currentTimeMillis();
        return communicator;
    }
 
    private static void createMonitorThread(){
        monitorThread = new MonitorThread();
        monitorThread.setDaemon(true);
        monitorThread.start();
    }
 
    public static void closeCommunicator(boolean remveServiceCache){
        synchronized (IceClientUtil.class){
            if(communicator != null){
                safeShutdown();
                monitorThread.interrupt();
                if(remveServiceCache && !classObjectPrxMap.isEmpty()){
                    try {
                        classObjectPrxMap.clear();
                    }catch (Exception e){
                        LOG.error("關閉Communicator失敗:"+e.getMessage());
                        e.printStackTrace();
                    }
                }
            }
        }
    }
 
    private static void safeShutdown(){
        try {
            communicator.shutdown();
        }catch (Exception e){
            LOG.error("安全關閉失敗:"+e.getMessage());
            e.printStackTrace();
        }finally {
            communicator.destroy();
            communicator = null;
        }
    }
 
    //反射創建Object Proxy
    private static ObjectPrx createIceProxy(Ice.Communicator communicator,Class serviceCls){
        ObjectPrx objectPrx = null;
        String clsName = serviceCls.getName();
        String serviceName = serviceCls.getSimpleName();
        int pos = serviceName.lastIndexOf("Prx");
        if(pos <= 0){
            throw new IllegalArgumentException("Invalid ObjectPrx class ,class name must end with Prx");
        }
        String realSvName = serviceName.substring(0,pos);
        try {
            ObjectPrx base = communicator.stringToProxy(realSvName);
            objectPrx = (ObjectPrx)Class.forName(clsName+"Helper").newInstance();
            Method method = objectPrx.getClass().getDeclaredMethod("uncheckedCast",ObjectPrx.class);
            objectPrx = (ObjectPrx)method.invoke(objectPrx,base);
            return objectPrx;
        }catch (Exception e){
            LOG.error("加載ObjectPrx失敗:"+e.getMessage());
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
 
    //用於客戶端Api 獲取Ice服務實例
    public static ObjectPrx getServicePrx(Class serviceCls){
        ObjectPrx objectPrx = classObjectPrxMap.get(serviceCls);
        if(objectPrx != null){
            lastAccessTimestamp = System.currentTimeMillis();
            return objectPrx;
        }
 
        objectPrx = createIceProxy(getIceCommuicator(),serviceCls);
        classObjectPrxMap.put(serviceCls,objectPrx);
        lastAccessTimestamp = System.currentTimeMillis();
        return objectPrx;
    }
 
    static class MonitorThread extends Thread{
        @Override
        public void run() {
           while (!Thread.currentThread().isInterrupted()){
               try {
                   if(lastAccessTimestamp + idleTimeOutSeconds *1000L < System.currentTimeMillis()){
                       closeCommunicator(true);
                   }
               }catch (Exception e){
                   LOG.error("Client線程錯誤:"+e.getMessage());
                   e.printStackTrace();
               }
           }
        }
    }
}

7.IceGridClientTest測試調用

package com.yinzhen.demo.ice.userservice;

import com.yinzhen.demo.ice.user.UserInfo;
import com.yinzhen.demo.ice.user.UserServicePrx;

public class IceGridClientTest {
	
	public static void main(String[] args) throws Exception {
		UserServicePrx userServicePrx = (UserServicePrx) IceClientUtil.getServicePrx(UserServicePrx.class);
		if(userServicePrx == null){
			throw new Exception("qp == null");
		}
		UserInfo userInfo = userServicePrx.getUserInfoById("id");
		if(userInfo == null){
			throw new Exception("userInfo == null");
		}
		// 輸出服務端返回結果
		System.out.println(userInfo.remark);
	}

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章