SpringCloud2023.0.0中OpenFeign集成Sentinel的注意事项
2023-10-03 13:31:14
OpenFeign 与 Sentinel 集成:深入解析
概述
在 Spring Cloud 2023.0.0 中,OpenFeign 与 Sentinel 集成可以为远程服务调用提供限流、熔断和降级保护,从而增强服务的可用性和稳定性。
Sentinel 的关键配置
feign.sentinel.enabled 是用于控制是否启用 Sentinel 保护的配置参数。默认值为 false,表示未启用。当 feign.sentinel.enabled = true 时,Sentinel 将拦截 Feign 客户端发出的请求,并根据配置的规则进行相应操作。
错误分析:GetMapping that is not used by contract Default
当启用 Sentinel 保护时,可能会遇到 "GetMapping that is not used by contract Default" 错误。这是因为 Sentinel 拦截了 Feign 客户端发出的 GET 请求,但这些请求未在 Feign 接口中定义。
解决方案
有两种方法可以解决此错误:
1. 排除不需要拦截的请求
使用 @SentinelResource 注解并指定排除的请求,例如:
@FeignClient(name = "example-service")
@SentinelResource(exclude = {"/actuator/**"})
public interface ExampleService {
@GetMapping("/hello")
String hello();
}
2. 使用自定义 Feign 注解
定义一个自定义 Feign 注解并使用它标记不需要拦截的请求,例如:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface NonSentinel {
}
然后在 Feign 接口中使用此注解,例如:
@FeignClient(name = "example-service")
public interface ExampleService {
@GetMapping("/hello")
String hello();
@GetMapping("/actuator/**")
@NonSentinel
String actuator();
}
总结
在 OpenFeign 与 Sentinel 集成时,需要仔细设置 feign.sentinel.enabled 参数。通过排除不需要拦截的请求或使用自定义 Feign 注解,可以解决 "GetMapping that is not used by contract Default" 错误,从而顺利启用 Sentinel 保护。
常见问题解答
-
Sentinel 如何拦截 Feign 客户端请求?
Sentinel 通过使用 Feign 的 RequestInterceptor 进行拦截,可以在请求发送到远程服务之前应用规则。 -
如何自定义 Sentinel 规则?
可以使用 Sentinel Dashboard 或通过编程方式配置自定义规则。Sentinel 支持多种规则类型,例如限流规则、熔断规则和降级规则。
-
Sentinel 集成是否会影响 Feign 客户端的性能?
Sentinel 集成会引入一些性能开销,但可以通过优化规则配置和使用异步执行来降低开销。
-
如何排除 Feign 客户端中的所有请求?
可以将 @SentinelResource(excludeAll = true) 注解应用于 Feign 接口,以排除所有请求。
-
为什么不建议排除所有请求?
排除所有请求会禁用 Sentinel 保护,从而降低服务的可用性和稳定性。