com.github.houbbbbb.sso.scheduler.ServerStartJob Maven / Gradle / Ivy
The newest version!
package com.github.houbbbbb.sso.scheduler;
import com.github.houbbbbb.sso.config.SSOPFilterConfig;
import com.github.houbbbbb.sso.cons.SSOPConstants;
import com.github.houbbbbb.sso.nt.constants.SwitchConstants;
import com.github.houbbbbb.sso.nt.factory.ItemType;
import com.github.houbbbbb.sso.nt.factory.StaticFactory;
import com.github.houbbbbb.sso.nt.template.ClientTemplate;
import com.github.houbbbbb.sso.nt.template.ServerTemplate;
import com.github.houbbbbb.sso.nt.util.DebugUtil;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author : hbw
* @desctiption :
* @date : 2020-06-23 14:09
*/
public class ServerStartJob implements Job {
private static final Integer INI_DELAY = 0;
private String type;
private Integer clientRetryTimes;
private Long clientRetryTime;
private String serverHost;
private Integer serverPort;
private Boolean enabled;
public ServerStartJob(SSOPFilterConfig ssopFilterConfig){
this.type = ssopFilterConfig.getType();
this.clientRetryTimes = ssopFilterConfig.getClientRetryTimes();
this.clientRetryTime = ssopFilterConfig.getClientRetryTime();
this.serverHost = ssopFilterConfig.getServerHost();
this.serverPort = ssopFilterConfig.getServerPort();
this.enabled = ssopFilterConfig.getEnabled();
}
@Override
public void run() {
iniStart();
clientRestart();
}
/**
* 客户端重启
*/
public void clientRestart () {
if (TypeJudge.client(type, enabled)) {
final int unLimit = -1;
AtomicInteger retryTimes = new AtomicInteger(0);
ScheduledThreadPoolExecutor scheduler = Scheduler.getScheduler(Scheduler.Type.CLIENT_RESTART);
scheduler.scheduleAtFixedRate(() -> {
if (SwitchConstants.clientStatus) {
DebugUtil.debug("client", "restart ... ");
DebugUtil.info("client", "restart ... ");
startClient();
retryTimes.addAndGet(1);
}
int limitTimes = clientRetryTimes;
if (unLimit != limitTimes) {
if (retryTimes.addAndGet(1) > limitTimes) {
scheduler.shutdownNow();
}
}
}, INI_DELAY, clientRetryTime, TimeUnit.MILLISECONDS);
}
}
/**
* 服务启动
*/
public void iniStart () {
try {
if (TypeJudge.server(type, enabled)) {
DebugUtil.debug("server", "start ... ");
DebugUtil.info("server", "start ... ");
startServer();
}
if (TypeJudge.client(type, enabled)) {
DebugUtil.debug("client", "start ...");
DebugUtil.info("client", "start ...");
startClient();
}
} catch (Exception e) {e.printStackTrace();}
}
private void startClient() {
SwitchConstants.clientStatus = false;
ThreadPoolExecutor executor = StaticFactory.getThread(ItemType.CLIENT_THREAD);
executor.execute(() -> new ClientTemplate(serverHost, serverPort).run());
}
private void startServer() {
SwitchConstants.clientStatus = false;
ThreadPoolExecutor executor = StaticFactory.getThread(ItemType.SERVER_THREAD);
executor.execute(() -> new ServerTemplate(serverPort).run());
}
}