In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the relevant knowledge of "the request merge method of Hystrix in Spring Cloud". Many people will encounter such a 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!
Service provider interface
I need to provide two interfaces in the service provider for service consumers to invoke, as follows:
RequestMapping ("/ getbook6") public List book6 (String ids) {System.out.println ("ids >" + ids); ArrayList books = new ArrayList (); books.add (new Book ("Li Zicheng", 55, "Yao Xueyin", "people's Literature Publishing House"); books.add ("A brief History of Chinese Literature", 33, "Lin Geng", "Tsinghua University Press")) Books.add (new Book, 33, Hu Shi, Wu); books.add (new Book (ids, 22, helloworld, ); return books;} @ RequestMapping (/ getbook6/ {id}) public Book book61 (@ PathVariable Integer id) {Book book = new Book (Li Zicheng 2, 55, Yao Xueyin 2, Renmin Literature Publishing House 2) Return book;}
The first interface is a batch interface, and the second interface is an interface that handles a single request. In the batch interface, the format of the ids parameter sent by the service consumer is 1, 2, 3, 4. In this format, under normal circumstances, we need to query the corresponding data according to ids, and then assemble it into a collection and return it. For convenience, all requests will return the same data set. The API for handling a single request is relatively simple and will not be discussed in detail.
Service consumers
OK, after the service provider has handled it, let's take a look at what the service consumer is going to do.
BookService
First, add two methods in BookService to invoke the interface provided by the service provider, as follows:
Public Book test8 (Long id) {return restTemplate.getForObject ("http://HELLO-SERVICE/getbook6/{1}", Book.class, id);} public List test9 (List ids) {System.out.println (" test9- "+ ids+" Thread.currentThread (). GetName (): "+ Thread.currentThread (). GetName ()) Book [] books = restTemplate.getForObject ("http://HELLO-SERVICE/getbook6?ids={1}", Book [] .class, StringUtils.join (ids,", ")); return Arrays.asList (books);}
Test8 is used to call the API that provides a single id, and test9 is used to call the API for batch processing. In test9, I print out the thread in which test9 executes, so it is convenient for us to observe the execution result. In addition, in RestTemplate, if the return value is a collection, we have to first receive it with an array, and then convert it to the collection (maybe there are other ways, friends have better suggestions to make).
BookBatchCommand
Once the methods in OK,BookService are ready, we can create a BookBatchCommand, which is a batch command, as follows:
Public class BookBatchCommand extends HystrixCommand {private List ids; private BookService bookService; public BookBatchCommand (List ids, BookService bookService) {super (Setter.withGroupKey (HystrixCommandGroupKey.Factory.asKey ("CollapsingGroup")) .andCommandKey (HystrixCommandKey.Factory.asKey ("CollapsingKey")); this.ids = ids; this.bookService = bookService;} @ Override protected List run () throws Exception {return bookService.test9 (ids);}}
This class is actually similar to the one we introduced in the previous blog, which inherits from HystrixCommand and is used to handle merged requests and call the test9 method in BookService in the run method.
BookCollapseCommand
Next we need to create a BookCollapseCommand that inherits from HystrixCollapser to implement the request merge. As follows:
Public class BookCollapseCommand extends HystrixCollapser {private BookService bookService; private Long id; public BookCollapseCommand (BookService bookService, Long id) {super (Setter.withCollapserKey (HystrixCollapserKey.Factory.asKey ("bookCollapseCommand")) .andCollapserPropertiesDefaults (HystrixCollapserProperties.Setter (). WithTimerDelayInMilliseconds (100)); this.bookService = bookService; this.id = id;} @ Override public Long getRequestArgument () {return id } @ Override protected HystrixCommand createCommand (Collection collapsedRequests) {List ids = new ArrayList (collapsedRequests.size ()); ids.addAll (collapsedRequests.stream (). Map (CollapsedRequest::getArgument) .conversation (Collectors.toList (); BookBatchCommand bookBatchCommand = new BookBatchCommand (ids, bookService); return bookBatchCommand;} @ Override protected void mapResponseToRequests (List batchResponse, Collection collapsedRequests) {System.out.println ("mapResponseToRequests"); int count = 0 For (CollapsedRequest collapsedRequest: collapsedRequests) {Book book = batchResponse.get (count++); collapsedRequest.setResponse (book);}
With regard to this class, I would like to say the following:
1. First of all, in the constructor, we set the request time window to 100ms, that is, requests with a request interval within 100ms will be merged into one request.
The 2.createCommand method is mainly used to merge requests, where you get the id of each single request, put these individual id into a collection, and then create a BookBatchCommand object that is used to initiate a batch request.
The 3.mapResponseToRequests method is mainly used to set the request result for each request. The first parameter of the method, batchResponse, represents the result of the batch request, and the second parameter, collapsedRequests, represents each merged request, and then we set the request result for collapsedRequests by traversing the batchResponse.
OK, when all this is done, we can test it.
test
We create an access interface on the service consumer to test the merge request, as follows:
RequestMapping ("/ test7") @ ResponseBodypublic void test7 () throws ExecutionException, InterruptedException {HystrixRequestContext context = HystrixRequestContext.initializeContext (); BookCollapseCommand bc1 = new BookCollapseCommand (bookService, 1l); BookCollapseCommand bc2 = new BookCollapseCommand (bookService, 21); BookCollapseCommand bc3 = new BookCollapseCommand (bookService, 31); BookCollapseCommand bc4 = new BookCollapseCommand (bookService, 41); Future Q1 = bc1.queue (); Future Q2 = bc2.queue (); Future Q3 = bc3.queue (); Book book1 = q1.get () Book book2 = q2.get (); Book book3 = q3.get (); Thread.sleep (3000); Future Q4 = bc4.queue (); Book book4 = q4.get (); System.out.println ("book1 > >" + book1); System.out.println ("book2 >" + book2); System.out.println ("book3 >" + book3); System.out.println ("book4 >" + book4); context.close ();}
I would like to make the following two points about this test interface:
1. First initialize the HystrixRequestContext
two。 Create an instance of the BookCollapseCommand class to initiate requests, first send 3 requests, then sleep for 3 seconds, and then initiate one request, so that the first three requests will be merged into one request, and the fourth request will not be merged because of the long interval, but a separate thread will be created to process it.
OK, let's take a look at the execution result, as follows:
Request merging through annotations
OK, the above request merge method is a bit troublesome to write, and we can use annotations to implement this function more elegantly. First, add two methods to BookService, as follows:
@ HystrixCollapser (batchMethod = "test11", collapserProperties = {@ HystrixProperty (name = "timerDelayInMilliseconds", value = "100")}) public Future test10 (Long id) {return null;} @ HystrixCommandpublic List test11 (List ids) {System.out.println (" test9- "+ ids+" Thread.currentThread (). GetName (): "+ Thread.currentThread (). GetName ()) Book [] books = restTemplate.getForObject ("http://HELLO-SERVICE/getbook6?ids={1}", Book [] .class, StringUtils.join (ids,", ")); return Arrays.asList (books);}
Add the @ HystrixCollapser annotation to the test10 method to implement the request merge, use the batchMethod attribute to indicate the processing method after the request is merged, and the collapserProperties attribute to specify other attributes.
OK. After you have written it in BookService, you can call it directly, as follows:
RequestMapping ("/ test8") @ ResponseBodypublic void test8 () throws ExecutionException, InterruptedException {HystrixRequestContext context = HystrixRequestContext.initializeContext (); Future f1 = bookService.test10 (1l); Future f2 = bookService.test10 (21); Future f3 = bookService.test10 (31); Book b1 = f1.get (); Book b2 = f2.get (); Book b3 = f3.get (); Thread.sleep (3000); Future f4 = bookService.test10 (41); Book b4 = f4.get () System.out.println ("b1 >" + b1); System.out.println ("b2 > >" + b2); System.out.println ("b3 > >" + b3); System.out.println ("b4 >" + b4); context.close ();}
As before, the first three requests are merged, and the fourth request is executed separately, OK. The execution result is as follows:
Summary
Friends have seen the advantages of request merging. Multiple requests are merged into one request for one-time processing, which can effectively save network bandwidth and thread pool resources. However, there must be advantages and disadvantages. After setting request merging, one request may have been completed by 5ms, but now we have to wait for 10ms to see if there are other requests together. The time consumption of such a request increases from 5ms to 15ms. However, if the command we want to initiate is itself a high-latency command, then you can use request merge at this time, because the time consumption of the time window is negligible. In addition, high concurrency is also a very important scenario for requesting a merge.
This is the end of the content of "Hystrix request merge method in Spring Cloud". 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.
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.