温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何实现高并发下的中Hystrix请求合并

发布时间:2021-12-02 16:20:42 来源:亿速云 阅读:129 作者:柒染 栏目:云计算

如何实现高并发下的中Hystrix请求合并,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

实现高并发下的SpringCloud中Hystrix请求合并
1、在pom.xml中引入maven包

   <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-hystrix -->
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
      <version>2.1.6.RELEASE</version>
    </dependency>

spring Boot 包引入,版本必须一致,否则启动报错。

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.12.RELEASE</version>
    <relativePath/>
  </parent>

2、添加启动注解
@EnableCircuitBreaker该注解启动hystrix,否则不生效。

@SpringBootApplication
@EnableScheduling
@EnableSwagger2
@EnableCaching
@EnableAsync
@ServletComponentScan
@EnableMqHandlerScan(packages = {"com.sxgw.pcops.im.client.mq.handler"})
//使用hystrix必须增加
@EnableCircuitBreaker
public class ClientApplication {

  public static void main(String[] args) {
    SpringApplication.run(ClientApplication.class, args);
  }
}

3、请求接口Controller

@Api(value = "测试")
@RestController
@RequestMapping("/test")
@Slf4j
public class TestController {
  @Autowired
  private UserBatchServiceImpl userBatchServiceImpl;
  @ApiOperation("测试请求合并")
  @PostMapping(value = "/userbyMerge/{id}")
  public String userbyMerge(@PathVariable Long id)  {
    String ids = "";
   try {
     Future<String> userFu = this.userBatchServiceImpl.getUserById(id);
      ids = userFu.get();
   }catch (Exception e){
     e.printStackTrace();
   }
    return ids;
  }

}

4、编写请求合并逻辑
timerDelayInMilliseconds 该参数设置的是线程池中间间隔时间,如间隔5000ms则是一个线程池等待5s后执行

/**
 *
 * @author  
 *
 */
@Component
public class UserBatchServiceImpl {

    @HystrixCollapser(batchMethod = "getUserBatchById",scope= com.netflix.hystrix.HystrixCollapser.Scope.GLOBAL,
            collapserProperties = {@HystrixProperty(name ="timerDelayInMilliseconds",value = "5000")})
    public Future<String> getUserById(Long id) {
        throw new RuntimeException("This method body should not be executed");
    }

    @HystrixCommand
    public List<String> getUserBatchById(List<Long> ids) {
        System.out.println("进入批量处理方法"+ids);
        List<String> ps = new ArrayList<String>();
        for (Long id : ids) {

            ps.add(id+"");
        }
        return ps;
    }
}

5、测试时通过jmeter测试工具测试可以查看到效果。

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI