400 028 6601

Sentinel中RestTemplate与Feign分析

这篇文章主要讲解了“Sentinel中RestTemplate与Feign分析”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Sentinel中RestTemplate与Feign分析”吧!

为洞口等地区用户提供了全套网页设计制作服务,及洞口网站建设行业解决方案。主营业务为网站设计、成都做网站、洞口网站设计,以传统方式定制建设网站,并提供域名空间备案等一条龙服务,秉承以专业、用心的态度为用户提供真诚的服务。我们深信只要达到每一位用户的要求,就会得到认可,从而选择与我们长期合作。这样,我们也可以走得更远!

Sentinel API

Github : WIKI

Sentinel Annotation

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

RestTemplate 整合Sentinel

使用 @SentinelRestTemplate.

resttemplate.sentinel.enabled可以开关是否启用该注解。(开发阶段很有意义。)

源码: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来开启

Sentinel中RestTemplate与Feign分析

  1. 编写fallback 类,实现feign client

    @Component
    public class UserCenterFeignClientFallback implements IUserCenterFeignClient {
        @Override
        public UserDTO findById(Long userId) {
            UserDTO userDTO = new UserDTO();
            userDTO.setWxNickname("默认用户");
            return userDTO;
        }
    }
    
    @Slf4j
    @Component
    public class UserCenterFeignClientFallbackFactory implements FallbackFactory {
    
        @Override
        public IUserCenterFeignClient create(Throwable cause) {
            return new IUserCenterFeignClient() {
                @Override
                public UserDTO findById(Long userId) {
                    log.warn("远程调用被限流/降级,{}", cause);
                    UserDTO userDTO = new UserDTO();
                    userDTO.setWxNickname("默认用户");
                    return userDTO;
                }
            };
        }
    }

  2. 应用fallback class

    /**
     * IUserCenterFeignClient for 定义 user-center feign client
     * fallbackFactory 可以拿到异常信息
     * fallback 无法拿到异常信息
     *
     * @author Isaac.Zhang | 若初
     * @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. 启动应用,设置流控规则,结果展示如下

    {
        id: 1,
        ...
        wxNickName: "默认用户"
    }

感谢各位的阅读,以上就是“Sentinel中RestTemplate与Feign分析”的内容了,经过本文的学习后,相信大家对Sentinel中RestTemplate与Feign分析这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是创新互联,小编将为大家推送更多相关知识点的文章,欢迎关注!


网站栏目:Sentinel中RestTemplate与Feign分析
URL分享:http://mbwzsj.com/article/gcddjc.html

其他资讯