Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement the request cache of Hystrix in Spring Cloud

2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces the knowledge of "how to implement the request cache of Hystrix in Spring Cloud". Many people will encounter this dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Turn on the cache by overloading the method

If we use Hystrix using a custom Hystrix request command, we only need to override the getCacheKey method to implement the request cache, as follows:

Public class BookCommand extends HystrixCommand {private RestTemplate restTemplate; private Long id; @ Override protected Book getFallback () {Throwable executionException = getExecutionException (); System.out.println (executionException.getMessage ()); return new Book (selected Notes of Song Poems, 88, Qian Zhongshu, Sanlian Bookstore) @ Override protected Book run () throws Exception {return restTemplate.getForObject ("http://HELLO-SERVICE/getbook5/{1}", Book.class,id);} public BookCommand (Setter setter, RestTemplate restTemplate,Long id) {super (setter); this.restTemplate = restTemplate; this.id = id;} @ Override protected String getCacheKey () {return String.valueOf (id);}}

At run time, the system determines whether the request is the same as the previous request based on the return value of the getCacheKey method, that is, it is cached, and if it is cached, it directly uses the cached data without requesting the service provider, so it is obvious that the getCacheKey method will be executed before the run method. I now print a log in the service provider, as follows:

@ RequestMapping (value = "/ getbook5/ {id}", method = RequestMethod.GET) public Book book5 (@ PathVariable ("id") Integer id) {System.out.println ("> / getbook5/ {id}"); if (id = = 1) {return new Book ("Li Zicheng", 55, Yao Xueyin, people's Literature Publishing House) } else if (id = = 2) {return new Book (A brief History of Chinese Literature, 33, Lin Geng, Tsinghua University Press); return new Book (on Literary improvement, 33, Hu Shi, Wu);}

Then we execute the request in the Controller that serves the consumer, as follows:

@ RequestMapping ("/ test5") public Book test5 () {HystrixCommandKey commandKey = HystrixCommandKey.Factory.asKey ("commandKey"); HystrixRequestContext.initializeContext (); BookCommand bc1 = new BookCommand (HystrixCommand.Setter.withGroupKey (HystrixCommandGroupKey.Factory.asKey (")) .andCommandKey (commandKey), restTemplate, 1l); Book E1 = bc1.execute (); BookCommand bc2 = new BookCommand (HystrixCommand.Setter.withGroupKey (HystrixCommandGroupKey.Factory.asKey (")) .andCommandKey (commandKey), restTemplate, 11); Book e2 = bc2.execute () BookCommand bc3 = new BookCommand (HystrixCommand.Setter.withGroupKey (HystrixCommandGroupKey.Factory.asKey (")) .andCommandKey (commandKey), restTemplate, 11); Book e3 = bc3.execute (); System.out.println (" E1: "+ E1); System.out.println (" e2: "+ e2); System.out.println (" e3: "+ e3); return E1;}

I make three identical requests in a row, let's take a look at the log printing of the service provider, and note that the HystrixRequestContext needs to be initialized before the service request can be initiated. The execution results are as follows:

Friends see that the above is the log printed by the service provider, and the following is the log printed by the service consumer, which initiates three requests, but the service provider actually executes only once, and the other two times use cached data.

There is a special case: if I modify the data of the service provider, the cached data should be cleared, otherwise the user may get an incorrect data when reading it, and the cached data can be cleared easily, also according to id, as follows:

@ RequestMapping ("/ test5") public Book test5 () {HystrixCommandKey commandKey = HystrixCommandKey.Factory.asKey ("commandKey"); HystrixRequestContext.initializeContext (); BookCommand bc1 = new BookCommand (HystrixCommand.Setter.withGroupKey (HystrixCommandGroupKey.Factory.asKey (")) .andCommandKey (commandKey), restTemplate, 1l); Book E1 = bc1.execute (); HystrixRequestCache.getInstance (commandKey, HystrixConcurrencyStrategyDefault.getInstance ()) .clear (String.valueOf (11)) BookCommand bc2 = new BookCommand (HystrixCommand.Setter.withGroupKey (HystrixCommandGroupKey.Factory.asKey (")) .andCommandKey (commandKey), restTemplate, 11); Book e2 = bc2.execute (); BookCommand bc3 = new BookCommand (HystrixCommand.Setter.withGroupKey (HystrixCommandGroupKey.Factory.asKey (")) .andCommandKey (commandKey), restTemplate, 11); Book e3 = bc3.execute (); System.out.println ("E1:" + E1); System.out.println ("e2:" + e2) System.out.println ("E3:" + E3); return E1;}

Friends, after we executed the first request, the data with an id of 1 has been cached. Then I use the clear method in HystrixRequestCache to erase the cached data. If I initiate the request again, the service provider's method will be called again. Let's take a look at the execution result, as shown below:

Friends see that the service provider's method is executed twice because I cleared the cache with an id of 1 at the end of the first request.

Turn on caching through annotations

Of course, we can also enable caching through annotations. There are three annotations related to caching, which are @ CacheResult, @ CacheKey and @ CacheRemove, respectively.

@ CacheResult

The @ CacheResult method can be used on our previous Service method to indicate that caching is enabled for this method. By default, all parameters of the method will be cached key, as follows:

CacheResult@HystrixCommandpublic Book test6 (Integer id,String aa) {return restTemplate.getForObject ("http://HELLO-SERVICE/getbook5/{1}", Book.class, id);}

At this point, the test6 method will automatically enable caching. By default, all parameters will be cached key. If the two parameters passed in a call are the same as those passed before, the cache will be used directly, otherwise the request will be initiated as follows:

@ RequestMapping ("/ test6") public Book test6 () {HystrixRequestContext.initializeContext (); / / first request Book b1 = bookService.test6 (2, "); / / parameters are the same as last time, using cached data Book b2 = bookService.test6 (2,"); / / parameters are inconsistent, initiate a new request Book b3 = bookService.test6 (2, "aa"); return b1;}

Of course, we can also add the cacheKeyMethod attribute to @ CacheResult to specify the method that returns the cache key. Note that the returned key is of type String, as follows:

@ CacheResult (cacheKeyMethod = "getCacheKey2") @ HystrixCommandpublic Book test6 (Integer id) {return restTemplate.getForObject ("http://HELLO-SERVICE/getbook5/{1}", Book.class, id);} public String getCacheKey2 (Integer id) {return String.valueOf (id);}

The default rule is invalid at this time.

@ CacheKey

Of course, in addition to using the default data, we can also use @ CacheKey to specify the cached key, as follows:

@ CacheResult@HystrixCommandpublic Book test6 (@ CacheKey Integer id,String aa) {return restTemplate.getForObject ("http://HELLO-SERVICE/getbook5/{1}", Book.class, id);}

Here, we use the @ CacheKey annotation to indicate that the cached key is id, which has nothing to do with the parameter aa. In this case, as long as the id is the same, it is considered to be the same request, and the value of the aa parameter will not be used as the basis for determining the cache (here is just an example. In actual development, our call conditions may all be used as key, otherwise incorrect data may be obtained). If we use the cacheKeyMethod attribute in @ CacheResult to specify key and the @ CacheKey annotation to specify key, the latter is invalid.

@ CacheRemove

This is, of course, a comment to invalidate the cache, and the usage is simple, as follows:

@ CacheRemove (commandKey = "test6") @ HystrixCommandpublic Book test7 (@ CacheKey Integer id) {return null;}

Note that the value of commandKey,commandKey must be specified as the location of the cache, and the value of the commandKey attribute must be configured before Hystrix can find the location of the request command cache. To give a simple example, it is as follows:

@ RequestMapping ("/ test6") public Book test6 () {HystrixRequestContext.initializeContext (); / / first request Book b1 = bookService.test6 (2); / / clear cache bookService.test7 (2); / / cache is cleared, re-initiate request Book b2 = bookService.test6 (2); / / parameters are consistent, using cached data Book b3 = bookService.test6 (2); return b1 } the content of "how to implement the request cache of Hystrix in Spring Cloud" is introduced here. Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

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.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report