如何使用 Jedis 连接到适用于 Redis 集群的 AWS ElastiCache?

How do I connect to an AWS ElastiCache for Redis Cluster using Jedis?

以前,我们使用的是通过 AWS ElastiCache 禁用集群模式的 Redis。

我们使用 Jedis 的 Java 代码指向用于读取和写入的主要单节点端点。

我们现已启用集群模式。

我们现在更改了代码以指向新 Redis 集群的配置端点,但是它现在在接收请求时抛出错误,请参见下文:

Redis Unavailable. Continue using the Queue requestMessage instead. org.springframework.data.redis.ClusterRedirectException: Redirect: slot 2356 to [ipaddress]:6379.; nested exception is redis.clients.jedis.exceptions.JedisMovedDataException: MOVED 2356 [ipaddress]:6379

我们的配置代码如下:

    @Bean(name = "redisTemplate")
    public RedisTemplate<String, String> getRedisTemplate(JedisConnectionFactory jedisConnectionFactory) {
        RedisTemplate template = new RedisTemplate();
        template.setConnectionFactory(jedisConnectionFactory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(new StringRedisSerializer());
        template.afterPropertiesSet();
        return template;
    }

    @Bean
    JedisConnectionFactory jedisConnectionFactory(Configuration config) {
        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();
        jedisConnectionFactory.setHostName(config.get(HOST));
        jedisConnectionFactory.setPort(config.getInt(PORT));
        jedisConnectionFactory.setUsePool(true);
        jedisConnectionFactory.setPoolConfig(createJedisPoolConfig(config));
        jedisConnectionFactory.afterPropertiesSet();
        return jedisConnectionFactory;
    }

    JedisPoolConfig createJedisPoolConfig(Config config) {
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxTotal(config.getInt(MAX, 8));
        poolConfig.setMaxIdle(config.getInt(MAXIDLE, 8));
        poolConfig.setMinIdle(config.getInt(MINIDLE, 1));
        poolConfig.setTestOnBorrow(true);
        poolConfig.setTestOnReturn(true);
        return poolConfig;
    }

不应该只是将 Jedis 更改为指向配置端点就足够了吗?

我需要更改代码中的任何内容吗?

Shouldn't just changing Jedis to point to the configuration endpoint be enough?

不,因为 Redis 客户端 - 在本例中为 Jedis - 需要知道它正在连接到一个集群,而目前没有。

你得到 MOVED 因为 Redis 集群告诉客户端请求的数据现在已经 'resharded' 到另一个节点。然而,Jedis 并不知道集群正在被使用,因此没有任何其他节点,因此,甚至无法连接到它们来检索数据。

Do I need to change anything in my code?

您需要使用 JedisCluster 而不是 JedisPool 来发现 Redis 节点并在代码库中进行其他相关更改。

请注意,您只需要引用配置端点:

Set<HostAndPort> jedisClusterNodes = new HashSet<HostAndPort>();

jedisClusterNodes.add(new HostAndPort(CONFIGURATION_ENDPOINT, 6379));

try (JedisCluster jedisCluster = new JedisCluster(jedisClusterNodes)) {
// ...
}