服务提供方
创建一个sentinel-feign-provider服务并注册到Nacos
@SpringBootApplication
@EnableDiscoveryClient
@RestController
public class FeignProviderApplication {
public static void main(String[] args) {
SpringApplication.run(FeignProviderApplication.class, args);
}
@GetMapping("hello")
public String hello() {
return "hello";
}
}
服务消费方
1. 引入依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- feigns -->
<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>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
</dependencies>
2. application.yml
server:
port: 8060
spring:
application:
name: sentinel-feign-consumer
cloud:
nacos:
discovery:
server-addr: localhost:8848
feign:
sentinel:
# 开启feign sentinel熔断降级支持
enabled: true
3. Feign
使用方法和hystrix熔断差不多,需要指定fallback属性,fallback属性的类必须实现feign接口
- 接口
@FeignClient(value = "sentinel-feign-provider", fallback = TestFeignImpl.class)
public interface TestFeign {
@GetMapping("hello")
String hello();
}
- 实现类
@Component
public class TestFeignImpl implements TestFeign{
@Override
public String hello() {
return "feign fallback";
}
}
4. controller
@RestController
public class TestController {
@Autowired
private TestFeign testFeign;
@Autowired
private RestTemplate restTemplate;
@GetMapping("hello-feign")
public String helloFeign(){
return testFeign.hello();
}
// fallback属性指定降级的方法,默认为当前类的方法
@SentinelResource(value = "hello-rest", fallback = "helloRestFallback")
@GetMapping("hello-rest")
public String helloRest(){
return restTemplate.getForObject("http://sentinel-feign-provider/hello", String.class);
}
public String helloRestFallback(){
return "rest fallback";
}
}
5. 启动类
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients //开启feign
public class FeignConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(FeignConsumerApplication.class, args);
}
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
测试
启动服务提供方和消费方
curl http://localhost:8060/hello-rest
hello
curl http://localhost:8060/hello-feign
hello
关闭服务提供方
再次curl http://localhost:8060/hello-rest
rest fallback
再次curl http://localhost:8060/hello-feign
feign fallback
如果feign接口指定了fallback,并且@SentinelResource注解中也指定了fallback,优先使用feign接口中指定的