基於nacos的服務平滑上下線方案


所謂平滑上下線簡單說就是系統發版升級過程對用戶無感知,不至於等到夜深人靜的時候偷偷去搞,某些請求時間可以長點,但不能失敗。

主要是基於naocs提供的SDK接口進行服務的注銷和注冊。

在對應服務中新增注銷服務的接口和注冊服務的接口。

代碼如下:

package com.gaopeng.cloud.controller;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.registry.NacosRegistration;
import com.alibaba.nacos.api.exception.NacosException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class NacosController {
    protected final transient Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    NacosDiscoveryProperties nacosDiscoveryProperties;

    @Autowired
    NacosRegistration nacosRegistration;

    /**
     * 服務注冊接口
     *
     * @return
     */
    @GetMapping(value = "/api/nacos/register")
    public String registerInstance() {
        String serviceName = nacosDiscoveryProperties.getService();
        String groupName = nacosDiscoveryProperties.getGroup();
        String clusterName = nacosDiscoveryProperties.getClusterName();
        String ip = nacosDiscoveryProperties.getIp();
        int port = nacosDiscoveryProperties.getPort();

        log.info("register from nacos, serviceName:{}, groupName:{}, clusterName:{}, ip:{}, port:{}", serviceName, groupName, clusterName, ip, port);
        try {
            nacosRegistration.getNacosNamingService().registerInstance(serviceName, groupName, ip, port, clusterName);

        } catch (NacosException e) {
            log.error("register from nacos error", e);
            return "error";
        }
        return "success";
    }

    /**
     * 服務注銷接口
     *
     * @return
     */
    @GetMapping(value = "/api/nacos/deregister")
    public String deregisterInstance() {
        String serviceName = nacosDiscoveryProperties.getService();
        String groupName = nacosDiscoveryProperties.getGroup();
        String clusterName = nacosDiscoveryProperties.getClusterName();
        String ip = nacosDiscoveryProperties.getIp();
        int port = nacosDiscoveryProperties.getPort();

        log.info("deregister from nacos, serviceName:{}, groupName:{}, clusterName:{}, ip:{}, port:{}", serviceName, groupName, clusterName, ip, port);
        try {
            nacosRegistration.getNacosNamingService().deregisterInstance(serviceName, groupName, ip, port, clusterName);

        } catch (NacosException e) {
            log.error("deregister from nacos error", e);
            return "error";
        }
        return "success";
    }

}

 

系統升級步驟:   

a、在系統升級前先調用注銷接口將目標服務實例注銷,服務實例列表中將會刪除該實例

b、注銷之后將這個實例服務進行打包部署

c、部署后,調用服務注冊接口將該服務重新注冊

d、重復a、b、c完成服務的平滑升級過程

缺點:

1、需要開發人員手動增加服務注銷和注冊的接口

2、存在時間窗口,服務實例狀態變化感知不實時


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM