第一步:导入依赖
<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>
第二步:在启动类上加注解:@EnableCircuitBreaker
第三步:在controller层随便编写一个方法
@PostMapping( "/Find/{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测试效果
测试:进行批量操作
结果返回一个对象: