转载

当 Spring Cloud Alibaba Sentinel 碰上 Spring Cloud Sleuth 会擦出怎样的火花

前言

今年主要会做一个比较完整的微服务项目开源出来。目前已经开始了,刚兴趣的先 Star 一个吧。

项目: https://github.com/yinjihuan/kitty-cloud [1]

基础框架: https://github.com/yinjihuan/kitty [2]

在做的过程中遇到一个问题那就是标题所说的两个框架碰撞了火花。都是 S 开头的谁都不服谁。

问题描述

既然使用了 Sentinel 来限流,那么干脆熔断也直接用 Sentinel 好了,所以就没使用 Hystrix 了。

Sentinel 对 Feign 做了适配,使用的时候只需要引入 spring-cloud-starter-alibaba-sentinel,如下:

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>

然后在配置文件打开 Sentinel 对 Feign 的支持:feign.sentinel.enabled=true 就可以了。

一开始都很正常,平平淡淡的小日子过得也挺舒坦。

突然有一天,来了一位同姓但不同名的哥们,它叫 Sleuth。

Sleuth 文档:

https://cloud.spring.io/spring-cloud-static/Greenwich.SR5/single/spring-cloud.html#/_spring_cloud_sleuth [3]

Spring Cloud Sleuth 为 Spring Cloud 实现了分布式追踪解决方案。可以配合 Zipkin 或者 Jaeger 使用。

自从 Sleuth 来了之后,Sentinel Feign 的日子就不好过了,莫名其妙熔断回退失效了。

问题排查

Sentinel 对 Feign 的适配入口在 SentinelFeignAutoConfiguration 中。

当 Spring Cloud Alibaba Sentinel 碰上 Spring Cloud Sleuth 会擦出怎样的火花

主要是构建了 Feign 的 Builder 类,只要这个类被自动配置了,那么 Sentinel 对 Feign 的支持也会生效。突然不生效了,那么肯定是这里有问题。

于是开启 debug 模式,发现启动的时候这里没有执行。feign.sentinel.enabled 已经配置了,剩下就只有@ConditionalOnMissingBean 的问题了。

@ConditionalOnMissingBean 的作用是如果容器中已经有 Builder 那么这里就不会执行。

接下来就要看 Sleuth 的代码了,之所以能马上知道是 Sleuth 影响了,是因为一开始都是正常的,加了 Sleuth 后就出问题了。

在 Sleuth 中 Feign 相关的配置是在 TraceFeignClientAutoConfiguration 中。

当 Spring Cloud Alibaba Sentinel 碰上 Spring Cloud Sleuth 会擦出怎样的火花

可以看到,Sleuth 中对 Feign Builder 也有配置,一种是如果开启了 Hystrix 就用 SleuthHystrixFeignBuilder,如果没有开启就用 SleuthFeignBuilder。

在这里打个断点,启动时直接就进来了,这边执行完后 Builder 对象就有了,所以 Sentinel 中的自然就不会执行了。

解决方案

发生冲突的根本原因在于两个框架都要对 Feign 进行扩展,Sentinel 扩展是为了再调用的时候可以实现限流熔断等功能。Sleuth 扩展是为了使用 Feign 调用接口的时候可以传递链路跟踪的信息。

要想解决这个问题,要么妥协只用一个框架,这样是最简单的。

要么看看 Sleuth 后面会不会支持 Sentinel,目前可以看到已经支持了 Hystrix。

最后一种就是自己改源码,将 Sentinel 融入到 Sleuth 中。

SleuthFeignBuilder 中只是对 Client 做了包装。

当 Spring Cloud Alibaba Sentinel 碰上 Spring Cloud Sleuth 会擦出怎样的火花

SentinelFeign 中只是对 Builder 做了增强。

当 Spring Cloud Alibaba Sentinel 碰上 Spring Cloud Sleuth 会擦出怎样的火花

所以我们只要把两者结合起来就可以了。

当 Spring Cloud Alibaba Sentinel 碰上 Spring Cloud Sleuth 会擦出怎样的火花

PS:没 Star 的现在接着 Star 吧!

项目: https://github.com/yinjihuan/kitty-cloud [1]

基础框架: https://github.com/yinjihuan/kitty [2]

参考资料

[1]

kitty-cloud: https://github.com/yinjihuan/kitty-cloud

[2]

kitty: https://github.com/yinjihuan/kitty

[3]

spring_cloud_sleuth: https://cloud.spring.io/spring-cloud-static/Greenwich.SR5/single/spring-cloud.html#_spring_cloud_sleuth

关于作者 :尹吉欢,简单的技术爱好者,《Spring Cloud 微服务-全栈技术与案例解析》, 《Spring Cloud 微服务 入门 实战与进阶》作者, 公众号  猿天地  发起人。个人微信  jihuan900 , 欢迎勾搭。

相关推荐

  • 双剑合璧的开源项目Kitty-Cloud

  • Kitty-Cloud环境准备

  • Kitty-Cloud服务搭建过程剖析

后台回复 学习资料   领取学习视频

当 Spring Cloud Alibaba Sentinel 碰上 Spring Cloud Sleuth 会擦出怎样的火花

如有收获,点个在看,诚挚感谢

原文  https://mp.weixin.qq.com/s/-onj8ufg8xN9tA3gpCePrg
正文到此结束
Loading...