使用Redisson检索Redis中存在的现有键值对



我想使用redisson从redis获取现有的键值对。问题是我没有通过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);

最新更新