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


  既然用到了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個正常返回,后面兩個因為服務方限流而熔斷:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM