【问题标题】:How to store List or Set for a Redis key in Spring Boot?如何在 Spring Boot 中为 Redis 键存储 List 或 Set?
【发布时间】:2021-11-02 19:38:13
【问题描述】:

我想将用户的 id 存储在 Redis 的 USERS 键中。如果列表为空或 null,则在该键中添加一个带有 id 的新列表。 如果 key 包含一个已经存在的列表,那么应该将一个新的 id 添加到该列表中。 我在下面给出的代码中使用逗号分隔的字符串实现了这种方法:

private synchronized void pushIdInRedis(String id) {
    String Ids = (String) redisClient.getValue("USERS");
    if(StringUtils.isEmpty(Ids)){
        redisClient.setValue("USERS",id);
    } else {
        Ids = Ids+","+id;
        redisClient.setValue("USERS",Ids);
    }
}

我们可以使用列表来实现吗?它也应该是线程安全的。

【问题讨论】:

  • 这种逗号分隔值 ids 方法有什么具体原因吗? Redis 提供了一些更适合它的数据类型。例如lists

标签: java spring spring-boot redis jedis


【解决方案1】:

也许你应该看看RedisTemplate 文档。在那里你会找到方法opsForList(),它会返回一个ListOperations。有了它,你可以编辑给定的 Redis 列表。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-08
    • 1970-01-01
    • 2020-02-16
    • 2022-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-16
    相关资源
    最近更新 更多