我们可以通过以下方式使用redisson客户端从redis缓存中获取所有现有的key..
1.在你的项目pom.xml中添加mvn依赖。
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.16.3</version>
</dependency>
现在创建 RedisConfig 类以使用 redisson 客户端创建与 redis 服务器的连接
public class RedisConfig{
private static final Logger logger = LoggerFactory.getLogger(RedisConfig.class);
@Autowired
CacheManager cacheManager;
@Value("${spring.redis.port}")
private String redisPort;
@Value("${spring.redis.host}")
private String redisHost;
@Value("${spring.redis.password}")
private String password;
@Bean
public RedissonClient getRedissonClient() {
Config config = new Config();
String address="redis://"+redisHost+":"+redisPort;
config.useSingleServer().setAddress(address)
.setPassword(password);
RedissonClient client = Redisson.create(config);
return client;
}
}
现在假设您要访问缓存的所有键(通过 CacheName)
然后创建另一个函数
public Iterator<String>getKeysByCacheName(String cacheName){
RedissonClient client = getRedissonClient();
RKeys keys = client.getKeys();
Iterator<String> allKeys = keys.getKeysByPattern(cacheName+"*").iterator();
return allKeys;
}
这里 * 是访问所有键。
现在使用下面的代码来获取所有具有该值的键。
Iterator<String> allKeys = redisConfig.getKeysByCacheName("CacheName");
while (allKeys.hasNext()) {
String key = allKeys.next().split("::")[1];
Student student = (Student ) cacheManager.getCache("CacheName").get(key).get();
if (student !=null)
System.out.println("Cached Student Object is "+student );
}
类似地设置/添加你可以使用的缓存
cacheManager.getCache("CacheName").put("Key",Student);