In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
How to make SpringCloud-Hystrix cache and merge request, I believe many inexperienced people are helpless about this, for this reason this article summarizes the causes and solutions of the problem, through this article I hope you can solve this problem.
Caching is often used in development, and we often use third-party caching databases such as Redis to cache data.
result cache
Method level caching is also provided for us in Hystrix. Whether cached data is returned is determined by rewriting getCacheKey, which can be generated based on parameters. In this way, the same parameters can be used in the cache.
Revamp the previous MyHystrixCommand and add a rewrite implementation of getCacheKey to it, as shown below.
@Overrideprotected String getCacheKey() {return String.valueOf(this.name);}
In the above code, we use the name parameter passed in when creating the object as the cached key.
In order to prove that cache can be used, add a line of output to the run method. In the case of multiple calls, if the console only outputs once, then you can know that the latter is the cache logic. The code is as follows.
@Overrideprotected String run() {System.err.println("get data");return this.name + ":" + Thread.currentThread().getName();}
Execute the main method and find that the program reported an error, as shown in Figure 1:
The complete error message is as follows:
Caused by: java.lang.IllegalStateException: Request caching is not available. Maybe you need to initialize the HystrixRequestContext?
As you can see from the error message, cache processing depends on the context of the request, we must initialize Hystrix-RequestContext.
Modify the call code in the main method to initialize HystrixRequestContext, as shown below.
public static void main(String[] args) throws InterruptedException, ExecutionException { HystrixRequestContext context = HystrixRequestContext.initializeContext(); String result = new MyHystrixCommand("zhangsan").execute(); System.out.println(result); Future future = new MyHystrixCommand("zhangsan").queue(); System.out.println(future.get()); context.shutdown();}
After the modification, rewrite the main method to run normally, and the output is shown in Figure 2:
我们可以看到只输出了一次 get data,缓存生效。
缓存清除
刚刚我们学习了如何使用 Hystrix 来实现数据缓存功能。有缓存必然就有清除缓存的动作。
当数据发生变动时,必须将缓存中的数据也更新掉,不然就会出现脏数据的问题。同样地,Hystrix 也有清除缓存的功能。
增加一个支持缓存清除的类,代码如下所示。
public class ClearCacheHystrixCommand extends HystrixCommand {private final String name;private static final HystrixCommandKey GETTER_KEY = HystrixCommandKey.Factory.asKey("MyKey");public ClearCacheHystrixCommand(String name) {super(HystrixCommand.Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("MyGroup")) .andCommandKey(GETTER_KEY));this.name = name; }public static void flushCache(String name) { HystrixRequestCache.getInstance(GETTER_KEY,HystrixConcurrencyStrategyDefault.getInstance()).clear(name); }@Overrideprotected String getCacheKey() {return String.valueOf(this.name); }@Overrideprotected String run() { System.err.println("get data");return this.name + ":" + Thread.currentThread().getName(); }@Overrideprotected String getFallback() {return "失败了 "; }}
flushCache 方法就是清除缓存的方法,通过 HystrixRequestCache 来执行清除操作,根据 getCacheKey 返回的 key 来清除。
修改调用代码来验证清除是否有效果,代码如下所示。
public static void main(String[] args) throws InterruptedException, ExecutionException { HystrixRequestContext context = HystrixRequestContext.initializeContext(); String result = new ClearCacheHystrixCommand("zhangsan").execute(); System.out.println(result); ClearCacheHystrixCommand.flushCache("zhangsan"); Future future = new ClearCacheHystrixCommand("zhangsan").queue(); System.out.println(future.get());}
执行两次相同的 key,在第二次执行之前调用缓存清除的方法,也就是说第二次用不到缓存,输出结果如图 3 所示:
由此可以看出,输出两次 get data,这证明缓存确实被清除了。可以把 ClearCache-HystrixCommand.flushCache 这行代码注释掉再执行一次,就会发现只输出了一次 get data,缓存是有效的,输入结果如图 2 所示。
合并请求
Hystrix 支持将多个请求自动合并为一个请求(代码如下所示),利用这个功能可以节省网络开销,比如每个请求都要通过网络访问远程资源。如果把多个请求合并为一个一起执行,将多次网络交互变成一次,则会极大地节省开销。
public class MyHystrixCollapser extends HystrixCollapser {private final String name;public MyHystrixCollapser(String name) {this.name = name; }@Overridepublic String getRequestArgument() {return name; }@Overrideprotected HystrixCommand createCommand(final Collection requests) {return new BatchCommand(requests); }@Overrideprotected void mapResponseToRequests(List batchResponse, Collection requests) { int count = 0;for (CollapsedRequest request : requests) { request.setResponse(batchResponse.get(count++)); } }private static final class BatchCommand extends HystrixCommand {private final Collection requests;private BatchCommand(Collection requests) {super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("ExampleGroup")) .andCommandKey(HystrixCommandKey.Factory.asKey("GetValueForKey")));this.requests = requests; }@Overrideprotected List run() { System.out.println(" 真正执行请求......"); ArrayList response = new ArrayList();for (CollapsedRequest request : requests) { response.add(" 返回结果 : " + request.getArgument()); }return response; } }}
接下来编写测试代码,代码如下所示。
public static void main(String[] args) throws InterruptedException, ExecutionException { HystrixRequestContext context = HystrixRequestContext.initializeContext(); Future f1 = new MyHystrixCollapser("zhangsan").queue(); Future f2 = new MyHystrixCollapser("zhangsan333").queue(); System.out.println(f1.get() + "=" + f2.get()); context.shutdown();}
通过 MyHystrixCollapser 创建两个执行任务,按照正常的逻辑肯定是分别执行这两个任务,通过 HystrixCollapser 可以将多个任务合并到一起执行。从输出结果就可以看出,任务的执行是在 run 方法中去做的,输出结果如图 4 所示:
看完上述内容,你们掌握如何进行SpringCloud-Hystrix缓存与合并请求的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注行业资讯频道,感谢各位的阅读!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.