Spring boot 使用 Redis 缓存

添加依赖:

spring-boot-starter-cache

spring-boot-starter-data-redis

启用缓存:

@EnableCaching

配置 Redis:(非必须)

spring.redis.host=localhost

...

更多配置项查看文档

配置 Cache:

主要通过 JavaConfig 可配置 RedisTemplate 与 cacheManager

Key 序列化策略:

@Autowired
private RedisTemplate redisTemplate;

@Bean
public RedisTemplate customizeRedisTemplate() {
	redisTemplate.setKeySerializer(new StringRedisSerializer());
	return redisTemplate;
}
配置 cacheManager 全局参数:

@Bean
public RedisCacheManager cacheManager(RedisKeyDefine redisKeyDefine) {
	RedisCacheManager cacheManager = new RedisCacheManager(customizeRedisTemplate());
	cacheManager.setUsePrefix(true);
	cacheManager.setDefaultExpiration(1800);
	cacheManager.setCacheNames(redisKeyDefine.getExpiresMap().keySet());
	cacheManager.setExpires(redisKeyDefine.getExpiresMap());
	return cacheManager;
}
RedisKeyDefine:(该类作用类似 ehcache.xml)

@Component
public class RedisKeyDefine {

	// 定义缓存名
	public static final String CACHENAME_HELLO = "CACHE_HELLO";

	private Map<String, Long> expiresMap;

	@PostConstruct
	public void init() {
		expiresMap = new HashMap<String, Long>();
		expiresMap.put(CACHENAME_CATEGORY, 0L);
	}

	public Map<String, Long> getExpiresMap() {
		return expiresMap;
	}

}

使用缓存:

使用 @Cacheable 等注解需要缓存的方法,相关文档

默认情况 value 的值将作为 key 的前缀 ,可通过 cacheManager.setUsePrefix 方法修改

这里与 ehcache 的 cache 与 element 机制有所区别

缓存管理:

使用 RedisTemplate 来操作获取与删除 Key 

如果数据量过大,不建议在应用中获取与操作 key ,有可能造成一次性加载过多 key 且不能分页

建议使用 Redis 客户端 redis-cli 或 图形客户端 https://redisdesktop.com 等进行管理

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值