/**
* nacos服务主动下线
*
* 主动下线方法中,1调nacos实例下线(no run),2.调nacos的超时(仅在springcloud服务中能* 和), * 最后选择用2
*/
public boolean nacosDown(Map map) {
log.info("nacosDown deregister from nacos, serviceName:{}, hostUrl:{}, namespace:{} ", finalServiceName, hostUrl, namespace);
// String finalServiceName = "DEFAULT_GROUP@@" + serviceName;
// final String finalServiceName = serviceName;
new Thread(
() -> {
try {
//由于它会比terminationGracePeriodSeconds先执行,所以如果立刻下线的话新的pods还没开好的话,
//应用会卡10秒左右, 所以预留60秒的可用时间
Thread.sleep(waitTime * 1000);
Properties properties = new Properties();
properties.setProperty("serverAddr", hostUrl);
// properties.setProperty("namespace", namespace);
//
NamingService naming = NamingFactory.createNamingService(properties);
// naming.registerInstance("nacos.test.3", "11.11.11.11", 8888, "TEST1");
// naming.deregisterInstance(finalServiceName, ip, port);
// List<Instance> instances = naming.selectInstances(finalServiceName, true);
//有bug,已提交gitbug issure #4819
//https://github.com/alibaba/nacos/issues/4819
// naming.deregisterInstance(finalServiceName, ip, port, clusterName);
//只能修改心跳周期了,改成1秒, 尽量延迟最低
Instance instance = new Instance();
instance.setIp(ip);
instance.setPort(port);
Map<String, String> metadata = new HashMap<String, String>();
// 设置心跳的周期,单位为秒,这里将心跳间隔设置为3秒:
metadata.put(PreservedMetadataKeys.HEART_BEAT_INTERVAL, "1000");
// 设置心跳超时时间,单位为秒,这里将心跳超时时间设为500毫秒
// 即服务端6秒收不到客户端心跳,会将该客户端注册的实例设为不健康:
metadata.put(PreservedMetadataKeys.HEART_BEAT_TIMEOUT, "500");
// 设置实例删除的超时时间,单位为秒,这里将实例删除超时时间设为500毫秒,
// 即服务端9秒收不到客户端心跳,会将该客户端注册的实例删除:
metadata.put(PreservedMetadataKeys.IP_DELETE_TIMEOUT, "500");
instance.setMetadata(metadata);
naming.registerInstance(finalServiceName, instance);
log.info("sucess deregister from nacos, serviceName:{}, clusterName:{}, ip:{}, port:{}", finalServiceName, clusterName, ip, port);
log.info("sucess deregister instants size : {} ", naming.getAllInstances(finalServiceName).size());
log.info("sucess deregister instants size : {} ", naming.selectInstances(finalServiceName, false).size());
// naming.shutDown();
} catch (NacosException e) {
log.info("error deregister from nacos, serviceName:{}, clusterName:{}, ip:{}, port:{}", finalServiceName, clusterName, ip, port);
e.printStackTrace();
} catch (InterruptedException e) {
log.info("error thread deregister from nacos, serviceName:{}, clusterName:{}, ip:{}, port:{}", finalServiceName, clusterName, ip, port);
e.printStackTrace();
}
}
).start();
log.info("deregister from nacos, serviceName:{}, clusterName:{}, ip:{}, port:{}", finalServiceName, clusterName, ip, port);
return true;
}