OpenFeign集成Sentinel
一:引入依赖
<!--sentinel依赖-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<!--引入OpenFeign依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
二:配置文件application开启OpenFeignSentinel熔断
server:
port: 10002 #order服务端口号
spring:
application:
name: order-server #应用名称
cloud:
nacos:
discovery:
server-addr: localhost:8848 #指定nacos注册中心地址
feign:
sentinel:
enabled: true #开启熔断功能
三:熔断工厂
package cn.ybl.feign;
import cn.ybl.domain.User;
import feign.hystrix.FallbackFactory;
/**
* UserFeign的熔断工厂类
*/
public class UserFeignClientFallbackFactory implements FallbackFactory<UserFeign> {
/**
* 熔断托底方法
* @param throwable
*/
@Override
public UserFeign create(Throwable throwable) {
return new UserFeign() {
@Override
public User getUser(Long id) {
return new User(-1L, "触发熔断", "服务不可用,请稍后重试!");
}
};
}
}
四:Feign接口通过feign客户端注解指向熔断工厂
package cn.ybl.feign;
import cn.ybl.domain.User;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@FeignClient(value = "user-server",fallbackFactory = UserFeignClientFallbackFactory.class)
@RequestMapping("/user")
public interface UserFeign {
@GetMapping("/getById/{id}")
User getUser(@PathVariable("id") Long id);
}
如此便完成了OpenFeign整合Sentinel,当调用此feign接口出现异常时则触发熔断,返回托底数据
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现