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

正常请求

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

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

相关推荐
摸鱼仙人~5 分钟前
从 Gunicorn 到 FastAPI:Python Web 生产环境架构演进与实战指南
python·fastapi·gunicorn
難釋懷5 分钟前
解决状态登录刷新问题
java·开发语言·javascript
ytttr8735 分钟前
基于MATLAB的三维装箱程序实现(遗传算法+模拟退火优化)
开发语言·matlab
毕设源码-朱学姐23 分钟前
【开题答辩全过程】以 基于Django框架中山社区社会补助系统为例,包含答辩的问题和答案
后端·python·django
耶耶耶耶耶~23 分钟前
Modern C++ 特性小结
开发语言·c++
醉舞经阁半卷书130 分钟前
Matplotlib从入门到精通
python·数据分析·matplotlib
历程里程碑31 分钟前
Linux 5 目录权限与粘滞位详解
linux·运维·服务器·数据结构·python·算法·tornado
程序员哈基耄40 分钟前
安全高效,本地运行:全能文件格式转换工具
大数据·python·安全
Whisper_Sy1 小时前
Flutter for OpenHarmony移动数据使用监管助手App实战 - 周报告实现
开发语言·javascript·网络·flutter·php
Sylvia-girl1 小时前
线程的死锁【了解】
java·开发语言·jvm