Redis windows 安装
完整依赖详见 ==> Gitee
<!-- 使用spring cache --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <!-- redis --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <!-- 为了解决 ClassNotFoundException: org.apache.commons.pool2.impl.GenericObjectPoolConfig --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> <version>2.0</version> </dependency>标记注解 @EnableCaching,开启缓存,并配置Redis缓存管理器,需要初始化一个缓存空间。在缓存的时候,也需要标记使用哪一个缓存空间
@Configuration @EnableCaching public class RedisConfig { @Value("${cache.default.expire-time}") private int defaultExpireTime; @Value("${cache.user.expire-time}") private int userCacheExpireTime; @Value("${cache.user.name}") private String userCacheName; /** * 缓存管理器 * * @param lettuceConnectionFactory * @return */ @Bean public CacheManager cacheManager(RedisConnectionFactory lettuceConnectionFactory) { RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig(); // 设置缓存管理器管理的缓存的默认过期时间 defaultCacheConfig = defaultCacheConfig.entryTtl(Duration.ofSeconds(defaultExpireTime)) // 设置 key为string序列化 .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())) // 设置value为json序列化 .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer())) // 不缓存空值 .disableCachingNullValues(); Set<String> cacheNames = new HashSet<>(); cacheNames.add(userCacheName); // 对每个缓存空间应用不同的配置 Map<String, RedisCacheConfiguration> configMap = new HashMap<>(); configMap.put(userCacheName, defaultCacheConfig.entryTtl(Duration.ofSeconds(userCacheExpireTime))); RedisCacheManager cacheManager = RedisCacheManager.builder(lettuceConnectionFactory) .cacheDefaults(defaultCacheConfig) .initialCacheNames(cacheNames) .withInitialCacheConfigurations(configMap) .build(); return cacheManager; } }到此配置工作已经结束了
下面详细讲一下每个注解的作用和可选项。
@EnableCaching 注释触发后置处理器, 检查每一个Spring bean 的 public 方法是否存在缓存注解。如果找到这样的一个注释, 自动创建一个代理拦截方法调用和处理相应的缓存行为。
将方法的结果缓存,必须要指定一个 cacheName(缓存空间)
@Cacheable("books") public Book findBook(ISBN isbn) {...}默认 cache key
缓存的本质还是以 key-value 的形式存储的,默认情况下我们不指定key的时候 ,使用 SimpleKeyGenerator 作为key的生成策略
如果没有给出参数,则返回SimpleKey.EMPTY。如果只给出一个Param,则返回该实例。如果给出了更多的Param,则返回包含所有参数的SimpleKey。注意:当使用默认策略时,我们的参数需要有 有效的hashCode()和equals()方法
自定义 cache key
@Cacheable(cacheNames="books", key="#isbn") public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed) @Cacheable(cacheNames="books", key="#isbn.rawNumber") public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed) @Cacheable(cacheNames="books", key="T(someType).hash(#isbn)") public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed)如上,配合Spring EL 使用,下文会详细介绍 Spring EL 对 Cache 的支持
指定对象指定对象中的属性某个类的某个静态方法自定义 keyGenerator
@Cacheable(cacheNames="books", keyGenerator="myKeyGenerator") public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed)实现 KeyGenerator接口可以自定义 cache key 的生成策略
自定义 cacheManager
@Cacheable(cacheNames="books", cacheManager="anotherCacheManager") public Book findBook(ISBN isbn) {...}当我们的项目包含多个缓存管理器时,可以指定具体的缓存管理器,作为缓存解析
同步缓存
在多线程环境中,可能会出现相同的参数的请求并发调用方法的操作,默认情况下,spring cache 不会锁定任何东西,相同的值可能会被计算几次,这就违背了缓存的目的
对于这些特殊情况,可以使用sync属性。此时只有一个线程在处于计算,而其他线程则被阻塞,直到在缓存中更新条目为止。
@Cacheable(cacheNames="foos", sync=true) public Foo executeExpensiveOperation(String id) {...}条件缓存
condition: 什么情况缓存,condition = true 时缓存,反之不缓存unless: 什么情况不缓存,unless = true 时不缓存,反之缓存 @Cacheable(cacheNames="book", condition="#name.length() < 32") public Book findBook(String name) @Cacheable(cacheNames="book", condition="#name.length() < 32", unless="#result?.hardback") public Optional<Book> findBook(String name)Spring EL 对 Cache 的支持
NameLocationDescriptionExamplemethodNameRoot object被调用的方法的名称#root.methodNamemethodRoot object被调用的方法#root.method.nametargetRoot object当前调用方法的对象#root.targettargetClassRoot object当前调用方法的类#root.targetClassargsRoot object当前方法的参数#root.args[0]cachesRoot object当前方法的缓存集合#root.caches[0].nameArgument nameEvaluation context当前方法的参数名称#iban or #a0 (you can also use #p0 or #p<#arg> notation as an alias).resultEvaluation context方法返回的结果(要缓存的值)。只有在 unless 、@CachePut(用于计算键)或@CacheEvict(beforeInvocation=false)中才可用.对于支持的包装器(例如Optional),#result引用的是实际对象,而不是包装器#result这个注解和 @Cacheable 有点类似,都会将结果缓存,但是标记 @CachePut 的方法每次都会执行,目的在于更新缓存,所以两个注解的使用场景完全不同。@Cacheable 支持的所有配置选项,同样适用于@CachePut
@CachePut(cacheNames="book", key="#isbn") public Book updateBook(ISBN isbn, BookDescriptor descriptor) 需要注意的是,不要在一个方法上同时使用@Cacheable 和 @CachePut用于移除缓存
可以移除指定key声明 allEntries=true移除该CacheName下所有缓存声明beforeInvocation=true 在方法执行之前清除缓存,无论方法执行是否成功 @CacheEvict(cacheNames="book", key="#isbn") public Book updateBook(ISBN isbn, BookDescriptor descriptor) @CacheEvict(cacheNames="books", allEntries=true) public void loadBooks(InputStream batch)可以让你在一个方法上嵌套多个相同的Cache 注解(@Cacheable, @CachePut, @CacheEvict),分别指定不同的条件
@Caching(evict = { @CacheEvict("primary"), @CacheEvict(cacheNames="secondary", key="#p0") }) public Book importBooks(String deposit, Date date)类级别注解,用于配置一些共同的选项(当方法注解声明的时候会被覆盖),例如 CacheName。
支持的选项如下:
@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface CacheConfig { String[] cacheNames() default {}; String keyGenerator() default ""; String cacheManager() default ""; String cacheResolver() default ""; }参考:
https://docs.spring.io/spring/docs/current/spring-framework-reference/integration.html#cache-annotations-cacheablehttps://spring.io/guides/gs/caching/本文demo:
https://gitee.com/yintianwen7/taven-springboot-learning/tree/master/springboot-redis
