Spring Cloud 微服务中 gateway 网关如何设置健康检测端点

主要是为了让 k8s 识别到网关项目已经就绪,但是又不想在里面通过 Controller 实现。因为在 Controller 中这样做并不是最佳实践,因为 Gateway 的设计初衷是专注于路由和过滤,而不是业务逻辑的处理。

Gateway 中配置健康检查端点可以通过以下方式进行(可根据实际需求进行扩展):

1. 自定义路由配置(推荐)

可以使用 Spring Cloud Gateway 的 Java DSL 配置自定义的路由,以在网关中添加一个专门用于健康检查的路由。例如:

java 复制代码
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.ServerResponse;

import static org.springframework.web.reactive.function.server.RequestPredicates.*;

@Configuration
public class GatewayConfig {

    @Bean
    public RouterFunction<ServerResponse> healthCheckRoute() {
        return route(GET("/health-check"),
                request -> ServerResponse.status(HttpStatus.OK)
                        .body(BodyInserters.fromValue("Gateway is healthy")));
    }
}

这样,就可以通过访问 http://localhost:8080/health-check 来执行健康检查。

上面代码的描述说明:

  • route 方法是 Spring Cloud Gateway 提供的 Java DSL(领域特定语言,Domain-Specific Language)中的一部分。这是一种声明性的路由配置方式,允许使用流畅的 API 配置路由规则。
  • GatewayConfig 类中,healthCheckRoute 方法返回一个 RouterFunction<ServerResponse>,这个函数式接口是用来配置路由规则的。route 方法是用于创建路由规则的,它接收一个请求谓词(RequestPredicate)和一个处理函数(HandlerFunction)作为参数。
  • 具体来说,route(GET("/health-check"), ...) 表示创建一个满足 GET 请求谓词,并且路径为 /health-check 的路由规则。接着,通过 ServerResponse 构建响应,这里设置为 HTTP 状态码 HttpStatus.OK,并返回一条消息 "Gateway is healthy"。

这种方式更加直观和类型安全,相比于配置文件,可以在代码中清晰地看到路由规则的定义。这是 Spring WebFlux 框架提供的一种路由方式,用于构建响应式的、非阻塞的 Web 应用程序。

2. 利用 Actuator 健康检查

可以通过配置属性来启用 Actuator,并将其端口设置为用于健康检查的端口。

要想使用 Actuator,项目中需要引入 Actuator 的依赖:

xml 复制代码
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

application.propertiesapplication.yml 配置文件中添加以下配置:

bash 复制代码
# application.properties
management.endpoints.web.exposure.include=health
management.server.port=8081  # 可与 server.port 相同或不同

或者

yaml 复制代码
# application.yaml
management:
  endpoints:
    web:
      exposure:
        include: health
  server:
    port: 8081  # 可与 server.port 相同或不同

上述配置将 Actuator 暴露的端点配置为仅包含 health,并将健康检查端口设置为 8081。此时,可以通过访问 http://localhost:8081/actuator/health 来执行健康检查。

【注】Actuator 中还有其他配置,实际使用过程中建议查看 官方文档 了解相应的配置,以免给自己挖坑。比如 /env/beans,它们可能会泄漏应用程序的敏感信息。确保只在受信任的环境中启用这些端点,并谨慎处理它们的输出。

3. 通过 RestController 实现(不推荐)

如果有业务逻辑需要处理,更推荐将业务逻辑集中在后端微服务中,而将 Gateway 专注于路由和过滤。这样可以更好地保持清晰的代码结构和单一责任原则。

java 复制代码
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.GetMapping;

/**
 * @author roc
 * @date 2024/1/16 14:14
 */
@RestController
@RequestMapping("/health")
public class HealthController {

    @GetMapping("/check")
    public String check() {
        return "Gateway is healthy";
    }
}

如果还有其他方式请大佬们分享一下。

个人博客:Roc's Blog

相关推荐
大腕先生9 小时前
微服务环境搭建&架构介绍(附超清图解&源代码)
微服务·云原生·架构
A ?Charis16 小时前
记录一下_treafik使用Gateway-APi使用的细节参数
gateway
WeiLai111216 小时前
面试基础--微服务架构:如何拆分微服务、数据一致性、服务调用
java·分布式·后端·微服务·中间件·面试·架构
茶本无香18 小时前
kafka+spring cloud stream 发送接收消息
spring cloud·kafka·java-zookeeper
Swift社区18 小时前
【微服务优化】ELK日志聚合与查询性能提升实战指南
spring·elk·微服务·云原生·架构
陌殇殇1 天前
002 SpringCloudAlibaba整合 - Feign远程调用、Loadbalancer负载均衡
java·spring cloud·微服务
m0_675447081 天前
Java版企电子招标采购系统源业码Spring Cloud + Spring Boot +二次开发+ MybatisPlus + Redis
java·spring cloud·企业电子招投标系统源码·招投标系统源码
LUCIAZZZ1 天前
EasyExcel快速入门
java·数据库·后端·mysql·spring·spring cloud·easyexcel
落落落sss1 天前
MongoDB
数据库·windows·redis·mongodb·微服务·wpf
黄名富1 天前
Spring Cloud — 深入了解Eureka、Ribbon及Feign
分布式·spring·spring cloud·微服务·eureka·ribbon