溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

如何實現高并發(fā)下的中Hystrix請求合并

發(fā)布時間:2021-12-02 16:20:42 來源:億速云 閱讀:133 作者:柒染 欄目:云計算

如何實現高并發(fā)下的中Hystrix請求合并,很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。

實現高并發(fā)下的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后執(zhí)行

/**
 *
 * @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測試工具測試可以查看到效果。

看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注億速云行業(yè)資訊頻道,感謝您對億速云的支持。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI