Hystrix protection mechanisms for unavailable services and introduction of caching

Source: Internet
Author: User

    I wrote a blog post about the basic use of hystrix through a case study, in which we call a service that works through Hystrix, which means that the Hytrix protection mechanism doesn't work. Here we will demonstrate the process of hystrix initiating a protection mechanism when calling an unavailable service in Hystrixprotectdemo.java. This class is based on the Normalhystrixdemo.java rewrite, only in which the Getfallback method is added, the code is as follows.      

1//omit the necessary package and import code 2public class Hystrixprotectdemo extends hystrixcommand<string> {3RestClient client = Null;4httprequest request = null;5//constructor very similar to 6public hystrixdemoprote Ctdemo () {7super (HystrixCommandGroupKey.Factory.asKey ("Examplegroup")); 8}9//initrestclient method unchanged 10private void Initrestclient () {11//and Normalhystrixdemo.java, please refer to code 12}13//run method also unchanged 14protected String run () {15//and Normalhystrix Demo.java, please refer to code 16}17//This time multiple Getfallback method, once error, will call code 18protected String Getfallback () {19// Omit the action of jumping to the error prompt page 20return "Call unavailable Service."; 21}22//main function 23public static void main (string[] args) {24HystrixDemoProtectDemo Normaldemo = new Hystrixdemoprotectdemo (); 25normaldemo.initrestclient (); 26try {27thread.sleep (+);) catch (Interruptedexception e) { 29e.printstacktrace (); 31String result = Normaldemo.execute (); 32system.out.println ("Call available function, Result is: "+ result"; 33}34} 

The constructors in this class are similar to Normalhystrixdemo.java, and the Initrestclient and run methods do not change at all, so they are not given in detail.

In line 18th, we rewrite the Getfallback method of the Hystrixcommand class, in which we define the action that once the access is wrong, here is just the output a paragraph, in the actual project, you can jump to the corresponding error prompt page.

The code in the main function is exactly the same as in the Normalhystrixdemo.java, except that there is no need to run the startup class of the Hystrixserverdemo project before running this code, so the service must not be called. After running this code, we can see the following results.

In Run

Call available function, result is:call unavailable Service.

From the output on line 2nd, we can confirm that the Hystrix processing class can call the Getfallback method automatically once the service error is invoked.

If the Getfallback method is not defined here, then once the service is unavailable, the user may see a bunch of meaningless content in the browser after the connection times out, so that the user experience is poor and if other fault-tolerant measures are not in place for the entire system, it may even cause current and downstream modules to be paralyzed.

On the contrary, as we are well prepared in the Getfallback method provided by Hystirx, the error-handling code can be triggered immediately if there is an error, and the effect is equivalent to the process of the fusing.

By getfallback, friendly to inform the user of the problem, as well as the subsequent how to deal with, so that on the one hand can fuse the request to protect the entire system, on the other hand will not cause poor experience and the user mass loss situation.

If every request to go back to the background application and then to the database to retrieve data, which is too much pressure on the server, and sometimes this factor may even become a bottleneck affecting the performance of Web services. Therefore, most Web sites will put some data without real-time updates into the cache, the front-end request is to get data in the cache.

Hystrix provides protection convenience while also supporting the function of caching, in the following Hystrixcachedemo.java, we will demonstrate hystrix to read the data from the cache, the code is as follows.

1//omit the necessary package and import codes2 Public classHystrixcachedemoextendsHystrixcommand<string> {3//User ID4Integer ID;5//use a hashmap to simulate data in a database.6PrivateHashmap<integer,string> userlist =NewHashmap<integer,string>();7//constructor Function8 PublicHystrixcachedemo (Integer id) {9Super(HystrixCommandGroupKey.Factory.asKey ("Requestcachecommand")); 10 This. ID =ID;Userlist.put (1, "Tom"));12}

In line 3rd, we define a user ID and, on line 6th, define a hashmap that holds the user's information.

In the 8th row of the constructor, we use the parameter ID in line 10th to initialize the id attribute of this object, and in line 11th, the put method is simulated to build a user, in the project, the user's information is actually in the database.

        protected  String Run () {            System.out.println ("in Run");            return  userlist.get (ID); +        }

If the cache is not taken, line 13th defines that the run function will be triggered by the Execute method, and in the 15th row, we get a user data from the UserList HashMap by the Get method. Here we use the Get method to simulate many actions that retrieve data from the database based on the ID.

