com.app.common.utils.ServerWrapper Maven / Gradle / Ivy
The newest version!
package com.app.common.utils;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.log4j.BasicConfigurator;
import com.app.common.cluster.ClusterManager;
import com.app.common.cluster.IClusterServerListener;
import com.app.common.cluster.ServerInfo;
import com.app.common.db.DBUtils;
import com.app.common.logger.AsyncSlf4jLoggerFactory;
/**
* 服务入口封装
*
* @author deshuai.kong
*
*/
public class ServerWrapper {
public static void StartDB(final String serverName, final String configFile, IClusterServerListener serverSpec)
throws Exception {
BasicConfigurator.configure();
PropertiesConfiguration pc = new PropertiesConfiguration(configFile);
AsyncSlf4jLoggerFactory.initialize(pc);
String dbSourceName = pc.getString("Cluster.DB.Name");
String dbConfigPath = pc.getString("Cluster.DB.Config");
DBUtils.init(dbSourceName, dbConfigPath);
String clusterName=pc.getString("Cluster.ClusterName");
ClusterManager.addServerListener(clusterName, serverSpec);
ServerInfo serverInfo = getServerInfo(pc);
ClusterManager.startServer(clusterName, serverInfo);
}
public static void Start(final String serverName, final String configFile, IClusterServerListener serverSpec)
throws Exception {
BasicConfigurator.configure();
PropertiesConfiguration pc = new PropertiesConfiguration(configFile);
AsyncSlf4jLoggerFactory.initialize(pc);
String clusterName=pc.getString("Cluster.ClusterName");
ClusterManager.addServerListener(clusterName, serverSpec);
ServerInfo serverInfo = getServerInfo(pc);
ClusterManager.startServer(clusterName, serverInfo);
}
private static ServerInfo getServerInfo(PropertiesConfiguration pc) {
ServerInfo serverInfo = new ServerInfo();
String host = pc.getString("Cluster.Host");
String ClusterName = pc.getString("Cluster.ClusterName");
if (ClusterName.equals("DB") && host.equals("127.0.0.1")){
host = getIP(host);
}
serverInfo.setName(pc.getString("Cluster.Name"));
serverInfo.setType(pc.getInt("Cluster.Type"));
serverInfo.setGroup(pc.getString("Cluster.Group"));
serverInfo.setHost(host);
serverInfo.setPort(pc.getInt("Cluster.Port"));
HashMap hm = new HashMap<>();
hm.put("Cluster.DB.HeartPeriod", pc.getString("Cluster.DB.HeartPeriod","2"));
hm.put("Cluster.Zookeeper.Host", pc.getString("Cluster.Zookeeper.Host","127.0.0.1"));
hm.put("Cluster.Zookeeper.port", pc.getInt("Cluster.Zookeeper.port",2183));
serverInfo.setAtts(hm);
return serverInfo;
}
private static String getIP(String host){
String ip = host;
try {
String hostName = InetAddress.getLocalHost().getHostName();
ip = InetAddress.getByName(hostName).getHostAddress();
} catch (UnknownHostException e) {
e.printStackTrace();
}
return ip;
}
}