点击下载教程项目代码:
netflix_hystrix_demo.zip
@CacheResult 是 Hystrix 提供的一个用于缓存方法返回结果的注解。
在分布式系统中,一些方法的执行可能涉及到复杂的业务逻辑、网络请求或数据库查询等操作,这些操作往往比较耗时。通过使用 @CacheResult 注解,可以将方法的返回结果缓存起来,下次再调用相同参数的该方法时,直接从缓存中获取结果,无需再次执行方法体中的逻辑,从而显著提高系统的响应速度和性能。
由于缓存的存在,减少了对底层资源(如数据库、外部服务等)的重复请求,降低了服务的负载,有助于提高系统的稳定性和可扩展性,特别是在高并发场景下,能够更好地应对大量请求,避免服务因过载而出现性能问题。
@CacheResult 注解源码如下:
package com.netflix.hystrix.contrib.javanica.cache.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Marks a methods that results should be cached for a Hystrix command.
* 标记应缓存 Hystrix 命令结果的方法。
* This annotation must be used in conjunction with {@link com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand} annotation.
* 此注解必须与{@link com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand}注解一起使用。
* @author dmgcodevil
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CacheResult {
/**
* Method name to be used to get a key for request caching.
* 用于获取请求缓存键的方法名称。
* The command and cache key method should be placed in the same class and have same method signature except
* cache key method return type, that should be <code>String</code>.
* 命令和缓存键方法应放在同一个类中,并具有相同的方法签名,
* 但缓存键方法的返回类型应为字符串。
* <p/>
* cacheKeyMethod has higher priority than an arguments of a method, that means what actual arguments
* of a method that annotated with {@link CacheResult} will not be used to generate cache key, instead specified
* cacheKeyMethod fully assigns to itself responsibility for cache key generation.
* By default this returns empty string which means "do not use cache method".
* cacheKeyMethod 的优先级高于方法的参数,这意味着注释为 @CacheResult 的方法的实际参数
* 将不会被用于生成缓存密钥,相反,指定的 cacheKeyMethod 将全权负责生成缓存密钥。
* 默认情况下,它返回空字符串,表示 “不使用缓存方法”。
* @return method name or empty string
*/
String cacheKeyMethod() default "";
}@CacheResult 注解常用属性如下:
该属性是必须指定的,用于指定一个方法,该方法将根据被注解方法的参数生成缓存键。生成的缓存键必须是唯一的,以便准确地缓存和检索结果。
@CacheResult 注解通常直接标注在需要缓存结果的方法上,并且一般会与 @HystrixCommand 注解一起配合使用。例如:
@Service
public class MyService {
@CacheResult(cacheKeyMethod = "generateCacheKey")
@HystrixCommand
public String getData(String key) {
// 模拟从数据库或其他数据源获取数据的操作
System.out.println("执行getData方法,key: " + key);
return "Data for " + key;
}
private String generateCacheKey(String key) {
return "myCacheKey:" + key;
}
}在上述示例中,getData 方法被标注了 @CacheResult 注解,并且通过 cacheKeyMethod 属性指定了一个用于生成缓存键的方法 generateCacheKey。当第一次调用 getData("key1") 时,会执行 getData 方法体中的逻辑,并将结果缓存起来,缓存键由 generateCacheKey("key1") 生成,即 myCacheKey:key1。之后再次调用 getData("key1") 时,Hystrix 会直接从缓存中获取结果,而不会再次执行 getData 方法体中的代码。