Hystrix 简单请求合并

2023-11-19

频繁的调用provider接太浪费了, 就有了将多个请求合并为一个请求的方式。
首先在provider中提供一个请求合并的接口:

@RestController
public class UserController {
    /**【既可以处理多个,也可以处理单个请求】
    *单个请求的话,List中只有一项数据
    *假设 consumer 传过来的多个id格式是 1,2,3,4....*/
    @GetMapping("/user/{ids}")
    public List<User> getUserByIds(@PathVariable String ids){
        System.out.println(ids);
        String[] split = ids.split(",");
        List<User> user = new ArrayList<>();
        for(String s : split){
            User user1 = new User();
            user1.setId(Integer.parseInt(s));
            user.add(user1);
        }
        return user;
    }
}

然后在Hystrix中定义UserService:

@Service
public class UserService {

    @Autowired
    RestTemplate restTemplate;
    

    public List<User> getUsersByIds(List<Integer> ids){
        User[] users = restTemplate.getForObject("http://provider/user/{1}", User[].class, StringUtils.join(ids, ","));
        return Arrays.asList(users);
    }
}

接下来定义 UserBatchCommand ,相当于我们之前的 HelloCommand:

public class UserBatchCommand extends HystrixCommand<List<User>> {
    private List<Integer> ids;
    private UserService userService;

    public UserBatchCommand(List<Integer> ids, UserService userService) {
        super(HystrixCommand.Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("batchCmd")).andCommandKey(HystrixCommandKey.Factory.asKey("batchKey")));
        this.ids = ids;
        this.userService = userService;
    }

    @Override
    protected List<User> run() throws Exception {
        return userService.getUsersByIds(ids);
    }
}

一、最后定请求合并方法,【继承方式,做为了解】:

public class UserCollapseCommand extends HystrixCollapser<List<User>, User, Integer> {
    private UserService userService;
    private Integer id;

    public UserCollapseCommand(UserService userService, Integer id) {
        super(HystrixCollapser.Setter.withCollapserKey(HystrixCollapserKey.Factory.asKey("UserCollapseCommand")).andCollapserPropertiesDefaults(HystrixCollapserProperties.Setter().withTimerDelayInMilliseconds(200)));
        this.userService = userService;
        this.id = id;
    }

    /**
     * 请求参数
     *
     * @return
     */
    @Override
    public Integer getRequestArgument() {
        return id;
    }

    /**
     * 请求合并的方法
     *
     * @param collection
     * @return
     */
    @Override
    protected HystrixCommand<List<User>> createCommand(Collection<CollapsedRequest<User, Integer>> collection) {
        List<Integer> ids = new ArrayList<>(collection.size());
        for (CollapsedRequest<User, Integer> userIntegerCollapsedRequest : collection) {
            ids.add(userIntegerCollapsedRequest.getArgument());
        }
        return new UserBatchCommand(ids, userService);
    }

    /**
     * 请求结果分发
     *
     * @param users
     * @param collection
     */
    @Override
    protected void mapResponseToRequests(List<User> users, Collection<CollapsedRequest<User, Integer>> collection) {
        int count = 0;
        for (CollapsedRequest<User, Integer> request : collection) {
            request.setResponse(users.get(count++));
        }
    }
}

然后测试调用:

@GetMapping("/hello5")
    public void hello5() throws ExecutionException,InterruptedException{
        HystrixRequestContext ctx = HystrixRequestContext.initializeContext();
        UserCollapseCommand cmd1 = new UserCollapseCommand(userService, 99);
        UserCollapseCommand cmd2 = new UserCollapseCommand(userService, 98);
        UserCollapseCommand cmd3 = new UserCollapseCommand(userService, 97);

        Future<User> q1 = cmd1.queue();
        Future<User> q2 = cmd2.queue();
        Future<User> q3 = cmd3.queue();

        User u1 = q1.get();
        User u2 = q2.get();
        User u3 = q3.get();

        System.out.println(u1);
        System.out.println(u2);
        System.out.println(u3);
        Thread.sleep(2000);//睡2秒就变成两次请求,
        UserCollapseCommand cmd4 = new UserCollapseCommand(userService, 96);
        Future<User> q4 = cmd4.queue();
        User u4 = q4.get();
        System.out.println(u4);
        ctx.close();

    }

