SpringCache+Redis缓存技术
依赖
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> <exclusions> <exclusion> <groupId>io.lettuce</groupId> <artifactId>lettuce-core</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> </dependency>
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency>
|
配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| spring: cache: type: redis redis: time-to-live: 10000 key-prefix: CACHE_ use-key-prefix: true cache-null-values: true redis: host: 127.0.0.1 port: 6379 password: 123456
|
开启缓存
原理
- CacheAutoConfiguration
- -> RedisCacheConfiguration
- -> 自动配置了RedisCacheMapper
- -> 初始化所有的缓存
- -> 每个缓存决定使用什么配置
- -> 如果RedisCacheConfiguration有就用已有的,没有就用默认配置
- -> 想改缓存的配置,只需要给容器中放一个RedisCacheConfiguration即可
- -> 就会应用到当前RedisCacheConfiguration管理的所有缓存分区中
注解
@Cacheable
触发将数据保存到缓存中的操作
- value:指定缓存分区
- key:指定缓存的键名称,支持spel表达式,**spel使用教程**
- sync:是否加锁,防止缓存击穿
1
| @Cacheable(value = {"test"},key = "'sada'", sync = true)
|
@CacheEvict
触发将数据从缓存中删除的操作
- value:指定缓存分区
- key:指定缓存的键名称,支持spel表达式
- allEntries:是否删除缓存分区中所有数据
1
| @CacheEvict(value="test",key="'ttt'",allEntries=true)
|
@CachePut
不影响方法执行更新缓存
@Caching
组合以上多个操作
@CacheConfig
在类级别共享缓存的相同配置
自定义RedisCacheConfiguration配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| @Configuration public class MyRedisCacheConfig {
@Bean RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties) { RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig(); config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())); config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new FastJsonRedisSerializer<>(Object.class))); CacheProperties.Redis redisProperties = cacheProperties.getRedis(); if (redisProperties.getTimeToLive() != null) { config = config.entryTtl(redisProperties.getTimeToLive()); } if (redisProperties.getKeyPrefix() != null) { config = config.prefixCacheNameWith(redisProperties.getKeyPrefix()); }
if (!redisProperties.isCacheNullValues()) { config = config.disableCachingNullValues(); } if (!redisProperties.isUseKeyPrefix()) { config = config.disableKeyPrefix(); } return config; } }
|
相关文章
数据库连接池
SpringIOC
Junit和Spring
Tomcat
Servlet
Request,Response和ServletContext
Cookie和Session
JSP和EL和Jstl
Filter和Listener
Mybatis