Ribbon、Feign整合Sentinel & 服務的熔斷降級


一、Ribbon整合Sentinel,服務的熔斷降級

1、引入依賴的jar包

<!-- 加入sentinel-->
<dependency>
	<groupId>com.alibaba.cloud</groupId>
	<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>

<!-- 加入actuator -->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

<!-- 加入ribbon -->
<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>

2、增加注解 @SentinelRestTemplate,指定其 blockHandler、blockHandlerClass、fallback、fallbackClass 四個屬性

 

  • blockHandler限流后處理的方法;
  • blockHandlerClass限流后處理的類;
  • fallback熔斷后處理的方法;
  • fallbackClass熔斷后處理的類;

 

限流:blockHandler、blockHandlerClass;熔斷降級fallback、fallbackClass

@Configuration
public class RibbonConfig {

    @Bean
    @LoadBalanced
    @SentinelRestTemplate( blockHandler = "flowLimitHandler", blockHandlerClass = GlobalExceptionHandler.class, fallback = "reduceHandler", fallbackClass = GlobalExceptionHandler.class
    )
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

異常處理類:

public class GlobalExceptionHandler {

    /**
     * 限流的處理方法
     */
    public static SentinelClientHttpResponse flowLimitHandler(HttpRequest request, byte[] body,
                                                              ClientHttpRequestExecution execution, BlockException ex) {
        Person person = new Person(-1, "被限流了!", 0);
        return new SentinelClientHttpResponse(JSONObject.toJSONString(person));
    }

    /**
     * 服務降級
     * @return
     */
    public static SentinelClientHttpResponse reduceHandler(HttpRequest request, byte[] body,
                                                              ClientHttpRequestExecution execution, BlockException ex) {
        Person person = new Person(-1, "服務降級!", 0);
        return new SentinelClientHttpResponse(JSONObject.toJSONString(person));
    }
}

3、配置文件中增加開啟 @SentinelRestTemplate 的配置

spring:
  cloud:
    nacos:
      discovery:
        server-addr: 192.168.172.20:8848
    sentinel:
      transport:
        dashboard: localhost:9999
  application:
    name: sentinel-ribbon-order

server:
  port: 8010

management:
  endpoints:
    web:
      exposure:
        include: '*'

#是否開啟@SentinelRestTemplate注解
resttemplate:
  sentinel:
    enabled: true

4、controller類

@RestController
public class Controller {

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/getPersonById")
    public Person getPersonById() {
        ResponseEntity<Person> responseEntity = restTemplate.getForEntity("http://product-center/v1/person/" + 10, Person.class);
        return responseEntity.getBody();
    }
}

5、結果驗證

(1)流控規則的配置

 

 在瀏覽器快速訪問:http://localhost:8010/getPersonById,結果如下:

 

 (2)降級規則的驗證

將上面添加的限流規則刪除,增加降級規則。

 

 在瀏覽器快速訪問:http://localhost:8010/getPersonById,結果如下:

 

 

 二、Feign整合Sentinel,服務的熔斷降級

 1、增加依賴的 jar包

<!-- 加入sentinel-->
<dependency>
	<groupId>com.alibaba.cloud</groupId>
	<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>

<!-- 加入actuator -->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

<!-- nacos client  -->
<dependency>
	<groupId>com.alibaba.cloud</groupId>
	<artifactId>spring-cloud-alibaba-nacos-discovery</artifactId>
</dependency>

<!-- feign -->
<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

2、在Feign的聲明式接口上添加fallback屬性 或者 fallbackFactory屬性

注意:服務啟動類需要增加 @EnableFeignClinets 注解;

本文只使用 fallbackFactory 屬性。

@FeignClient(name = "product-center", fallbackFactory = ProductCenterFeignApi.class)
public interface ProductCenter {

    /**
     * 聲明式接口,遠程調用http://product-center/v1/person/{id}
     */
    @GetMapping("/v1/person/{id}")
    public Person getPerson(@PathVariable("id") String id);
}

ProductCenterFeignApi 的異常處理需要實現
FallbackFactory 接口,如下
@Component
@Slf4j
public class ProductCenterFeignApi implements FallbackFactory<ProductCenter> {
    @Override
    public ProductCenter create(Throwable throwable) {
        return new ProductCenter() {
            @Override
            public Person getPerson(String id) {
                log.error("原因: ", throwable);
                Person person = new Person();
                if(throwable instanceof FlowException) {
                    person.setId(-1);
                    person.setName("接口被流控了!");
                }
                else if(throwable instanceof DegradeException) {
                    person.setId(-2);
                    person.setName("服務被降級了!");
                }
                else {
                    person.setId(-999);
                    person.setName("其他異常了!");
                }
                return person;
            }
        };
    }
}

controller 類

@RestController
public class Controller {

    @Autowired
    private ProductCenter productCenter;

    @GetMapping("/getPersonById")
    public Person getPersonById() {
        return productCenter.getPerson("666");
    }
}

啟動類增加 @EnableFeignClients 注解

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class SenFeignApp {

    public static void main(String[] args) {
        SpringApplication.run(SenFeignApp.class, args);
    }
}

3、配置文件中增加  feign.sentinel.enabled=true 

spring:
  cloud:
    nacos:
      discovery:
        server-addr: 192.168.172.20:8848
    sentinel:
      transport:
        dashboard: localhost:9999
  application:
    name: sentinel-feign-order

server:
  port: 8011

management:
  endpoints:
    web:
      exposure:
        include: '*'

feign:
  client:
    config:
      product-center:
        loggerLevel: FULL
  httpclient:
    enabled: true
    max-connections: 200  #最大連接數
    max-connections-per-route: 50   #為每個url請求設置最大連接數
  sentinel: enabled: true 

4、結果驗證

(1)流控規則的驗證

瀏覽器快速訪問:http://localhost:8011/getPersonById

(2)降級規則的驗證

刪除上面配置的流控規則,配置降級規則;

瀏覽器快速訪問:http://localhost:8011/getPersonById

 


免責聲明!

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



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