既然用到了feign,那么主要是针对服务消费方的降级处理。我们基于0.9.0.RELEASE版本的spring cloud alibaba nacos+feign实例添油加醋,把sentinel功能加上去:
1、pom引入sentinel依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
2、application配置哨兵控制台地址、开启feign+sentinel:
#哨兵
spring.cloud.sentinel.transport.dashboard=localhost:8080
#打开sentinel
feign.sentinel.enabled=true
3、启动类在@FeignClient注解中指定降级处理类和配置类:
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController; @EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class TransConsumerApplication { public static void main(String[] args) {
SpringApplication.run(TransConsumerApplication.class, args);
} @Slf4j
@RestController
static class TestController { @Autowired
private ApplicationApi applicationApi; @GetMapping("/sayhello")
public String sayhello() {
return "say: " + applicationApi.hello();
} @GetMapping("/sayhey")
public String sayhey() {
return "say: " + applicationApi.hey();
} } @FeignClient(name = "lxytrans-provider", fallback = TestFallback.class, configuration = FeignConfiguration.class)
interface ApplicationApi { @GetMapping("/hello")
String hello(); @GetMapping("/hey")
String hey(); } class TestFallback implements ApplicationApi { @Override
public String hello() {
return "hello feign fallback.";
} @Override
public String hey() {
return "hey feign fallback.";
}
} class FeignConfiguration {
@Bean
public TestFallback testFallback() {
return new TestFallback();
}
} }
跑起来后,调用一把这两个接口,可以发现哨兵控制台多了消费方:
此处无需配置流控、降级,我们的服务方维持原来的流控、降级处理(参见0.9.0.RELEASE版本的spring cloud alibaba sentinel限流、降级处理实例)。调用sayhey,服务方时延2秒,超时直接熔断:
再让消费方通过jmeter调用sayhello,前面3个正常返回,后面两个因为服务方限流而熔断: