Hystrix service fault tolerance processing: what is hystrix

	return this.name + ":" + Thread.currentThread() . getName();
	@Override
	protected String getFallback() {
	return"failed";
}

}

After re executing the calling code, you can find that the returned content is "failed", which proves that fallback has been triggered.

# 3, Semaphore policy configuration
 The semaphore policy configuration method is shown in the following code:

```java
public MyHystrixCommand(String name) {
	super ( HystrixCommand . Setter
		.Wi thGroupKey(Hystr ixCommandGroupKey .Factory .asKey( "MyGroup"))
		. andCommandPropertiesDefaults (
			Hystr ixCommandProperties . Setter( )
			. withExecut ionIsolationStrategy(
				Hystr ixCommandProperties
				. ExecutionIsolat ionStrategy . SEMAPHORE
			)
		)
	);
	this.name = name;
}

Previously, the thread name was deliberately output in the run method. Through this name, you can determine whether the current thread isolation or semaphore isolation is.

4, Thread isolation policy configuration

The system adopts thread isolation policy by default. We can configure some parameters of thread pool through andThreadPoolPropertiesDefaults, as shown in the following code:

public MyHystrixCommand(String name) {
	super(HystrixCommand.Setter.withGroupKey (
		HystrixCommandGroupKey.Factory .asKey( "MyGroup"))
		.andCommandPropertiesDefaults (
			HystrixCommandProperties.Setter()
				.withExecutionIsolationStrategy (
					HystrixCommandProperties.ExecutionIsolationStrategy.THREAD
				)
		) . andThreadPoolPropertiesDefaults (
		HystrixThreadPoolProperties. Setter()
			. withCoreSize(10 )
			. withMaxQueueSize(100)
			.withMax. imumSize(100)
		)
	);
	this.name = name ;
}

5, Result cache

Cache is often used in development. We often use Redis, a third-party cache database, to cache data. Method level caching is also provided in Hystrix. Determine whether to return cached data by rewriting getCacheKey. getCacheKey can be generated according to parameters, so that the same parameters can be used for caching.

The MyHystrixCommand before the transformation adds the rewriting implementation of getCacheKey, as shown in the following code:

@verride
protected String getCacheKey() {
	return String.valueOf(this.name);
}

In the above code, the name parameter passed in when we create the object is used as the cached key.

In order to prove that the cache can be used, add a line of output in the run method. If the console outputs only once after multiple calls, you can know that the following is the cache logic, as shown in the following code:

@override
protected String run() {
	System.err.print1n("get data");
	return this.name + ":" + Thread. currentThread().getName();
}

Execute the main method and find an error:

According to the error prompt, the cache processing depends on the request context. We must initialize the hystrix requestcontext.

Modify the calling code in the main method and initialize the HystrixRequestContext, as shown in the following code:

public static void main(String[] args)throws InterruptedException, ExecutionException {
	HystrixRequestContext context = HystrixRequestContext. initializeContext();
	String result = new MyHystrixCommand("yinjihuan").execute();
	System.out.println(result);
	Future<string>future = new MyHystrixCommand("yinjihuan") .queue();
	System.out.println(future.get());
	context . shutdown() ;
}

After the transformation, rewrite and execute the main method, and it can run normally. The output results are as follows

You can see that get data is output only once and the cache takes effect.

6, Cache clear

In the previous section, we learned how to use Hystrix to implement data caching. If there is a cache, there must be an action to clear the cache. When the data changes, the data in the cache must also be updated, otherwise the problem of dirty data will occur. Similarly, Hystrix also has the function of clearing the cache.

Add a class that supports cache cleanup, as shown in the following code:

public class ClearCacheHystrixCommand extends HystrixCommand<String> {
	private final String name ;
	private static final HystrixCommandKey GETTER_ KEY =
	HystrixCommandKey.Factory . asKey("MyKey");
	public ClearCacheHystrixCommand (String name) {
		super ( HystrixCommand . Setter .withGroupKey ( HystrixCommandGroupKey .
			Factory .asKey( "MyGroup" )) . andCommandKey (GETTER_ KEY )
		);
		this.name = name;
	}
	public static void fushCache(String name) {
		HystrixRequestCache.getInstance ( GETTER_ KEY ,HystrixConcurrencyStrategyDefault. getInstance()). clear (name);
	}
	
	@Override
	protected String getCacheKey() {
		return String.valueOf(this.name);
	}
	
	@Override
	protected String run() {
		System.err.println("get data");
		return this.name + ":" + Thread.currentThread(). getName();
	}
	@Override
	protected String getFallback() {
		return "failed";
	}
}

The flushCache method is a method to clear the cache. It is cleared through the HystrixRequestCache and according to the key returned by getCacheKey.

Modify the calling code to verify whether the clearing is effective, as shown in the following code:

HystrixRequestContext context = HystrixRequestContext.initializeContext(); 
String result = new ClearCacheHystrixCommand("yinjihuan"). execute();
System.out.println(result);
ClearCacheHystrixCommand.flushCache("yinjihuan");
Future<string> future = new ClearCacheHystrixCommand("yinjihuan").queue();
System.out.println( future.get());

The same key is executed two times before calling the cache clearing method before the second execution. That is to say, the second time is not cached, and the output results are as follows:

As can be seen from the above, get data is output twice, which proves that the cache has indeed been cleared. You can comment out the clearcache hystrixcommandflushcache line and execute it again. You will find that only get data is output once, and the cache is valid. The input results are as follows:

get data
yinjihuan:hystrix-MyGroup-1 
yinjihuan:hystrix-MyGroup-1

7, Merge request

Hystrix supports the automatic merging of multiple requests into one request (see the code below). Using this function can save network overhead. For example, each request must access remote resources through the network. If multiple requests are combined into one and executed together, it will greatly save overhead by turning multiple network interactions into one.

public class MyHystrixCollapser extends HystrixCollapser<List<String>,String, String>{
	private final String name;
	public MyHystrixCollapser(String name) {
		this.name = name;
	}
	
	@Override
	public String getRequestArgument() {
		return name;
	}

	@Override
	protected HystrixCommand<List<String>>createCommand( final Collection<CollapsedRequest<String,String>> requests){
tRequestArgument() {
		return name;
	}

	@Override
	protected HystrixCommand<List<String>>createCommand( final Collection<CollapsedRequest<String,String>> requests){

Keywords: Java Back-end Interview Programmer

Added by Neville1985 on Sun, 26 Dec 2021 10:24:51 +0200