OpenFeign 整合 Sentinel 实现服务降级
引入依赖
XML
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- nacos服务发现 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- openfeign 服务调用 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!--sentinel 服务保护 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
</dependencies>
打开配置
java
spring:
application:
name: order-feign-sentinel
cloud:
nacos:
server-addr: 127.0.0.1:8847
discovery:
username: nacos
password: nacos
# springboot 默认日志级别是info 因此 feign的debug日志级别就不会输出
logging:
level:
com.learning.springcloud.order.feign: debug
# openfeign 整合 sentinel
feign:
sentinel:
enabled: true
编写接口
- stock-nacos 接口类
java
@RestController
@RequestMapping("/stock")
public class StockController {
@Value("${server.port}")
String serverPort;
@RequestMapping("/reduct2")
public Object reductStock2() {
int a = 1 / 0; // 故意制造异常
System.out.println(serverPort + ":扣减库存2成功了");
return "reduct2 stock success. stock service port:" + serverPort;
}
}
- OpenFeigin 接口类
java
@FeignClient(name = "stock-nacos", path = "/stock", configuration = FeignConfig.class)
public interface StockFeignService {
@RequestMapping("/reduct2")
String reductStock2();
}
- 服务降级处理类 实现OpenFeigin 接口类 并 托管Spring容器
java
@Component
public class StockFeignServiceForback implements StockFeignService {
@Override
public String reductStock2() {
return "降级了!!!";
}
}
- OpenFeign 接口类 增加 fallback 属性, 值为服务降级处理类
java
// fallback = StockFeignServiceForback.class
@FeignClient(name = "stock-nacos", path = "/stock", configuration = FeignConfig.class,
fallback = StockFeignServiceForback.class)
public interface StockFeignService {
@RequestMapping("/reduct2")
String reductStock2();
}