【问题标题】:Retrieve existing key-value pair present in Redis using Redisson使用 Redisson 检索 Redis 中存在的现有键值对
【发布时间】:2022-04-01 00:13:14
【问题描述】:

我想使用 redisson 从 redis 获取现有的键值对。问题是我没有通过 redisson 输入该键值对,并且我无法从文档中找到任何函数来获取作为字符串存在的现有键和值。

【问题讨论】:

  • RedissonKeys.countExists(String... name) 可以帮助您确定密钥是否存在,而无需事先知道它的类型。

标签: java spring spring-boot redis redisson


【解决方案1】:

我们可以通过以下方式使用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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-20
    • 2021-09-26
    • 2011-04-17
    • 2018-04-04
    • 1970-01-01
    • 1970-01-01
    • 2018-05-31
    • 1970-01-01
    相关资源
    最近更新 更多