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

正常请求

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

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

相关推荐
周周记笔记15 分钟前
学习笔记:Python的起源
开发语言·python
懒大王952728 分钟前
uni-app + Vue3 + EZUIKit.js 播放视频流
开发语言·javascript·uni-app
_extraordinary_32 分钟前
Java 多线程进阶(四)-- 锁策略,CAS,synchronized的原理,JUC当中常见的类
java·开发语言
魂尾ac40 分钟前
Django + Vue3 前后端分离技术实现自动化测试平台从零到有系列 <第一章> 之 注册登录实现
后端·python·django·vue
JasmineX-11 小时前
数据结构——顺序表(c语言笔记)
c语言·开发语言·数据结构·笔记
Source.Liu1 小时前
【Pywinauto库】10.7 pywinauto.controls.uia_controls控件
windows·python·自动化
人工干智能1 小时前
建自己的Python项目仓库,使用工具:GitHub(远程仓库)、GitHub Desktop(版本控制工具)、VSCode(代码编辑器)
python·编辑器·github
java搬砖工-苤-初心不变1 小时前
OpenResty 配合 Lua 脚本的使用
开发语言·lua·openresty
IT灰猫1 小时前
C++轻量级配置管理器升级版
开发语言·c++·设计模式·配置管理·ini解析
StarPrayers.1 小时前
PySpark基础知识(python)
python·数据分析·spark