I want to fetch existing key value pair from redis using redisson. The issue is that I did not enter that key value pair through redisson, and I am not able to find any function from documentation to fetch existing key and value present as a string.
Asked
Active
Viewed 2,097 times
1 Answers
1
We can get all existing key from redis cache by using redisson client in the following way..
1.Add mvn dependency in your project pom.xml.
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.16.3</version>
</dependency>
Now create RedisConfig class to create connection with redis server by using redisson client
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;
}
}
Now suppose you want to access all the keys of your cache(By CacheName) then create another function
public Iterator<String>getKeysByCacheName(String cacheName){
RedissonClient client = getRedissonClient();
RKeys keys = client.getKeys();
Iterator<String> allKeys = keys.getKeysByPattern(cacheName+"*").iterator();
return allKeys;
}
Here * is access all the keys. Now use the below code to get all keys with there values.
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 );
}
Similarly to set/add cache you can use
cacheManager.getCache("CacheName").put("Key",Student);

Manoj Kumar Mali
- 46
- 4