项目中使用了redis缓存,但在修改了数据库时,redis中的数据无法实时更新,这就需要删除掉redis库中的key,重新加载缓存。
具体实现如下:
1、新建实现类并继承CommandLineRunner接口;
2、定义redis的key值前缀;
3、用redisTemplate获取redis连接;
4、调用RedisKeyCommands接口中的del方法,根据key值前缀删除redis库中对应的key;
下面是代码实现:
a、删除单个key值代码:
package com.platinum.redis.runner;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
@Component
public class CacheUpdateRunner implements CommandLineRunner {
@SuppressWarnings("rawtypes")
@Autowired
private RedisTemplate redisTemplate;
private static final String CACHE_KEY_PREFIX = "age" ;
@Override
public void run(String... args) throws Exception {
String pattern = CACHE_KEY_PREFIX + "*" ;
RedisConnection connection = redisTemplate
.getConnectionFactory().getConnection();
Set<byte[]> caches = connection.keys(pattern.getBytes());
if(!caches.isEmpty()){
connection.del(caches.toArray(new byte[][]{}));
}
}
b、删除多个指定key的代码:
package com.dbs.backtesting.runner;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
@Component
public class CacheUpdateRunner implements CommandLineRunner {
@SuppressWarnings("rawtypes")
@Autowired
private RedisTemplate redisTemplate;
private static final String CACHE_KEY_PREFIX_ECO = "economicindicator*" ;
private static final String CACHE_KEY_PREFIX_GET_ECO = "getEco*" ;
@Override
public void run(String... args) throws Exception {
List<String> list = new ArrayList<String>();
list.add(CACHE_KEY_PREFIX_ECO);
list.add(CACHE_KEY_PREFIX_GET_ECO);
RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
for(String patterns : list) {
Set<byte[]> caches = connection.keys(patterns.getBytes());
if(!caches.isEmpty()){
connection.del(caches.toArray(new byte[][]{}));
}
}
}
}
注意:需要在类中添加@Component注解。
本文介绍了一种在Spring Boot应用中使用Redis作为缓存时,如何实现实时更新缓存的方法。通过创建实现CommandLineRunner接口的类,定义缓存key前缀,并利用RedisTemplate和RedisKeyCommands接口的del方法,可以有效地删除指定前缀的key,从而在数据库更新时同步刷新Redis缓存。
234

被折叠的 条评论
为什么被折叠?



