当前位置:网站首页>Hystrix implements request consolidation
Hystrix implements request consolidation
2022-07-02 09:22:00 【Protect our fat tiger】
Add
@EnableHystrix
@EnableHystrixDashboard
Add dependencies on services that need to be merged
<!--hystrix rely on -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>
Request interface
package com.leilei.controller;
import com.leilei.entity.AlarmDictionary;
import com.leilei.service.AlarmService;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;
import org.springframework.web.bind.annotation.*;
import java.util.concurrent.Future;
/** * @author lei * @create 2022-03-30 22:45 * @desc **/
@RequestMapping("/alarm")
@RestController
public class AlarmController {
private final AlarmService alarmService;
public AlarmController(AlarmService alarmService) {
this.alarmService = alarmService;
}
/** * External single request interface * @param id * @return */
@GetMapping(value = "/dictionary/{id}")
public AlarmDictionary requestCollapseAnnotation(@PathVariable Integer id) {
// Note that it needs to be turned on Hystrix Environmental Science
try (HystrixRequestContext context = HystrixRequestContext.initializeContext()) {
Future<AlarmDictionary> f1 = alarmService.find(id);
return f1.get();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
Aggregate batch processing inside the service
package com.leilei.service;
import com.leilei.entity.AlarmDictionary;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCollapser;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.concurrent.Future;
/** * @author lei * @create 2022-03-30 22:38 * @desc **/
@Service
public class AlarmService {
private final AlarmFeign alarmFeign;
public AlarmService(AlarmFeign alarmFeign) {
this.alarmFeign = alarmFeign;
}
/** * batchMethod Set the interface name of the batch method * HystrixProperty name Set to time delay timerDelayInMilliseconds That is, how long the request is submitted as a batch ;value Is the time threshold , In milliseconds * @param id * @return */
@HystrixCollapser(batchMethod = "findBatch",
collapserProperties = {
@HystrixProperty(name = "timerDelayInMilliseconds", value = "1000")})
public Future<AlarmDictionary> find(Integer id) {
throw new RuntimeException("This method body should not be executed");
}
@HystrixCommand
public List<AlarmDictionary> findBatch(List<Integer> alarms) {
List<AlarmDictionary> alarmDictionaries = alarmFeign.getBatch(alarms);
System.out.println(Thread.currentThread().getName() + ":" + alarmDictionaries);
return alarmDictionaries;
}
}
Service providers ( Of course, you can't use remote here , Using the internal batch logic of the service )
@RestController
@RequestMapping("/alarm/dictionary")
public class AlarmDictionaryController {
static List<AlarmDictionary> alarms = new ArrayList<>();
static {
alarms.add(new AlarmDictionary(1,"808 First level alarm "));
alarms.add(new AlarmDictionary(2,"808 Level two alarm "));
alarms.add(new AlarmDictionary(3,"808 Three alarm "));
alarms.add(new AlarmDictionary(4," Fatigue driving level 1 alarm "));
}
@PostMapping("/batch")
public List<AlarmDictionary> getBatchAlarmById(@RequestBody List<Integer> alarmIds) {
return alarms.stream().filter(x -> alarmIds.contains(x.getId())).collect(Collectors.toList());
}
}
test result

problem :
Hystrix The request must be in the request response mode , That is to say , A request must have a corresponding result , If the response is empty , An exception will be thrown
Caused by: java.lang.RuntimeException: Failed to map all collapsed requests to response. The expected contract has not been respected. Collapser key: 'find', requests size: '1', response size: '0'
at com.netflix.hystrix.contrib.javanica.collapser.CommandCollapser.mapResponseToRequests(CommandCollapser.java:76)
at com.netflix.hystrix.contrib.javanica.collapser.CommandCollapser.mapResponseToRequests(CommandCollapser.java:33)
at com.netflix.hystrix.HystrixCollapser$1$1.call(HystrixCollapser.java:171)
at rx.internal.util.ActionObserver.onNext(ActionObserver.java:39)
at rx.internal.operators.OnSubscribeDoOnEach$DoOnEachSubscriber.onNext(OnSubscribeDoOnEach.java:96)
... 68 more

At present, we can try-catch Handle , Better solutions need to be updated …
TODO…
Attach project address :hystrix-batch-collapser
边栏推荐
- Redis安装部署(Windows/Linux)
- 微服务实战|手把手教你开发负载均衡组件
- "Redis source code series" learning and thinking about source code reading
- Win10 uses docker to pull the redis image and reports an error read only file system: unknown
- 队列管理器running状态下无法查看通道
- 《统计学习方法》——第五章、决策树模型与学习(上)
- Talk about the secret of high performance of message queue -- zero copy technology
- Redis zadd导致的一次线上问题排查和处理
- ORA-12514问题解决方法
- Oracle delete tablespace and user
猜你喜欢

Chrome video download Plug-in – video downloader for Chrome

微服务实战|手把手教你开发负载均衡组件

Knowledge points are very detailed (code is annotated) number structure (C language) -- Chapter 3, stack and queue

Ora-12514 problem solving method

Avoid breaking changes caused by modifying constructor input parameters

Watermelon book -- Chapter 5 neural network

Win10 uses docker to pull the redis image and reports an error read only file system: unknown

Microservice practice | Eureka registration center and cluster construction

Programmers with ten years of development experience tell you, what core competitiveness do you lack?

企业级SaaS CRM实现
随机推荐
Matplotlib剑客行——初相识Matplotlib
【Go实战基础】gin 如何验证请求参数
Ora-12514 problem solving method
【Go实战基础】gin 如何绑定与使用 url 参数
Microservice practice | Eureka registration center and cluster construction
Demand delineation executive summary
JVM指令助记符
Chrome user script manager tempermonkey monkey
自定义Redis连接池
Microservice practice | teach you to develop load balancing components hand in hand
Pdf document of distributed service architecture: principle + Design + practice, (collect and see again)
十年开发经验的程序员告诉你,你还缺少哪些核心竞争力?
西瓜书--第六章.支持向量机(SVM)
Chrome用户脚本管理器-Tampermonkey 油猴
概念到方法,绝了《统计学习方法》——第三章、k近邻法
Jingdong senior engineer has developed for ten years and compiled "core technology of 100 million traffic website architecture"
View the port of the application published by was
I've taken it. MySQL table 500W rows, but someone doesn't partition it?
[go practical basis] how to bind and use URL parameters in gin
聊聊消息队列高性能的秘密——零拷贝技术