Chapter 2 springboot + hystrix (1), springboothystrix
Hystrix is a tool used in microservices for fusing and downgrading.
Purpose: prevent multiple requests from being blocked due to a service call failure or call delay and call failure of multiple requests.
1. pom. xml (introduce the hystrix-core package)
1 <! -- Hystrix --> 2 <dependency> 3 <groupId> com. netflix. hystrix </groupId> 4 <artifactId> hystrix-core </artifactId> 5 <version> 1.5.2 </version> 6 </dependency>View Code
2. application. properties
1 # hystrix2 hystrix. timeoutInMillions = 3000View Code
(Set hystrix properties, the above is the "service call timeout time", other attribute settings see: https://github.com/Netflix/Hystrix/wiki/Configuration)
3. HyStrixProperties
1 package com. xxx. firstboot. hystrix; 2 3 import org. springframework. boot. context. properties. configurationProperties; 4 import org. springframework. stereotype. component; 5 6 import lombok. getter; 7 import lombok. setter; 8 9 @ Getter @ Setter10 @ Component11 @ ConfigurationProperties (prefix = "hystrix") 12 public class HyStrixProperties {13 private int timeoutInMillions; 14}View Code
4. MyHyStrixCommand
1 package com. xxx. firstboot. hystrix; 2 3 import org. slf4j. logger; 4 import org. slf4j. loggerFactory; 5 6 import com. netflix. hystrix. hystrixCommand; 7 import com. squareup. okhttp. okHttpClient; 8 import com. squareup. okhttp. request; 9 import com. squareup. okhttp. response; 10 11 public class MyHystrixCommand extends HystrixCommand <Response> {12 private static final Logger LOGGER = LoggerFactory. getLogger (MyHystrixCommand. class); 13 private String url; 14 15 public MyHystrixCommand (Setter setter, String url) {16 super (setter); 17 this. url = url; 18} 19 20 @ Override21 protected Response run () throws Exception {22 LOGGER.info ("the service is being called, current Thread: '{}'", Thread. currentThread (). getName (); 23 Request request = new Request. builder (). url (url ). build (); 24 return new okhttpclient().newcall(requestcmd.exe cute (); 25} 26 27 @ Override28 public Response getFallback () {29 LOGGER. error ("service call failed, service: '{}'"); 30 return null; 31} 32}View Code
Note:
- This class is the most critical class.
- Inherit HystrixCommand <T>
- Add constructor. Note: The non-argument constructor cannot be added. Therefore, this class cannot be managed as a spring bean.
- Run () when the program starts. When an error or timeout occurs, run getFallback ()
5. HyStrixUtil
1 package com. xxx. firstboot. hystrix; 2 3 import java. util. concurrent. executionException; 4 import java. util. concurrent. future; 5 6 import org. springframework. beans. factory. annotation. autowired; 7 import org. springframework. stereotype. component; 8 9 import com. netflix. hystrix. hystrixCommand. setter; 10 import com. netflix. hystrix. hystrixCommandGroupKey; 11 import com. netflix. hystrix. hystrixCommandKey; 12 import com. netflix. hystrix. hystrixCommandProperties; 13 import com. squareup. okhttp. response; 14 15 @ Component16 public class HystrixUtil {17 18 @ Autowired19 private HyStrixProperties hp; 20 21 public Response execute (String Response servicename, 22 String Response servicemethodget1_info, 23 String url) throws InterruptedException, executionException {24 Setter setter = Setter. withGroupKey (HystrixCommandGroupKey. factory. asKey (custom servicename); // 25 setter of the called service. andCommandKey (HystrixCommandKey. factory. asKey (invoke servicemethodgethotelinfo); // a 26 setter of the called method of the service. andCommandPropertiesDefaults (HystrixCommandProperties. setter (). withExecutionTimeoutInMilliseconds (hp. getTimeoutInMillions (); 27 return new MyHystrixCommand (setter, url0000.exe cute (); // run 28 // Future <Response> future = new MyHystrixCommand (setter, url) synchronously ). queue (); // asynchronous execution 29 // return future. get (); // get 30} 31 32} if needed}View Code
Note:
- Hystrix execution Method
- Synchronous execution: the timeout time takes effect.
- Asynchronous execution: the timeout time does not work (for versions earlier than 1.4.0, the timer starts to work when get () is called)
- Isolation level of hystrix
- HystrixCommandGroupKey: this name is set to a called service, such as. zooservice. All methods under this service use the same thread pool (provided that ThreadPoolKey is not configured)
- HystrixCommandKey: this name is usually the name of a method in the called service (in fact, it is an external method in a controller of the called Service), eg. getdetailinfo ()
- ThreadPoolKey: This is rarely used. Unless some called methods in a called service are fast and some called methods are slow, A ThreadPoolKey must be used separately, separate thread pool allocation for each method
6. application. properties
1 service. hotel. name = movie service2 service. hotel. method. get1_info = get1_infoView Code
Description: defines the service name of the called service and the called method name. Of course, the service name can also use the simple Class Name of the controller of the called service.
7. HystrixController
1 package com. xxx. firstboot. web; 2 3 import java. io. IOException; 4 import java. util. concurrent. executionException; 5 6 import org. springframework. beans. factory. annotation. autowired; 7 import org. springframework. beans. factory. annotation. value; 8 import org. springframework. web. bind. annotation. requestMapping; 9 import org. springframework. web. bind. annotation. requestMethod; 10 import org. springframework. Web. bind. annotation. requestParam; 11 import org. springframework. web. bind. annotation. restController; 12 13 import com. squareup. okhttp. response; 14 import com. xxx. firstboot. hystrix. hystrixUtil; 15 16 @ RestController17 @ RequestMapping ("/hystrix") 18 public class HystrixController {19 20 @ Value ("$ {service. hotel. url} ") 21 private String pai_url; 22 23 @ Value (" $ {service. hotel. name} ") 24 private String sponse RviceName; 25 26 @ Value ("$ {service. hotel. method. getaskinfo} ") 27 private String response servicemethodgetaskinfo; 28 29 @ Autowired30 private HystrixUtil hystrixUtil; 31 32 @ RequestMapping (value ="/firstHystrix ", method = RequestMethod. GET) 33 public String getaskinfo (@ RequestParam ("id") int id, @ RequestParam ("name") String name) {34 String url = String. format (pai_url, id, name); 35 Response respons E = null; 36 try {37 response = hystrixUtil.exe cute (Region servicename, Region servicemethodget1_info, url); 38 if (response! = Null) {39 return response. body (). string (); 40} 41} catch (IOException e) {42 e. printStackTrace (); 43} catch (InterruptedException e) {44 e. printStackTrace (); 45} catch (ExecutionException e) {46 e. printStackTrace (); 47} finally {48 if (response! = Null & response. body ()! = Null) {49 try {50 response. body (). close (); // resource close 51} catch (IOException e) {52 e. printStackTrace (); 53} 54} 55} 56 return "failed to get hotel information"; 57} 58 59}View Code
Note:
- Use @ value for property injection. Assume that application is configured on consul. properties content. After modifying the content of the property file, the service must also be restarted because @ value is read-only once (not tested, as said by colleagues)
- Use spring's Environment for injection. After modifying the content of the attribute file, the Service does not need to be restarted and will be refreshed every five minutes (not tested, as my colleague said)
- Use boot to build a property collection class, such as the above HyStrixProperties class. I do not know whether to restart it (I have not tested it)
A friend of mine told me about the tests. I have time to test them.
The following is the code of the called service:
8. ingress Controller
1 @ RestController 2 @ RequestMapping ("/hotel") 3 @ Api ("container Controller related api") 4 public class container controller {5 @ ApiOperation ("Get Hotel information: getcontainer Info ") 6 @ RequestMapping (value = "/getaskinfo", method = RequestMethod. GET) 7 public Hotel getaskinfo (@ RequestParam ("id") int id, @ RequestParam ("name") String name) {8 // try {9 // TimeUnit. MILLISECONDS. sleep (2000); // used for testing timeout 10 //} catch (InterruptedException e) {11 // e. printStackTrace (); 12 //} 13 return new Hotel (id, name); 14} 15}View Code
Test: Start the called service --> Start the called Service
Refer:
Chinese Summary of http://blog.csdn.net/xiaoyu411502/article/details/50601687 official
Https://stonetingxin.gitbooks.io/hystrix/content/ is basically the official Chinese Translation
Introduction to https://github.com/Netflix/Hystrix/wiki/Configuration hystrix Configuration
Http://blog.vicoder.com/hystrix-configuration/ Configuration
Http://www.insaneprogramming.be/blog/2014/08/19/hystrix-spring-boot/ boot integrated hystrix