Sentinel整合OpenFegin

之前学习了openFeign的使用,我是超链接
现在学习通过Sentinel来进行整合OpenFegin。

引入OpenFegin

我们需要在当前的8084项目中引入对应的依赖

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

激活Sentinel对OpenFeign的支持,所以配置yml

# 激活Sentinel对OpenFeign的支持
feign:
  sentinel:
    enabled: true

主启动类要添加@EnableFeignClients注解

@EnableDiscoveryClient
@EnableFeignClients
@SpringBootApplication
public class OrderApplication {

    @Bean
    @LoadBalanced
    @SentinelRestTemplate(blockHandler = "handleException",
            blockHandlerClass= GlobalException.class
            ,fallback = "fallback",
            fallbackClass = GlobalException.class)
    public RestTemplate getRestTemplate() {
        return new RestTemplate();
    }
    public static void main(String[] args) {
        SpringApplication.run(OrderApplication.class);
    }
}

OpenFegin接口编写

这里我们的接口写法和之前保持一致,但是要注意,我们这里要多增加一个FeignClient的属性:

  • allback: 定义容错的处理类,当调用远程接口失败或超时时,会调用对应接口的容错逻辑,fallback指定的类必须实现@FeignClient标记的接口

  • 正常@FeignClient(value = “msb-user”)就可以发起请求

//当没有成功调用/user/{userId}接口时会走fallback属性标注的类型的处理方法 实现类方法
@Service
@FeignClient(value = "msb-user",fallback = UserFeignServiceImpl.class)
public interface UserFeignService {
    @GetMapping("/user/{userId}")
    String getUserName(@PathVariable Integer userId);
}
  • 实现类必须添加@Component注解,否则无法注入到容器中
@Component
public class UserFeignServiceImpl implements UserFeignService {
    @Override
    public String getUserName(Integer userId) {

        return "服务降级";
    }
}

这里完成后我们来编写控制器

 @GetMapping("/order/user/{userId}")
    public String createOrder(@PathVariable Integer userId){
        if(userId > 3){
            throw new RuntimeException("没有该id");
        }
        String userName = userFeignService.getUserName(userId);
        System.out.println(userName);
        return userName;
    }

正常请求
在这里插入图片描述
正常抛异常,这个不好,应该统一处理一下
在这里插入图片描述
方法调用不通,终止服务提供者,则调用实现类的方法。
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值