Ribbon和OpenFeign整合Sentinel

目錄

Ribbon整合Sentinel

OpenFeign整合我們的Sentinel


Ribbon整合Sentinel

在我們的RestTemplate組件上添加 @SentinelRestTemplate註解

並且我們可以通過在@SentinelRestTemplate 同樣的可以指定我們的blockHandlerClass,fallbackClass blockHandler,fallback 這四個屬性

@Configuration
public class WebConfig {

    @Bean
    @LoadBalanced
    @SentinelRestTemplate(
            blockHandler = "handleException",blockHandlerClass = GlobalExceptionHandler.class,
            fallback = "fallback",fallbackClass = GlobalExceptionHandler.class

    )
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}
@Slf4j
public class GlobalExceptionHandler {


    /**
     * 限流後處理方法
     */
    public static SentinelClientHttpResponse handleException(HttpRequest request,
                                                             byte[] body, ClientHttpRequestExecution execution, BlockException ex)  {

        ProductInfo productInfo = new ProductInfo();
        productInfo.setProductName("被限制流量拉");
        productInfo.setProductNo("-1");
        ObjectMapper objectMapper = new ObjectMapper();

        try {
            return new SentinelClientHttpResponse(objectMapper.writeValueAsString(productInfo));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 熔斷後處理的方法
     */
    public static SentinelClientHttpResponse fallback(HttpRequest request,
                                                      byte[] body, ClientHttpRequestExecution execution, BlockException ex) {
        ProductInfo productInfo = new ProductInfo();
        productInfo.setProductName("被降級拉");
        productInfo.setProductNo("-1");
        ObjectMapper objectMapper = new ObjectMapper();

        try {
            return new SentinelClientHttpResponse(objectMapper.writeValueAsString(productInfo));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }
}

 添加配置

#是否開啓@SentinelRestTemplate註解
resttemplate:
  sentinel:
    enabled: true

OpenFeign整合我們的Sentinel

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

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

/*
@FeignClient(name = "product-center",fallback = ProductCenterFeignApiWithSentinelFallback.class)
*/
/*
@FeignClient(name = "product-center",fallbackFactory = ProductCenterFeignApiWithSentielFallbackFactory.class)
*/
public interface ProductCenterFeignApiWithSentinel {

    /**
     * 聲明式接口,遠程調用http://product-center/selectProductInfoById/{productNo}
     * @param productNo
     * @return
     */
    @RequestMapping("/selectProductInfoById/{productNo}")
    ProductInfo selectProductInfoById(@PathVariable("productNo") String productNo);

}

feign的限流降級接口(通過fallback沒有辦法獲取到異常的)

@Component
public class ProductCenterFeignApiWithSentinelFallback implements ProductCenterFeignApiWithSentinel {
    @Override
    public ProductInfo selectProductInfoById(String productNo) {
        ProductInfo productInfo = new ProductInfo();
        productInfo.setProductName("默認商品");
        return productInfo;
    }
}
@Component
@Slf4j
public class ProductCenterFeignApiWithSentielFallbackFactory implements FallbackFactory<ProductCenterFeignApiWithSentinel> {
    @Override
    public ProductCenterFeignApiWithSentinel create(Throwable throwable) {
        return new ProductCenterFeignApiWithSentinel(){

            @Override
            public ProductInfo selectProductInfoById(String productNo) {
                ProductInfo productInfo = new ProductInfo();
                if (throwable instanceof FlowException) {
                    log.error("流控了....{}",throwable.getMessage());
                    productInfo.setProductName("我是被流控的默認商品");
                }else {
                    log.error("降級了....{}",throwable.getMessage());
                    productInfo.setProductName("我是被降級的默認商品");
                }

                return productInfo;
            }
        };
    }
}

個人博客:https://www.upheart.top/ 

個人公衆號,日常分享一個知識點,每天進步一點點,面試不慌

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章