二、通过注解实现请求合并【掌握】:

@Service
public class UserService {

    @Autowired
    RestTemplate restTemplate;

    /**
     * 注解方式实现请求合并
     * @param id
     * @return HystrixCollapse
     *【重要:@HystrixCollapser 注解指定批处理方法】
     */
    @HystrixCollapser(batchMethod = "getUsersByIds",collapserProperties = {@HystrixProperty(name = "timerDelayInMilliseconds",value = "200")})
    public Future<User> getUserById(Integer id) {
        return null;
    }

    @HystrixCommand
    public List<User> getUsersByIds(List<Integer> ids){
        User[] users = restTemplate.getForObject("http://provider/user/{1}", User[].class, StringUtils.join(ids, ","));
        return Arrays.asList(users);
    }
}

测试方法:

    /**
     * 注解方式实现请求合并 测试方法
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @GetMapping("/hello6")
    public void hello6() throws ExecutionException, InterruptedException {
        HystrixRequestContext ctx = HystrixRequestContext.initializeContext();
        Future<User> q1 = userService.getUserById(99);
        Future<User> q2 = userService.getUserById(98);
        Future<User> q3 = userService.getUserById(97);
        User u1 = q1.get();
        User u2 = q2.get();
        User u3 = q3.get();
        System.out.println(u1);
        System.out.println(u2);
        System.out.println(u3);
        Thread.sleep(2000);
        Future<User> q4 = userService.getUserById(96);
        User u4 = q4.get();
        System.out.println(u4);
        ctx.close();
    }

小结 :@HystrixCollapser(batchMethod = “getUserByIds”,collapserProperties = {@HystrixProperty(name = “timerDelayInMilliseconds”,value = “200”)})

@HystrixCommand

代码地址:https://github.com/astronger/springcloud-simple-samples

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Hystrix 简单请求合并 的相关文章

随机推荐

  • feignclient发送get请求,传递参数为对象。

    feignclient发送get请求 传递参数为对象 此时不能使用在地址栏传递参数的方式 需要将参数放到请求体中 第一步 修改application yml中配置feign发送请求使用apache httpclient 而不是默认的jdk
  • 做什么副业比较赚钱,这五个项目现在入行可能比上班挣得还多

    还有2个月不到的时间 2022就要过去了 这一年太魔幻了 而普通人的生活也的确太难了 这一年 各行各业都在萎缩 制造业急剧萎缩 要么不能静态生产 要么生产了就送不出去 因为可能是疫区 也可能是收货地 这样老板和员工都赚不到钱 中小商户和商铺
  • 我们无法设置移动热点_Win10 校园拨号连接情况下开热点

    win10校园网下开启热点 本段文字用以解决win10下无法建立移动热点 错误提示为 我们无法设置移动热点 因为你的电脑未建立以太网 WIFI或手机网络连接 这个问题可能出现在拨号上网连接的设备上 这也就是说我们的电脑现在无法识别出我们所用
  • java 读取resource下的文件

    目录 一 普通main代码里使用 1 假设有如下结构的代码 1 main方法里复制resource下的文件 2 main方法里读取resource下的文件 2 假设有如下结构的代码 二 对于springboot项目读取resource下的资
  • JDBC数据源连接池(4)---自定义数据源连接池

    JDBC数据源连接池 4 自定义数据源连接池 续上文 JDBC数据源连接池 3 Tomcat集成DBCP 我们已经 了解了DBCP C3P0 以及Tomcat内置的数据源连接池 那么 这些数据源连接池是如何实现的呢 为了究其原理 我在这里写
  • Bootstarp入门教程(5) 排版(2)

    3 缩略语 当鼠标悬停在缩写和缩写词上时就会显示完整内容 Bootstrap实现了对HTML的
  • 如何理解和解决高并发

    如何理解高并发 高并发指的两方面 提升硬件 负载均衡 使用缓存 缓存一致性如何保证 限流 DNS负载均衡 线程池和分布式锁 总结 高并发指的两方面 同一时刻有大量的请求访问系统 有大量的请求并行访问系统 当大量请求短时间内涌入系统的时候 我
  • 2018中国汽车企业排行榜TOP10

    看排名 懂中国汽车 Aming 汽车行业变化很快 但是从上市车企的情况来看 可以看到具体的财报数字 因而可以知道一个更具体的发展情况 不过这次的排行榜主要针对2018年上半年中国已经上市的汽车企业 特别推出利润排行榜与销量排行榜 同时还有利
  • Dockerfile讲解和案例分享

    目录 dockerfile是在容器外部 构建三部曲 dockerfile基本知识 dockerfile执行流程 dockerfile 常用保留字 FROM MAINTAINER RUN EXPOSE WORKDIR USER ENV ADD
  • 40个学术网站

    40个学术网站 满足你的科研需求 2018 03 06 美国留学那点事 文 中外学术情报 微信号 Academic Information 科研工作者每天日常莫过于看文献 做实验 写论文 人生最郁闷的事情不过于是导师说 那个XX 帮我下载下
  • java secretkey用法_Java SecretKeyFactory.generateSecret方法代码示例

    本文整理汇总了Java中javax crypto SecretKeyFactory generateSecret方法的典型用法代码示例 如果您正苦于以下问题 Java SecretKeyFactory generateSecret方法的具体
  • Rust- 类型转换

    Rust is a statically typed language which means that it emphasizes on knowing the types of all variables at compile time
  • Python全栈开发【基础-05】基本数据类型

    专栏介绍 本专栏为Python全栈开发系列文章 技术包括Python基础 函数 文件 面向对象 网络编程 并发编程 MySQL数据库 HTML JavaScript CSS JQuery bootstrap WSGI Django Flas
  • LeetCode 124. 二叉树中的最大路径和 Python

    给定一个非空二叉树 返回其最大路径和 本题中 路径被定义为一条从树中任意节点出发 达到任意节点的序列 该路径至少包含一个节点 且不一定经过根节点 示例 1 输入 1 2 3 1 2 3 输出 6 示例 2 输入 10 9 20 null n
  • n-gram模型中的平滑方法

    当使用n gram模型对测试语料中的句子进行评估时 如果句子中包含在训练集中未出现的n元语法 则计算出来句子出现的概率为0 例如上一篇博客语言模型和n元语法中的例子 此时用该模型来计算下面句子的概率 因此 必须分配给所有可能出现的字符串一个
  • 关于Vue.js和React.js,听听国外的开发者怎么说?

    VueJS 与 ReactJS 到底怎么样如何 听听别人怎么说 使用所有新的库和框架 很难跟上所有这些库和框架 也就是说 这就需要您决定哪些是值得花时间的 让我们看看人们说什么 和Vue JS一起工作是很愉快的 我发现学习曲线很浅 然而 这
  • 【LeetCode75】第五十九题 第N个泰波那契数

    目录 题目 示例 分析 代码 题目 示例 分析 题目顾名思义 让我们求出第N个泰波那契数 也就是除了开头三个数之外 第四个数开始就是等于前三个数之和 不要和斐波那契数弄混了 斐波那契是前两个数的和 泰波那契是前三个数的和 也就是说当前数 我
  • docker容器内修改文件

    1 找到容器对应的ID 使用docker ps命令找到对应的镜像id 2 根据容器id进入到对应文件夹 执行命令 docker exec it 镜像id bin bash 3 进入对应目录 以MySQL为例 执行命令cd etc mysql
  • HTML学习

    HTML 我的第一个网页 基本标签 图片标签 链接标签 列表 表格 媒体元素 页面结构分析 iframe内联框架 表单 我的第一个网页
  • Hystrix 简单请求合并

    频繁的调用provider接太浪费了 就有了将多个请求合并为一个请求的方式 首先在provider中提供一个请求合并的接口 RestController public class UserController 既可以处理多个 也可以处理单个