SpringCloud + Eureka 微服务优雅下线

先附上网上解决方案:

 https://www.jianshu.com/p/14c0b6c389f0

https://blog.csdn.net/hunger_wang/article/details/87722129

网上清一色基本都是这几种方法

下面介绍我自己的方法

① 注入ApplicationInfoManager管理器,可用于获取当前微服务的状态或者修改微服务状态

import com.netflix.appinfo.ApplicationInfoManager;

// 注入 ApplicationInfoManager 
@Autowired
private ApplicationInfoManager applicationInfoManager;

② 通过 ApplicationInfoManager修改当前微服务状态为下线

import com.netflix.appinfo.InstanceInfo

// 将当前微服务的状态设置为下线
applicationInfoManager.getInfo().setStatus(InstanceInfo.InstanceStatus.DOWN);

我的做法是新建一个RestController类,然后开放自定义修改微服务状态的接口,接着Eureka上该微服务的状态就会变成DOWN

然后sleep 60 等待60秒,直接进程kill掉

当然你也可以对接口改进,新增Timer,TimerTask,等待X秒后然后调用shutdown接口(要使用shutdown接口需要弄其它配置支持)

这是我的代码,没写成直接下线,而是改成微服务状态变换

import com.netflix.appinfo.ApplicationInfoManager;
import com.netflix.appinfo.InstanceInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class EurekaStatusConfig {
    @Autowired
    private ApplicationInfoManager applicationInfoManager;

    @GetMapping("eurekaChangeStatus")
    public String change(String status) {
        InstanceInfo.InstanceStatus instanceStatus = InstanceInfo.InstanceStatus.toEnum(status.toUpperCase());
        applicationInfoManager.getInfo().setStatus(instanceStatus);
        return "服务已经下线!";
    }
}

如果帮到你,请点个赞吧 O(∩_∩)O~

猜你喜欢

转载自blog.csdn.net/qq171563857/article/details/90603826