当前位置:网站首页>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
边栏推荐
- win10使用docker拉取redis镜像报错read-only file system: unknown
- 【Go实战基础】gin 如何绑定与使用 url 参数
- Don't spend money, spend an hour to build your own blog website
- MySql报错:unblock with mysqladmin flush-hosts
- Watermelon book -- Chapter 5 neural network
- 【Go实战基础】如何安装和使用 gin
- Elastic Stack之Beats(Filebeat、Metricbeat)、Kibana、Logstash教程
- 盘点典型错误之TypeError: X() got multiple values for argument ‘Y‘
- 使用IBM MQ远程连接时报错AMQ 4043解决思路
- Servlet全解:继承关系、生命周期、容器和请求转发与重定向等
猜你喜欢

Statistical learning methods - Chapter 5, decision tree model and learning (Part 1)

队列管理器running状态下无法查看通道

Matplotlib swordsman Tour - an artist tutorial to accommodate all rivers

In depth analysis of how the JVM executes Hello World

告别996,IDEA中必装插件有哪些?

概念到方法,绝了《统计学习方法》——第三章、k近邻法

Matplotlib剑客行——容纳百川的艺术家教程

Avoid breaking changes caused by modifying constructor input parameters

There is a problem with MySQL installation (the service already exists)

From concept to method, the statistical learning method -- Chapter 3, k-nearest neighbor method
随机推荐
以字节跳动内部 Data Catalog 架构升级为例聊业务系统的性能优化
Double non undergraduate students enter the factory, while I am still quietly climbing trees at the bottom (Part 1)
微服务实战|手把手教你开发负载均衡组件
Probability is not yet. Look at statistical learning methods -- Chapter 4, naive Bayesian method
A detailed explanation takes you to reproduce the statistical learning method again -- Chapter 2, perceptron model
Sentinel reports failed to fetch metric connection timeout and connection rejection
Win10 uses docker to pull the redis image and reports an error read only file system: unknown
The channel cannot be viewed when the queue manager is running
WSL installation, beautification, network agent and remote development
Data type case of machine learning -- using data to distinguish men and women based on Naive Bayesian method
Cloudreve自建云盘实践,我说了没人能限制得了我的容量和速度
Programmers with ten years of development experience tell you, what core competitiveness do you lack?
一篇详解带你再次重现《统计学习方法》——第二章、感知机模型
Actual combat of microservices | discovery and invocation of original ecosystem implementation services
查看was发布的应用程序的端口
【Go实战基础】gin 高效神器,如何将参数绑定到结构体
Elastic Stack之Beats(Filebeat、Metricbeat)、Kibana、Logstash教程
【Go实战基础】gin 如何获取 GET 和 POST 的请求参数
During MySQL installation, mysqld Exe reports that the application cannot start normally (0xc000007b)`
分布式服务架构精讲pdf文档:原理+设计+实战,(收藏再看)