出自图灵学院4
代码地址
详细步骤
Sentinel 适配了 Feign 组件。如果想使用,除了引入 spring-cloud-starter-alibaba-sentinel 的依赖外还需要 2 个步骤:
配置文件打开 Sentinel 对 Feign 的支持:feign.sentinel.enabled=true
feign:
sentinel:
enabled: true #开启sentinel对feign的支持 默认false
加入 spring-cloud-starter-openfeign 依赖使 Sentinel starter 中的自动化配置类生效:
<!-- 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>
在Feign的声明式接口上添加fallback属性
@FeignClient(value = "mall-order",path = "/order",fallback = FallbackOrderFeignService .class)
public interface OrderFeignService {
@RequestMapping("/findOrderByUserId/{userId}")
public R findOrderByUserId(@PathVariable("userId") Integer userId);
}
@Component //必须交给spring 管理
public class FallbackOrderFeignService implements OrderFeignService {
@Override
public R findOrderByUserId(Integer userId) {
return R.error(-1,"=======服务降级了========");
}
}
添加fallbackFactory属性
@Component
public class FallbackOrderFeignServiceFactory implements FallbackFactory<OrderFeignService> {
@Override
public OrderFeignService create(Throwable throwable) {
return new OrderFeignService() {
@Override
public R findOrderByUserId(Integer userId) {
return R.error(-1,"=======服务降级了========");
}
};
}
}
UserController
@Autowired
OrderFeignService orderFeignService;
@RequestMapping(value = "/findOrderByUserId/{id}")
public R findOrderByUserId(@PathVariable("id") Integer id) {
//feign调用
R result = orderFeignService.findOrderByUserId(id);
return result;
}
注意:主启动类上加上@EnableFeignClients注解,开启Feign支持
@SpringBootApplication
@EnableFeignClients
@EnableDiscoveryClient
public class MallUserSentinelRibbonDemoApplication {
public static void main(String[] args) {
SpringApplication.run(MallUserSentinelRibbonDemoApplication.class, args);
}
}
测试
关闭mall-order服务,访问http://localhost:8801/user/findOrderByUserId/4自动降级了