使用 Spring Boot 和 Redis 查询所有 'account_positions' 数据

假设你有一个 Redis key 格式为 'account_positions:41',现在想直接查询所有 'account_positions' 数据。

你可以使用 Redis 的 KEYS 命令来获取所有以 'account_positions:' 开头的键,然后再使用 MGET 命令来获取这些键对应的所有值。

以下是一个使用 Spring Boot 和 RedisTemplate 的示例代码:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;

@Component
public class RedisExample {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public List<String> getAllAccountPositions() {
        Set<String> keys = redisTemplate.keys("account_positions:*");
        List<String> values = redisTemplate.opsForValue().multiGet(keys);
        return values;
    }
}

在这个示例中,我们使用 redisTemplate.keys("account_positions:*") 来获取所有以 'account_positions:' 开头的键,并将结果存储在 keys 集合中。然后,我们使用 redisTemplate.opsForValue().multiGet(keys) 来获取这些键对应的所有值,并将结果存储在 values 列表中。

你可以在 Spring Boot 应用程序的其他组件中注入 RedisExample,然后调用 getAllAccountPositions() 方法来获取所有 'account_positions' 的值。

SpringBoot Redis 查询所有 'account_positions' 数据

原文地址: https://www.cveoy.top/t/topic/o8AY 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录