(资料图)
接下来【lái】,我们将创建一个名为“GetDataCollapserExecutor”的类,该【gāi】类【lèi】用于执行【háng】Hystrix请求合并器【qì】:
@Servicepublic class GetDataCollapserExecutor { private final ExternalService externalService; @Autowired public GetDataCollapserExecutor(ExternalService externalService) { this.externalService = externalService; } @HystrixCollapser(batchMethod = "execute", collapserProperties = { @HystrixProperty(name = "timerDelayInMilliseconds", value = "100") }) public Future
如上所述【shù】,我【wǒ】们的GetDataCollapserExecutor类【lèi】包含【hán】以下内容:
构造函数:该【gāi】函数【shù】用【yòng】于注【zhù】入ExternalService实例。getData()方【fāng】法:该【gāi】方法使用@HystrixCollapser注解【jiě】进行注【zhù】释,该注解指定了一个名为“execute”的批量执行方法。在此示例中,我们将timerDelayInMilliseconds属【shǔ】性设置为100毫秒,这意味着【zhe】如果100毫秒【miǎo】内【nèi】有多【duō】个【gè】请求,则它们将被合并为单个请求。execute()方法:该方法使用@HystrixCommand注解进【jìn】行注释,该【gāi】注【zhù】解指定了Hystrix请求合并器执行逻辑【jí】。在此示例中,我【wǒ】们遍历请求参数列【liè】表,并为每个请【qǐng】求【qiú】创建【jiàn】一【yī】个GetDataCollapser实例。最后【hòu】,我们【men】将所有结果合【hé】并到一【yī】个HashMap中,并将其返回。现【xiàn】在,我们可以【yǐ】测试Hystrix请求合并器【qì】是否按预期【qī】工作【zuò】。我们将创建【jiàn】一【yī】个名【míng】为“DataController”的【de】类,并将其用于【yú】向客户端公开API:
@RestControllerpublic class DataController { private final GetDataCollapserExecutor getDataCollapserExecutor; @Autowired public DataController(GetDataCollapserExecutor getDataCollapserExecutor) { this.getDataCollapserExecutor = getDataCollapserExecutor; } @GetMapping("/data") public Map getData(@RequestParam List keys) throws ExecutionException, InterruptedException { List>> futures = new ArrayList>(); for (String key : keys) { futures.add(getDataCollapserExecutor.getData(key)); } Map resultMap = new HashMap>(); for (Future
如上所述,我们的DataController类包含以下内容:
构造函数:该函数用于注入【rù】GetDataCollapserExecutor实【shí】例。getData()方法:该方法使【shǐ】用@GetMapping注解进行注释,该注解指定了API的URL路【lù】径和请求【qiú】方【fāng】法。在【zài】此示例中【zhōng】,我们使用@RequestParam注【zhù】解将请求参数列表注【zhù】入方【fāng】法参数,并使用【yòng】Future和get()方法来【lái】获取Hystrix请求合并器的【de】返回值。现在,我们【men】可以使用Postman或【huò】类似的工【gōng】具向【xiàng】API发送HTTP请求【qiú】,并检查【chá】是否成功合并了多个请【qǐng】求。例如,我【wǒ】们可以向http://localhost:8080/data发送具有以下查询参数的GET请求:
?keys=key1&keys=key2&keys=key3
这【zhè】将使用Hystrix请求合【hé】并器执行三个【gè】请求,并将其结果合并到单个【gè】响应【yīng】中【zhōng】。
现在,我【wǒ】们可【kě】以启动应用程序并测【cè】试它是否按预【yù】期【qī】工【gōng】作。我们可以通过运行以下【xià】命令来启动应用【yòng】程【chéng】序:
mvn spring-boot:run
应用程序启【qǐ】动后【hòu】,我们可以使用Postman或【huò】类似的【de】工具向API发送HTTP请求,并检查是否【fǒu】已成功使用Hystrix请求【qiú】合并器【qì】合并了多个【gè】请【qǐng】求。例如,我们可以向http://localhost:8080/data发送具有以下查询参数的GET请求:
?keys=key1&keys=key2&keys=key3
如果一切正常,我们将看到以下响应:
{ "key1": "Data for key1", "key2": "Data for key2", "key3": "Data for key3"}
这表明Hystrix请【qǐng】求合并器已成功【gōng】执【zhí】行三个请求并【bìng】将其结果合并到单个响【xiǎng】应中【zhōng】。