第一步: 加入依赖
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>30.1-jre</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
<version>2.1.3.RELEASE</version>
</dependency>
<!-- hystrix -->
<dependency>
<groupId>com.netflix.hystrix</groupId>
<artifactId>hystrix-javanica</artifactId>
<version>1.5.6</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.netflix.hystrix</groupId>
<artifactId>hystrix-javanica</artifactId>
<version>1.5.6</version>
<scope>compile</scope>
</dependency>
第二步: 启动类加入注解
第三步: controller层
@PostMapping( "/GroupBuy/{id}")
public Groupbuy userbyMerge(@PathVariable Long id) throws InterruptedException, ExecutionException {
Future<Groupbuy> userFu = this.payGroupbuyService.getGroupById(id);
Groupbuy user = userFu.get();
log.info("返回结果" + user);
return user;
}
第四步: service层
@HystrixCollapser(batchMethod = "findById",scope=Scope.GLOBAL,
collapserProperties = {@HystrixProperty(name ="timerDelayInMilliseconds",
value = "2000")})
// 单个处理方法,建议用Future,这个是jdk线程异步获取的那个类,用于异步获取结果.
public Future<Groupbuy> getGroupById(Long id) {
throw new RuntimeException("This method body should not be executed");
}
// 单个处理方法和批量处理方法必须要同一个基本类型,只是批量方法需要使用List去包裹
@HystrixCommand
public List<Groupbuy> findById(List<Long> ids) {
System.out.println("进入批量处理方法"+ids);
List<Groupbuy> ps = new ArrayList<Groupbuy>();
for (Long id : ids) {
Groupbuy groupbuy = groupbuyMapper.selectById(id);
ps.add(groupbuy);
}
log.info("ps的数据为: "+ps);
return ps;
}
第四步: jmeter测试
进行批量操作
结果返回一条对象: