首页 > 解决方案 > 如何在 Spring 中修复“无法将此命令分派到 Redis 集群,因为键具有不同的插槽”

问题描述

我需要在 Spring 中使用 Redis Cluster。但是当我在键列表上使用 mget 或 del 时出现以下错误:“无法将此命令分派到 Redis 集群,因为键具有不同的插槽”。使用 JedisCluster 显示我的部分组件代码。

当我使用单键操作但不使用多个键时,它可以工作。

/* Component Code */
public class RedisServiceManager {

    @Value("${redis.hosts}")
    String hosts;

    @Autowired
    JedisPoolConfig jedisPoolConfig;

    private JedisCluster jedisCluster;

    @PostConstruct
    private void init() {
        List<String> redisHosts = Arrays.asList(hosts.split(","));
        Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
        redisHosts.forEach(redisHost -> {
            jedisClusterNode.add(new HostAndPort(redisHost, 6379));
        });
        jedisCluster = new JedisCluster(jedisClusterNode, jedisPoolConfig);
    }

    // This works
    public String getValueForKey(String key) {
        try {
            return jedisCluster.get(key);
        } catch (Exception e) {
            return null;
        }
    }

    // This works
    public void delKey(String cacheKey) {
        try {
            jedisCluster.del(cacheKey);
        } catch (Exception e) {
        }
    }

    // This doesn't work
    public List<String> getValuesForAllKeys(String... keys) {
        try {
            return jedisCluster.mget(keys);
        } catch (Exception e) {
            return new ArrayList<>();
        }
    }

    // This doesn't work
    public void delAllKeys(String... keys) {
        try {
            jedisCluster.del(keys);
        } catch (Exception e) {
        }
    }
}

有人可以帮忙吗?

标签: springspring-bootredisjedisredis-cluster

解决方案


这不是错误或问题,而是 redis 集群的工作方式。您可以在集群文档中找到更多详细信息。但不要担心:有一个“技巧”:您可以使用 这里描述的哈希


推荐阅读