本文作者:suxingrui
本文链接:https://blog.csdn.net/suxingrui/article/details/103795148
版权声明:本文为原创文章,转载请注明出处。
回顾2019年碰到的问题及解决方式
问题:简单给Nacos添加关闭服务的功能,支持平滑升级
问题发现:
Nacos提供对服务进行上下线的功能,这只会标记服务不可用,与Spring Cloud的应用的UP/DOWN状态类似。
并不会停止服务的进程,当新服务上线之后,还需要到服务器上关闭进程,不是很方便。
PS:大部分分布式多节点部署的场景是新服务节点直接覆盖老服务即可(包覆盖之后restart.sh),并不需要关闭服务的功能。
只是我这边刚好在测试环境,并不需要启动多个节点,但又需要支持平滑升级。
功能完成之后:
大致升级过程:
调查分析:
功能实现简单,大致原理就是给页面添加一个按钮
按钮调用Nacos后台,再远程调用应用服务提供的shutdown接口
解决方法:
1、应用服务实现接口:
@RestController
@RequestMapping
public class ShutdownController {
@PostMapping(value = {"/remote/instance/shutdown", "/instance/shutdown"})
public void shutdown(String key) {
if ("55ac348750604eb593c493abf736686f".equals(key)) {
System.exit(0);
}
}
}
2、改造Nacos
关键修改点:
@CanDistro
@RequestMapping(value = "/shutdown", method = RequestMethod.PUT)
public String shutdown(HttpServletRequest request) throws Exception {
String serviceName = WebUtils.required(request, CommonParams.SERVICE_NAME);
String namespaceId = WebUtils.optional(request, CommonParams.NAMESPACE_ID, Constants.DEFAULT_NAMESPACE_ID);
Instance instance = parseInstance(request);
serviceManager.registerInstance(namespaceId, serviceName, instance);
Service service = serviceManager.getService(namespaceId, serviceName);
if (service == null) {
throw new NacosException(NacosException.INVALID_PARAM,
"service not found, namespace: " + namespaceId + ", service: " + serviceName);
}
List<Instance> allIPs = service.allIPs();
int otherEnableCount = 0;
for (Instance inst : allIPs) {
if (!inst.getInstanceId().equals(instance.getInstanceId()) && inst.isEnabled() && inst.getWeight() > 0.0D) {
otherEnableCount++;
}
}
if (otherEnableCount < 1) {
throw new NacosException(NacosException.SERVER_ERROR, "当前其他可用服务数少于1,不能停止。");
}
String url = "http://" + instance.getIp() + ":" + instance.getPort() + "/remote/instance/shutdown";
Map<String, String> params = new HashMap<>(1);
params.put("key", "55ac348750604eb593c493abf736686f");
HttpClient.asyncHttpPost(url, null, params, null);
return "ok";
}
其他的修改在Forked的一个分支上:Nacos分支
PS:分支基于Nacos 1.4.0版本,创建于2020/01/01