溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

Sentinel中RestTemplate與Feign分析

發(fā)布時(shí)間:2021-11-15 17:13:42 來(lái)源:億速云 閱讀:198 作者:iii 欄目:大數(shù)據(jù)

這篇文章主要講解了“Sentinel中RestTemplate與Feign分析”,文中的講解內(nèi)容簡(jiǎn)單清晰,易于學(xué)習(xí)與理解,下面請(qǐng)大家跟著小編的思路慢慢深入,一起來(lái)研究和學(xué)習(xí)“Sentinel中RestTemplate與Feign分析”吧!

Sentinel API

Github : WIKI

  • Sphu (指明要保護(hù)的資源名稱(chēng))

  • Tracer (指明調(diào)用來(lái)源,異常統(tǒng)計(jì)接口)

  • ContextUtil(標(biāo)示進(jìn)入調(diào)用鏈入口)

  • 流控規(guī)則(針對(duì)來(lái)源屬性)

    @GetMapping("/test-sentinel-api")
        public String testSentinelAPI(@RequestParam(required = false) String a) {
            String resourceName = "test-sentinel-api";
    
            ContextUtil.enter(resourceName, "user-center-service");
            // 定義一個(gè)sentinel 保護(hù)的資源,名稱(chēng)是test-sentinel-api
            Entry entry = null;
            try {
    
                entry = SphU.entry(resourceName);
                // ...被保護(hù)的業(yè)務(wù)邏輯處理
                if (StringUtils.isEmpty(a)) {
                    // Sentinel 默認(rèn)只會(huì)統(tǒng)計(jì)BlockException & BlockException的子類(lèi),如果想統(tǒng)計(jì)其他異常信息,添加Tracer
                    throw new IllegalArgumentException("A is not empty.");
                }
                return a;
                // block Exception: 如果被保護(hù)的資源被限流或者降級(jí)了,就會(huì)拋異常出去
            } catch (BlockException e) {
                log.error("我被限流啦!!{}", e);
                return "我被限流啦??!";
            } catch (IllegalArgumentException argEx) {
                // 統(tǒng)計(jì)當(dāng)前異常發(fā)生次數(shù) / 占比
                Tracer.trace(argEx);
                return "非法參數(shù)信息";
            } finally {
                if (entry != null) {
                    entry.exit();
                }
                ContextUtil.exit();
            }
        }


  • 降級(jí)規(guī)則

    @GetMapping("/test-sentinel-api")
        public String testSentinelAPI(@RequestParam(required = false) String a) {
    
            // 定義一個(gè)sentinel 保護(hù)的資源,名稱(chēng)是test-sentinel-api
            Entry entry = null;
            try {
                entry = SphU.entry("test-sentinel-api");
                // ...被保護(hù)的業(yè)務(wù)邏輯處理
                if (StringUtils.isEmpty(a)) {
                    // Sentinel 默認(rèn)只會(huì)統(tǒng)計(jì)BlockException & BlockException的子類(lèi),如果想統(tǒng)計(jì)其他異常信息,添加Tracer
                    throw new IllegalArgumentException("A is not empty.");
                }
                return a;
                // block Exception: 如果被保護(hù)的資源被限流或者降級(jí)了,就會(huì)拋異常出去
            } catch (BlockException e) {
                log.error("我被限流啦?。}", e);
                return "我被限流啦?。?quot;;
            } catch (IllegalArgumentException argEx) {
                // 統(tǒng)計(jì)當(dāng)前異常發(fā)生次數(shù) / 占比
                Tracer.trace(argEx);
                return "非法參數(shù)信息";
            } finally {
                if (entry != null) {
                    entry.exit();
                }
            }
    
        }


Sentinel Annotation

