K8S下SpringCloud应用无损下线

废话不多说直接上代码,一种2个步骤

步骤一: 添加以下代码到SpringCloud应用中

 



import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.cloud.nacos.registry.NacosAutoServiceRegistration;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * 使用了nacos注册中心的服务关闭端点配置
 */
@ConditionalOnClass(NacosAutoServiceRegistration.class)
@RestController
@RequestMapping("actuator")
@RequiredArgsConstructor
@Slf4j
public class NacosStopEndpoint {
    private final NacosAutoServiceRegistration nacosAutoServiceRegistration;
    /**
     * 注销服务后关闭应用前等待的时间(毫秒)
     */
    private int waitTime = 30000;


    /**
     * 关闭服务 <br>
     * 只接收localhost发起的请求
     *
     * @param request
     * @return
     */
    @PostMapping("stopService")
    public ResponseEntity<Boolean> stopNacosService(
            HttpServletRequest request) throws UnknownHostException {
        if (!request.getRemoteHost().equalsIgnoreCase("127.0.0.1")) {
            log.warn("非法访问 尝试关闭应用 远程地址[{}]", request.getRemoteHost());
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(false);//非本机访问直接return 防止外部攻击
        }
        new Thread(() -> {
            log.info("Nacos instance has been de-registered");
            nacosAutoServiceRegistration.stop();

            log.info("Waiting {} milliseconds...", waitTime);
            try {
                Thread.sleep(waitTime);
            } catch (InterruptedException e) {
                log.info(Thread.currentThread().getName() + " interrupted!", e);
            }
            log.info("Spring close……");
            ((ConfigurableApplicationContext) SpringUtil.getApplicationContext()).close();
            log.info("Spring closed……");
            System.exit(0);
        }, "Application Closed Thread").start();


        return ResponseEntity.ok(true);
    }
}

步骤二:

配置K8S的工作负载的preStop函数 , 如下
 

["curl","-X","POST","http://127.0.0.1:8080/actuator/stopService","&&","sleep","30"]

大功告成!从此以后应用下线再也不会丢流量了!

### Kubernetes (K8s) 与 Spring Cloud 的关系 Kubernetes (K8s) 和 Spring Cloud 均是现代微服务架构中的重要工具,但它们的目标和功能有所不同。Spring Cloud 主要关注于简化分布式系统的开发过程,提供了诸如配置管理、服务注册与发现、断路器等功能[^1]。而 Kubernetes 则是一个用于自动化部署、扩展以及管理容器应用的强大平台,其核心在于集群管理和调度。 #### 功能对比 - **服务发现** Kubernetes 提供内置的服务发现机制,通过 Service 对象实现流量路由并支持负载均衡。相比之下,Spring Cloud 使用 Eureka 或 Consul 等组件来完成相同任务[^3]。 - **配置管理** 在 Kubernetes 中,ConfigMap 和 Secret 被用来处理静态或敏感数据的外部化存储问题。而在 Spring Cloud 生态体系下,则有 Config Server 来集中管理配置文件[^5]。 - **弹性伸缩** Kubernetes 支持基于 CPU/内存指标或其他自定义条件下的水平 Pod 自动扩缩容(HPA),这使得动态调整工作负载成为可能。对于 Spring Boot 应用程序而言,在 K8s 上运行时也可以利用这一特性获得更好的性能表现。 #### 如何配合使用? 当将 Spring Cloud 微服务迁移到 Kubernetes 平台上时,可以考虑如下几个方面: 1. **服务发现兼容性** 如果已经在项目中集成了 `spring-cloud-kubernetes` 相关模块,则可以直接借助 Kubernetes 的原生服务能力来进行服务间调用而不需额外维护独立的服务注册中心[^2]。 2. **配置同步** 将原本由 Spring Cloud Config 托管的内容转换成适合 Kubernetes 的形式——即存放到 ConfigMaps 或 Secrets 当中,并修改应用程序逻辑读取这些新来源的数据项[^4]。 3. **健康检查端点暴露** 确保每个微服务都按照标准开放了必要的探针接口(LivenessProbe & ReadinessProbe),以便 Kubelet 定期检测实例状态从而决定是否重启或者移除有问题的副本。 以下是创建一个简单 Sentinel Deployment 的 YAML 示例代码片段: ```yaml apiVersion: apps/v1 kind: Deployment metadata: name: yueyang-sentinel-deploy namespace: yueyang-cloud spec: replicas: 1 selector: matchLabels: app: sentinel template: metadata: labels: app: sentinel spec: containers: - name: sentinel-container image: 'registry.cn-shenzhen.aliyuncs.com/xiaohh-docker/sentinel:1.8.6' ports: - containerPort: 8718 --- apiVersion: v1 kind: Service metadata: name: yueyang-sentinel-svc namespace: yueyang-cloud spec: type: ClusterIP ports: - port: 8718 targetPort: 8718 protocol: TCP selector: app: sentinel ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值