1.开启支持
# 打开 Sentinel 对 Feign 的支持
feign:
sentinel:
enabled: true2.pom添加
<!-- Sentinel 适配了 Feign, 可以实现服务间调用的保护 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>3.添加feign支持
/**
* <h1>Sentinel 集成到 SpringCloud 工程中</h1>
* */
@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class SentinelClientApplication {
public static void main(String[] args) {
SpringApplication.run(SentinelClientApplication.class, args);
}
}4.feign调用
/**
* <h1>通过 Sentinel 对 OpenFeign 实现熔断降级</h1>
* */
@FeignClient(
value = "e-commerce-imooc",
fallback = SentinelFeignClientFallback.class
)
public interface SentinelFeignClient {
@RequestMapping(value = "qinyi", method = RequestMethod.GET)
CommonResponse<String> getResultByFeign(@RequestParam Integer code);
}
/**
* <h1>Sentinel 对 OpenFeign 接口的降级策略</h1>
* */
@Slf4j
@Component
public class SentinelFeignClientFallback implements SentinelFeignClient {
@Override
public CommonResponse<String> getResultByFeign(Integer code) {
log.error("request supply for test has some error: [{}]", code);
return new CommonResponse<>(
-1,
"sentinel feign fallback",
"input code: "+ code
);
}
}
/**
* <h1>OpenFeign 集成 Sentinel 实现熔断降级</h1>
* */
@Slf4j
@RestController
@RequestMapping("/sentinel-feign")
public class SentinelFeignController {
private final SentinelFeignClient sentinelFeignClient;
public SentinelFeignController(SentinelFeignClient sentinelFeignClient) {
this.sentinelFeignClient = sentinelFeignClient;
}
/**
* <h2>通过 Feign 接口去获取结果</h2>
* */
@GetMapping("/result-by-feign")
public CommonResponse<String> getResultByFeign(@RequestParam Integer code) {
log.info("coming in get result by feign: [{}]", code);
return sentinelFeignClient.getResultByFeign(code);
}
}