笔记:Spring Cloud Hystrix 异常处理、缓存和请求合并

时间:2023-03-09 01:15:47
笔记:Spring Cloud Hystrix 异常处理、缓存和请求合并

异常处理


HystrixCommand
实现的run方法中抛出异常,除了
HystrixBadRequestException之外,其他异常均会被Hystrix
认为命令执行失败并触发服务降级处理逻辑,所以当需要在命令中执行抛出不触发降级的异常时使用他,在使用注解配置实现
Hystrix
命令时,支持忽略指定异常类型功能,只需要通过设置 @HystrixCommand
注册的
ignoreException
参数,示例代码如下:

@HystrixCommand (ignoreExceptions = {IllegalStateException.class})

如果抛出了类型为
IllegalStateException
的异常,Hystrix
会将其包装为
HystrixBadRequestException
抛出,这样就不会触发后续的
fallback
逻辑。

如果需要在降级逻辑中获取触发的异常,我们可以通过
getExecutionException
方法来获取具体的异常,如果使用注解的方式,则需要在fallback实现的方法的参数中增加
Throwable
e
对象的定义,这样就可以在方法内部获取触发服务降级的具体异常内容,示例代码如下:

@HystrixCommand (ignoreExceptions = {IllegalStateException.class},fallbackMethod="helloFallback")

@GET

@Path ("get")

public String get(@QueryParam ("id") int id, @QueryParam ("name") String name) {

throw new
RuntimeException("get command failed.");

}

public String helloFallback(int id, String name, Throwable e) {

return
"error id=" + id + "\tname=" + name + "\tthrowable=" + e.getMessage();

}

请求缓存

当系统用户不断增长时,每个微服务需要承受的并发压力也越来越大,在分布式环境中,通常压力来自对依赖服务的调用,因为亲戚依赖服务的资源需要通过通信来实现,这样的依赖方式比起进程内的调用方式会引起一部分的性能损失,在高并发的场景下,Hystrix
提供了请求缓存的功能,我们可以方便的开启和使用请求缓存来优化系统,达到减轻高并发时的请求线程消耗、降低请求响应时间的效果

开启请求缓存功能

Spring Cloud Hystrix
请求缓存的使用非常简单,我们只需要在实现
HystrixCommand

HystrixObservableCommand
时,通过重载
getCacheKey()方法来开启请求缓存。

public class HelloGetCommand extends HystrixCommand<String> {

private RestTemplate restTemplate;

public
HelloGetCommand(Setter setter, RestTemplate restTemplate) {

super(setter);

this.restTemplate= restTemplate;

}

@Override

protected String run() throws Exception {

ResponseEntity<String> responseEntity=

restTemplate(getForEntity("http://ORG.DRSOFT.WEBSERVICE.HELLOSERVICE/hello/get", String.class);

return responseEntity.getBody();

}

@Override

protected String getFallback() {

return
"error id=" + id + "\tname=" + name;

}

@Override

protected String getCacheKey() {

return"get";

}

}

调用时候还需要在当前线程执行 HystrixRequestContext.initializeContext() 并且在结束时候需要进行释放,而且在Hystrix中带缓存的command是必须在request中调用的,示例代码如下:

HystrixRequestContext context = HystrixRequestContext.initializeContext();

try {

HystrixCommand<String> hystrixCommand = new
HelloGetCommand(setter, restTemplate);

return hystrixCommand.execute();

} finally {

context.shutdown();

}

清理失效缓存

在请求缓存时,如果只是读操作,那么不需要考虑缓存内容是否正确的问题,但是如果请求命令中还有更新数据的写操作,那么缓存中的数据就需要我们在进行写操作时及时处理,以防止读操作的请求命令获取到失效的数据,我们可以使用
HystrixRequestCache.clear
方法来进行缓存清理,示例代码如下:

/**

* 清除缓存

*/

public
void
flushCache() {

HystrixRequestCache.getInstance(this.getCommandKey()

, HystrixConcurrencyStrategyDefault.getInstance()).clear("get");

}