Moment For Technology

How to better use the Hystrix API

Posted on Sept. 23, 2022, 9:49 a.m. by Ryan Hodson
Category: The back-end Tag: Spring Cloud

I. Hystrix execution

1. Synchronize the execution

  1. Simply inheriting HystrixCommand, the execution logic is in the run method
  2. Synchronously executes the execute method that calls command directly
class HelloHystrixCommand extends HystrixCommandString { private String name; HelloHystrixCommand(String name) { super(HystrixCommandGroupKey.Factory.asKey("test")); this.name = name; } @Override protected String run() throws Exception { TimeUnit.MILLISECONDS.sleep(20); return "hello " + name; Long start = system.currentTimemillis (); System.out.println(start); System.out.println(new HelloHystrixCommand("world").execute()); System.out.println(System.currentTimeMillis() - start);Copy the code

2. Execute asynchronously

  1. Use Java futures to execute asynchronously
  2. Execute is the same as queue().get()
FutureString future = new HelloHystrixCommand("bob").queue(); try { System.out.println(future.get(20, TimeUnit.MILLISECONDS)); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } catch (TimeoutException e) {system.out.println (" Get timeout!" ); }Copy the code

Reactive

  1. Both of the above examples are executed by HystrixCommand
  2. HystrixCommand is a synchronous and asynchronous hystrix that encapsulates the Run method to get an Observable and then a future
  3. HystrixObserableCommand encapsulates an Observable with the Construct method, creates its own data source, and then calls Observe and toObservable to get the future. Easy to use Rxjava development users
// Encapsulate Observable, Class HelloObservableCommand extends HystrixObservableCommandString {private String Value; public HelloObservableCommand(String value) { super(HystrixCommandGroupKey.Factory.asKey("observable")); this.value = value; } @Override protected ObservableString construct() { return Observable.just(value); Construct Observable HelloObservableCommand observableCommand = new HelloObservableCommand("world"); // observableCommand.observe().subscribe(value - System.out.println("hello " + value)); observableCommand.toObservable().subscribe(value - System.out.println("hello " + value));Copy the code

Two, failure transfer

You can override the getFallback method in HystrixCommand to deal with errors in the execute and Queue methods

class FailbackHystrixCommand extends HystrixCommandString { private String name; FailbackHystrixCommand(String name) { super(HystrixCommandGroupKey.Factory.asKey("test")); this.name = name; } @Override protected String run() throws Exception { throw new RuntimeException("run exception"); } @Override protected String getFallback() { return "run execute exception!" ; } } @Test public void fallback() { FailbackHystrixCommand fail = new FailbackHystrixCommand("fail"); System.out.println(fail.execute()); }Copy the code

Command group thread pool name

  1. The command group name must be specified. It is only a logical concept. It is used to classify multiple commands of the same type, for example, the commands of a service into the same category
  2. Through HystrixCommandGroupKey. Factory. AsKey specified command group (" test ")
  3. The command name can not be specified. The default is the class name, or you can specify it yourself
  4. Through HystrixCommandKey. Factory. AsKey (" testKey ") specifies the command name
  5. The thread pool name is used when commands belong to the same group but to different cells, which is similar to the subdivision category of the group
  6. Through HystrixThreadPoolKey. Factory. AsKey (" HelloWorldPool ") sets the thread pool key name
class HelloHystrixCommand extends HystrixCommandString { private String name; HelloHystrixCommand(String name) { super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("test")) .andCommandKey(HystrixCommandKey.Factory.asKey("testKey")) .andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey("testThreadKey"))); this.name = name; } @Override protected String run() throws Exception { TimeUnit.MILLISECONDS.sleep(20); return "hello " + name; }}Copy the code

Request caching

  1. The so-called request cache can customize the cache matching policy, so that the cache logic is followed by the key matching the cache policy, instead of calling the run method to execute
  2. We can customize the cache hit policy in the getCacheKey method
  3. The cache will only be hit if it is in the same context, the cache will not be hit until it is across the context
  4. For example, if the cache hit logic is that the parameters of the request are consistent, then subsequent parameters of the same request will be cached
class HystrixCommandWithCache extends HystrixCommandString { private String data; HystrixCommandWithCache(String data) { super(HystrixCommandGroupKey.Factory.asKey("cache")); this.data = data; } @Override protected String run() throws Exception { return "run " + data; } @override protected String getCacheKey() {return data;} @override protected String getCacheKey() {return data; } } public void commandWithCache() { HystrixRequestContext context = HystrixRequestContext.initializeContext(); HystrixCommandWithCache man = new HystrixCommandWithCache("man"); HystrixCommandWithCache other = new HystrixCommandWithCache("other"); HystrixCommandWithCache man1 = new HystrixCommandWithCache("man"); System.out.println(man.execute()); Println (man.isresponseFromcache ()); // Return false system.out.println (man.isresponseFromcache ()); System.out.println(other.execute()); / / data parameters, return false System. Out. The println (other) isResponseFromCache ()); System.out.println(man1.execute()); // man returns true system.out.println (man1.isresponseFromcache ()); context.shutdown(); HystrixRequestContext context1 = HystrixRequestContext.initializeContext(); HystrixCommandWithCache man2 = new HystrixCommandWithCache("man"); System.out.println(man2.execute()); System.out.println(man2.isresponseFromcache ())); context1.shutdown(); }Copy the code

Five, the Request of Collapsing

Six, HystrixRequestContext

  1. If you want to use request-level features, you must use the HystrixRequestContext

1. Creation method

HystrixRequestContext context = HystrixRequestContext.initializeContext();
Copy the code

2. Web applications use HystrixRequestContext

Each request opens a HystrixRequestContext

public class HystrixRequestContextServletFilter implements Filter { public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HystrixRequestContext context = HystrixRequestContext.initializeContext(); try { chain.doFilter(request, response); } finally { context.shutdown(); }}} // Add web.xml, Gives effect to filter the  filter   display - name  HystrixRequestContextServletFilter  / display - name  filter-nameHystrixRequestContextServletFilter/filter-name filter-classcom.netflix.hystrix.contrib.requestservlet.HystrixRequestContextServletFilter/filter-class /filter filter-mapping filter-nameHystrixRequestContextServletFilter/filter-name url-pattern/*/url-pattern /filter-mappingCopy the code

Appendix:

Reference github.com/Netflix/Hys...

Search
About
mo4tech.com (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.