源碼:com.alibaba.csp.sentinel.annotation.aspectj.SentinelResourceAspect & com.alibaba.csp.sentinel.annotation.aspectj.AbstractSentinelAspectSupport

  • SentinelResource 使用該注解重構(gòu)上述方法

        @GetMapping("/test-sentinel-resource")
        @SentinelResource(value = "test-sentinel-api", blockHandler = "blockException", fallback = "fallback")
        public String testSentinelResource(@RequestParam(required = false) String a) {
            // ...被保護(hù)的業(yè)務(wù)邏輯處理
            if (StringUtils.isEmpty(a)) {
                // Sentinel 默認(rèn)只會(huì)統(tǒng)計(jì)BlockException & BlockException的子類(lèi),如果想統(tǒng)計(jì)其他異常信息,添加Tracer
                throw new IllegalArgumentException("A is not empty.");
            }
            return a;
        }
    
        /**
         * testSentinelResource BlockException method
         */
        public String blockException(String a, BlockException e) {
            log.error("限流了,{}", e);
            return "blockHandler 對(duì)應(yīng)《限流規(guī)則》";
        }
    
        /**
         * testSentinelResource fallback method
         * {@link SentinelResource} #fallback 在< 1.6的版本中,不能補(bǔ)貨BlockException
         */
        public String fallback(String a) {
            return "fallback 對(duì)應(yīng)《降級(jí)規(guī)則》";
        }


RestTemplate 整合Sentinel

使用 @SentinelRestTemplate.

resttemplate.sentinel.enabled可以開(kāi)關(guān)是否啟用該注解。(開(kāi)發(fā)階段很有意義。)

源碼:com.springframework.cloud.alibaba.sentinel.custom.SentinelBeanPostProcessor

@Bean
@LoadBalanced
@SentinelRestTemplate
public RestTemplate restTemplate() {
    return new RestTemplate();
}

@Autowired
private RestTemplate restTemplate;
...
Feign整合 Sentinel

配置文件中添加 feign.sentinel.enabled: true來(lái)開(kāi)啟

Sentinel中RestTemplate與Feign分析

  1. 編寫(xiě)fallback 類(lèi),實(shí)現(xiàn)feign client

    @Component
    public class UserCenterFeignClientFallback implements IUserCenterFeignClient {
        @Override
        public UserDTO findById(Long userId) {
            UserDTO userDTO = new UserDTO();
            userDTO.setWxNickname("默認(rèn)用戶(hù)");
            return userDTO;
        }
    }
    
    @Slf4j
    @Component
    public class UserCenterFeignClientFallbackFactory implements FallbackFactory<IUserCenterFeignClient> {
    
        @Override
        public IUserCenterFeignClient create(Throwable cause) {
            return new IUserCenterFeignClient() {
                @Override
                public UserDTO findById(Long userId) {
                    log.warn("遠(yuǎn)程調(diào)用被限流/降級(jí),{}", cause);
                    UserDTO userDTO = new UserDTO();
                    userDTO.setWxNickname("默認(rèn)用戶(hù)");
                    return userDTO;
                }
            };
        }
    }


  2. 應(yīng)用fallback class

    /**
     * IUserCenterFeignClient for 定義 user-center feign client
     * fallbackFactory 可以拿到異常信息
     * fallback 無(wú)法拿到異常信息
     *
     * @author <a href="mailto:magicianisaac@gmail.com">Isaac.Zhang | 若初</a>
     * @since 2019/7/15
     */
    @FeignClient(name = "user-center",
            // fallback = UserCenterFeignClientFallback.class,
            fallbackFactory = UserCenterFeignClientFallbackFactory.class
    )
    public interface IUserCenterFeignClient {
        @GetMapping(path = "/users/{userId}")
        public UserDTO findById(@PathVariable Long userId);
    }


  3. 啟動(dòng)應(yīng)用,設(shè)置流控規(guī)則,結(jié)果展示如下

    {
        id: 1,
        ...
        wxNickName: "默認(rèn)用戶(hù)"
    }


感謝各位的閱讀,以上就是“Sentinel中RestTemplate與Feign分析”的內(nèi)容了,經(jīng)過(guò)本文的學(xué)習(xí)后,相信大家對(duì)Sentinel中RestTemplate與Feign分析這一問(wèn)題有了更深刻的體會(huì),具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是億速云,小編將為大家推送更多相關(guān)知識(shí)點(diǎn)的文章,歡迎關(guān)注!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI