Sentinel整合OpenFegin

之前学习了openFeign的使用,我是超链接

现在学习通过Sentinel来进行整合OpenFegin。

引入OpenFegin

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

java 复制代码
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

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

yml 复制代码
# 激活Sentinel对OpenFeign的支持
feign:
  sentinel:
    enabled: true

主启动类要添加@EnableFeignClients注解

java 复制代码
@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")就可以发起请求

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

        return "服务降级";
    }
}

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

java 复制代码
 @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;
    }

正常请求

正常抛异常,这个不好,应该统一处理一下

方法调用不通,终止服务提供者,则调用实现类的方法。

相关推荐
萧瑟余晖1 分钟前
Java深入解析篇三十六之分布式系统详解
java·开发语言·分布式
ZJU_统一阿萨姆37 分钟前
【推理优化进阶】调度器的数学内核:排队论、SLO 与在线决策
开发语言·人工智能·语言模型·系统架构·vllm
名明鸣冥1 小时前
k8s-agent架构思考(一)
python
SomeB1oody1 小时前
【RustyML入门】5.2. 分类指标
开发语言·后端·机器学习·rust·教程
ZJU_统一阿萨姆1 小时前
【推理优化进阶】图编译与运行时:动态形状、CUDA Graph 与内存规划
开发语言·人工智能·语言模型·架构·开源
@呱呱爱学习1 小时前
C++大成之路_ STL容器_ Vector
开发语言·c++
DoLovya1 小时前
从零实现 ESP8266 + MQTT 智能门禁:公网一键开门、舵机控制、在线监控完整方案
python·物联网·mqtt·嵌入式·esp8266·门禁系统
码匠许师傅2 小时前
【C++ 面试真题】19. 聊聊 C++ 的迭代器
开发语言·c++·面试
AI情绪识别开源2 小时前
检信ALLEMOTION VibrationAI 2.4.0 12维度情绪识别开源源代码
开发语言·python
Dovis(誓平步青云)2 小时前
DevEco Studio 6.1.1 Windows 安装实录:从下载校验到首次启动
android·开发语言·数据库·人工智能·windows·harmonyos