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;
    }

正常请求

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

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

相关推荐
军训猫猫头33 分钟前
1.如何对多个控件进行高效的绑定 C#例子 WPF例子
开发语言·算法·c#·.net
真的想上岸啊1 小时前
学习C++、QT---18(C++ 记事本项目的stylesheet)
开发语言·c++·学习
明天好,会的1 小时前
跨平台ZeroMQ:在Rust中使用zmq库的完整指南
开发语言·后端·rust
摸爬滚打李上进1 小时前
重生学AI第十六集:线性层nn.Linear
人工智能·pytorch·python·神经网络·机器学习
丁劲犇2 小时前
用 Turbo Vision 2 为 Qt 6 控制台应用创建 TUI 字符 MainFrame
开发语言·c++·qt·tui·字符界面·curse
旷世奇才李先生2 小时前
Next.js 安装使用教程
开发语言·javascript·ecmascript
凛铄linshuo2 小时前
爬虫简单实操2——以贴吧为例爬取“某吧”前10页的网页代码
爬虫·python·学习
牛客企业服务2 小时前
2025年AI面试推荐榜单,数字化招聘转型优选
人工智能·python·算法·面试·职场和发展·金融·求职招聘
述雾学java2 小时前
Spring Cloud Feign 整合 Sentinel 实现服务降级与熔断保护
java·spring cloud·sentinel
charlie1145141912 小时前
深入理解Qt的SetWindowsFlags函数
开发语言·c++·qt·原理分析