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

Example Analysis of Hystrix caching and merge request in Spring Cloud

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)05/31 Report--

Editor to share with you the example analysis of Hystrix caching and merge requests in Spring Cloud. I believe most people don't know much about it, so share this article for your reference. I hope you can learn a lot after reading this article. Let's learn about it together.

Cache and merge request cache comments

The caching capabilities of Hystrix are described in chapter 6.3. in Spring Cloud, caching is also supported and can be implemented through annotations. According to the previous section, caching and merging request functions need to initialize the request context before it can be implemented. Create a new javax.servlet.Filter to create and destroy the request context of the Hystrix, as shown in listing 6-9.

Listing 6-19:

Codes\ 06\ 6.4\ spring-hystrix-invoker\ src\ main\ java\ org\ crazyit\ cloud\ HystrixFilter.java

@ WebFilter (urlPatterns = "/ *", filterName = "hystrixFilter") public class HystrixFilter implements Filter {public void init (FilterConfig filterConfig) throws ServletException {} public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {HystrixRequestContext context = HystrixRequestContext .initializeContext (); try {chain.doFilter (request, response);} finally {context.shutdown () }} public void destroy () {}}

Write the service method, decorated with the @ CacheResult annotation, as shown in listing 6-20.

Listing 6-20:CacheService.java

@ Componentpublic class CacheService {@ CacheResult @ HystrixCommand public Person getPerson (Integer id) {System.out.println ("execute getPerson method"); Person p = new Person (); p.setId (id); p.setName ("angus"); return p;}}

Note that in the service method, the console output is done once after being called. In the method of the controller, the getPerson method is called multiple times. The controller code is shown in listing 6-21.

Listing 6-21:

Codes\ 06\ 6.4\ spring-hystrix-invoker\ src\ main\ java\ org\ crazyit\ cloud\ InvokerController.java

@ RequestMapping (value = "/ cache1/ {personId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public Person testCacheResult (@ PathVariable Integer personId) {/ / invoke multiple service for (int I = 0; I < 3; iService +) {Person p = cacheService.getPerson (personId); System.out.println ("controller invokes service" + I) } return new Person ();}

The service method is called multiple times in the controller, that is, after the user sends the request, the service method is executed multiple times, the "service caller" is started, and the following address is accessed: http://localhost:9000/cache1/1. The console output is as follows:

Execute getPerson method controller invokes service 0 controller invokes service 1 controller invokes service 2

According to the output, in the process of a user request, the service method is executed only once, and the cache takes effect. There are three main comments in the cache:

CacheResult: this annotation modifies the method, indicating that the result returned by the modified method will be cached and needs to be used with @ HystrixCommand.

@ CacheRemove: used to modify the method to invalidate the cache, which needs to be associated with the cache key of @ CacheResult.

CacheKey: used to modify a method parameter, indicating that it is used as a cached key.

The previous example uses the @ CacheResult annotation, and the following code snippet is used in conjunction with @ CacheResult and @ CacheRemove:

@ CacheResult () @ HystrixCommand (commandKey = "removeKey") public String cacheMethod (String name) {return "hello";} @ CacheRemove (commandKey = "removeKey") @ HystrixCommand public String updateMethod (String name) {return "update";}

The cacheMethod method in the above code snippet uses a cache key of "removeKey". When the method updateMethod is called, the cache with the key of "updateMethod" will be deleted. As for the more in-depth use of the three cache annotations, this section will not repeat them, and readers can test them themselves.

Merge request comment

In Spring Cloud, merge requests are also supported. During a HTTP request, the same requests are collected for a period of time and executed in a batch command. To implement a merge request, you also need to initialize the request context. For more information, please see Filter in 6.4.4. Next, write the service class, as shown in listing 6-22.

Listing 6-22:CollapseService.java

Public class CollapseService {/ / configure @ HystrixCollapser (batchMethod = "getPersons", collapserProperties = {@ HystrixProperty (name = "timerDelayInMilliseconds", value = "1000")}) public Future getSinglePerson (Integer id) {System.out.println ("execute a single acquisition method"); return null } @ HystrixCommand public List getPersons (List ids) {System.out.println ("collect request, number of parameters:" + ids.size ()); List ps = new ArrayList (); for (Integer id: ids) {Person p = new Person (); p.setId (id); p.setName ("crazyit"); ps.add (p) } return ps;}}

In the code listing, the last method actually executed is "getPersons". The getSinglePerson method is decorated with the @ HystrixCollapser annotation and collects the request for calling getSinglePerson within 1 second and puts it into the getPersons method for batch processing. The getSinglePerson method is called multiple times in the controller, as shown in listing 6-23.

Listing 6-23:

Codes\ 06\ 6.4\ spring-hystrix-invoker\ src\ main\ java\ org\ crazyit\ cloud\ InvokerController.java

@ RequestMapping (value = "/ collapse", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public String testCollapse () throws Exception {/ / execute three consecutive requests Future F1 = collapseService.getSinglePerson (1); Future f2 = collapseService.getSinglePerson (2); Future f3 = collapseService.getSinglePerson (3); Person p1 = f1.get (); Person p2 = f2.get () Person p3 = f3.get (); System.out.println (p1.getId () + "- -" + p1.getName ()); System.out.println (p2.getId () + "- -" + p2.getName ()); System.out.println (p3.getId () + "- -" + p3.getName ()); return ";}

The getSinglePerson method is executed asynchronously three times to start the "Service Caller" and visit the following address: http://localhost:9000/collapse. The console output is as follows:

Collect requests. Number of parameters: 31---crazyit2---crazyit3---crazyit

According to the output, only the getPersons method is executed in the end. Instead of directly using the merge request in Hystrix,Spring Cloud, the merge processor has been implemented for us by the @ HystrixCollapser annotation, and we only care about the execution of the real command.

The above is all the content of the article "sample Analysis of Hystrix caching and merge requests in Spring Cloud". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

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

Servers

Wechat

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

12
Report