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

@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

原文地址:https://www.cnblogs.com/yufeng218/p/14199288.html