0.9.0.RELEASE版本的spring cloud alibaba sentinel+feign降級處理實例

  既然用到了feign,那麼主要是針對服務消費方的降級處理。咱們基於0.9.0.RELEASE版本的spring cloud alibaba nacos+feign實例添油加醋,把sentinel功能加上去:html

  一、pom引入sentinel依賴:web

<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
        </dependency>

  二、application配置哨兵控制檯地址、開啓feign+sentinel:spring

#哨兵 spring.cloud.sentinel.transport.dashboard=localhost:8080 #打開sentinel feign.sentinel.enabled=true

  三、啓動類在@FeignClient註解中指定降級處理類和配置類:app

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(); } } }

  跑起來後,調用一把這兩個接口,能夠發現哨兵控制檯多了消費方:ide

  此處無需配置流控、降級,咱們的服務方維持原來的流控、降級處理(參見0.9.0.RELEASE版本的spring cloud alibaba sentinel限流、降級處理實例)。調用sayhey,服務方時延2秒,超時直接熔斷:spa

 

  再讓消費方經過jmeter調用sayhello,前面3個正常返回,後面兩個由於服務方限流而熔斷:code

相關文章
相關標籤/搜索