com.gw.common.utils.ServerGwWrapper Maven / Gradle / Ivy
The newest version!
package com.gw.common.utils;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.log4j.BasicConfigurator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ConfigurableApplicationContext;
import com.app.common.cluster.ClusterManager;
import com.app.common.cluster.IClusterServerListener;
import com.app.common.cluster.ServerInfo;
import com.app.common.logger.AsyncSlf4jLoggerFactory;
import com.app.common.utils.IdUtil;
/**
* 服务入口封装
*
* @author deshuai.kong
*
*/
public class ServerGwWrapper {
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 serverKey = pc.getString("serverKey");
String clusterName = "ZK";
ServerInfo serverInfo = ConfigUtils.getServerInfo(serverKey);
Consts.Name = serverKey.replace("SERVER.", "");
ClusterManager.addServerListener(clusterName, serverSpec);
ClusterManager.startServer(clusterName, serverInfo);
}
public static void Start(final Class> serverName, final String configFile, String... args) throws Exception {
Start(serverName.getSimpleName(), configFile, new IClusterServerListener() {
Logger logger = LoggerFactory.getLogger(this.getClass());
AtomicBoolean serverStatus = new AtomicBoolean(false);
ConfigurableApplicationContext cc = null;
private void shutdownHook(final ServerInfo serverInfo) {
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
quit(serverInfo);
}
});}
public void quit(final ServerInfo serverInfo) {
logger.info("Received quit notify....");
try {
stop(serverInfo);
} catch (Exception e) {
logger.error("stop error for server", e);
}
logger.info("Quit");
}
@Override
public void stop(ServerInfo serverInfo) {
try {
if (serverStatus.get()) {
logger.info(serverInfo.getHost() + ":" + serverInfo.getPort() + ":" + serverInfo.getName()
+ ":stop");
if (cc != null) {
cc.close();
}
serverStatus.compareAndSet(true, false);
}
} catch (Exception e) {
logger.error("stop", e);
}
}
@Override
public void start(ServerInfo serverInfo) {
try {
if (!serverStatus.get()) {
if (serverInfo != null) {
Consts.Host = serverInfo.getHost();
Consts.ServerInfo = serverInfo.toString();
int workerId = Math.abs((Consts.ServerInfo+serverInfo.getSeqName()).hashCode() % 31);
IdUtil.setWorkerId(workerId);
}
shutdownHook(serverInfo);
cc = SpringApplication.run(serverName, args);
logger.info(serverInfo.getHost() + ":" + serverInfo.getPort() + ":" + serverInfo.getName()
+ ":start");
serverStatus.compareAndSet(false, true);
}
} catch (Exception e) {
logger.error("start", e);
}
}
});
}
}