17protected String Getcachekey () {18return string.valueof (ID); 19}

The Getcachekey method defined in line 17th is the key to hystrix implementation of caching, where we can define "criteria for cached objects", specifically, we are here to return string.valueof (ID), i.e., If the second Hystrixcachedemo object and the first object have the same string.valueof (ID) value, then the second object can walk the cache when it calls the Execute method.

 Public Static voidMain (string[] args) {21st//Initialize the context, otherwise the caching mechanism cannot be usedHystrixrequestcontext context =Hystrixrequestcontext.initializecontext ();23//define two objects with the same IDHystrixcachedemo CacheDemo1 =NewHystrixcachedemo (1);Hystrixcachedemo CacheDemo2 =NewHystrixcachedemo (1);26//the first object calls the Run method and does not walk the cacheSYSTEM.OUT.PRINTLN ("The result for CacheDemo1 is:" +Cachedemo1.execute ());System.out.println ("Whether get from cache:" +Cachedemo1.isresponsefromcache);29//The second object, because it has the same ID as the first object, walks the cacheSYSTEM.OUT.PRINTLN ("The result for CacheDemo2 is:" +Cachedemo2.execute ());System.out.println ("Whether get from cache:" +Cachedemo2.isresponsefromcache);32//Ecstasy context to empty the cache33Context.shutdown ();34//the context is initialized again, but because the cache is clear, CacheDemo3 does not walk the cacheContext =Hystrixrequestcontext.initializecontext ();Hystrixcachedemo CacheDemo3 =NewHystrixcachedemo (1);PNS System.out.println ("The result for 3 is:" +Cachedemo3.execute ());System.out.println ("Whether get from cache:" +Cachedemo3.isresponsefromcache);Context.shutdown ();

In the main method of line 20th, we define the following main logic.

First, in line 22nd, the context is initialized with the Initializecontext method, so that the caching mechanism can be started. , in lines 24th and 25, we created two Hystrixcachedemo objects of different names, but with the same ID.

Second, in line 27th, we use the Execute method of the CacheDemo1 object to find the user based on the ID, although we are here to fetch the data from the HashMap by the Get method in line 15th of the Run method, but you can think of this as fetching data from the data table.

Third, in line 30th, we call the Execute method of the CacheDemo2 object, because it has the same ID as the CacheDemo1 object, so there is no Execute method. Instead, the data is taken directly from the cache that holds the Cachedemo1.execute, which avoids the loss of the system due to multiple accesses to the database.

We destroyed the context in line 33rd and re-initialized the context in line 35th, and then, although the ID of the CacheDemo3 object defined in line 36th was still 1, the cache was emptied because the context object was reset. So the Execute method executed in the 37th does not go through the cache.

Running the above code, we can see the following output, which can well verify the above description of the main process.

1 in    run2 for      cacheDemo1 is:tom3    whether get from cache:false4     for CacheDemo2 Is:tom5    Whether get from cache:true6 in    run7 for     3 Is:tom

It is important to note that in the cache-related Getcachekey method, we are not defining the logic of "Saving cached values", but rather defining "criteria for cached Objects", which beginners often confuse. Specifically, in the Getcachekey method here, we did not save the value of the user object with ID 1 (this is Tom), but instead defined the following criteria: As long as two (or more) Hystrixcachedemo objects have the same string.valueof (ID) value, and the 1 result value of the ID is already in the cache, then the successor can read the data directly from the cache.

In the previous section, we demonstrated the results of the operation of the Hystrix call and the unavailability of the service, and introduced a caching mechanism in the call process, where we will summarize the general workflow of Hystrix based on the above case.

First, we can make a class with hystrix protection mechanism by extends hystrixcommand<t>, where T is generic, and in the above case we use string.

Second, once the Hystrixcommand has been inherited, we can define the business function code that invokes the "available" and "unavailable" services by overriding the Run method and the Getfallback method, where the return value of the two methods needs to be consistent with the generic T defined in the first step. In the project, we generally define the "Service Unavailable" protection measures in the Getfallback method (that is, the downgrade measures that will be mentioned later in this article).

Thirdly, we can also use the caching mechanism to reduce the pressure on the server in concurrency, in hystrix, we can define the "criteria for judging which cache objects can go" in Getcachekey.

In using the cache is, note two points, the first need to open the context, second, Hystrix will be defined in the class by the property to determine whether the object is the same number of times, if it is, and was called before, you can go cache.

This article declines.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.