实现高并发下的SpringCloud中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后执行,maxRequestsInBatch设置每批执行条数

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

    @HystrixCollapser(batchMethod = "getUserBatchById",scope= com.netflix.hystrix.HystrixCollapser.Scope.GLOBAL,
 collapserProperties = {@HystrixProperty(name="timerDelayInMilliseconds",value = "5000"),
            @HystrixProperty(name = "maxRequestsInBatch", value = "500")})
    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测试工具测试可以查看到效果。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值