3

以下是我的绝地配置

@Bean
public JedisConnectionFactory getJedisConnectionFactory() {
    JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();
    jedisConnectionFactory.setUsePool(true);
    return jedisConnectionFactory;
}

@Bean
public RedisTemplate<String, Object> getRedisTemplate() {
    RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
    redisTemplate.setConnectionFactory(getJedisConnectionFactory());
    return redisTemplate;
}

当我有单个服务器时,此配置运行良好。我想要做的是拥有 1 个 redis master 和多个 redis slave。根据 redis 文档,读取应该从奴隶发生,写入应该从主人发生。如何更改上述配置以使用 master 写入和 slave 读取?

假设我的主人在 192.168.10.10,奴隶在 localhost。

谢谢!

4

4 回答 4

5

目前,Spring Data Redis 中没有可以启用所需行为的配置选项。Jedis本身也不提供对这种场景的支持(参见jedis #458)。 RedisConnection执行操作时向工厂请求连接。此时,请求的资源的使用目的不清楚,因为命令可能是rw或者rw

一种可能的解决方案是自定义RedisConnectionFactory能够提供连接 - 到您拥有的其中一个从属设备 - 在执行只读命令的情况下。

SlaveAwareJedisConnectionFactory factory = new SlaveAwareJedisConnectionFactory();
factory.afterPropertiesSet();

RedisConnection connection = factory.getConnection();

// writes to master
connection.set("foo".getBytes(), "bar".getBytes());

// reads from slave
connection.get("foo".getBytes());

/**
 * SlaveAwareJedisConnectionFactory wraps JedisConnection with a proy that delegates readonly commands to slaves.
 */
class SlaveAwareJedisConnectionFactory extends JedisConnectionFactory {

  /**
    * Get a proxied connection to Redis capable of sending
    * readonly commands to a slave node
    */
  public JedisConnection getConnection() {

    JedisConnection c = super.getConnection();

    ProxyFactory proxyFactory = new ProxyFactory(c);
    proxyFactory.addAdvice(new ConnectionSplittingInterceptor(this));
    proxyFactory.setProxyTargetClass(true);

    return JedisConnection.class.cast(proxyFactory.getProxy());
  };

  /**
   * This one will get the connection to one of the slaves to read from there
   * 
   * @return
   */
  public RedisConnection getSlaveConnection() {

    //TODO: find the an available slave serving the data
    return new JedisConnection(new Jedis("your slave host lookup here"));
  }

  static class ConnectionSplittingInterceptor implements MethodInterceptor,
      org.springframework.cglib.proxy.MethodInterceptor {

    private final SlaveAwareJedisConnectionFactory factory;

    public ConnectionSplittingInterceptor(SlaveAwareJedisConnectionFactory factory) {
      this.factory = factory;
    }

    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {

      RedisCommand commandToExecute = RedisCommand.failsafeCommandLookup(method.getName());

      if (!commandToExecute.isReadonly()) {
        return invoke(method, obj, args);
      }

      RedisConnection connection = factory.getSlaveConnection();

      try {
        return invoke(method, connection, args);
      } finally {
        // properly close the connection after executing command
        if (!connection.isClosed()) {
          connection.close();
        }
      }
    }

    private Object invoke(Method method, Object target, Object[] args) throws Throwable {

      try {
        return method.invoke(target, args);
      } catch (InvocationTargetException e) {
        throw e.getCause();
      }
    }

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
      return intercept(invocation.getThis(), invocation.getMethod(), invocation.getArguments(), null);
    }
  }
}

上面的解决方案包含几个问题。例如。 MULTI EXEC应用程序中的块可能不再按预期工作,因为命令现在可能会通过管道传输到您不希望它们出现的地方。RedisTemplates所以也许有多个用于专用目的也是有意义的。

于 2015-04-09T12:38:25.610 回答
4

您应该使用Redis Sentinel来保持 redis 的主/从配置...您可以使用以下连接到哨兵池-

@Bean
public RedisConnectionFactory jedisConnectionFactory() {
RedisSentinelConfiguration sentinelConfig = new RedisSentinelConfiguration() .master("mymaster")
    .sentinel("127.0.0.1", 26379) .sentinel("127.0.0.1", 26380);
return new JedisConnectionFactory(sentinelConfig);
}

参考:Spring Sentinel 支持

于 2015-10-18T09:51:20.387 回答
2

你想写到主从从读

这是如何使用哨兵集群和 spring-boot 配置它

spring:
  data:
    redis:
      sentinel: 
        master: mymaster
        nodes: my.sentinel.hostname1:26379,my.sentinel.hostname2:26379
      port: 6379

和弹簧配置

@Configuration
public class RedisDatasourceConfig {

  @Bean
  public LettuceClientConfigurationBuilderCustomizer lettuceClientConfigurationBuilderCustomizer() {
    return p -> p.readFrom(SLAVE_PREFERRED);
  }
}
于 2019-03-24T22:42:17.283 回答
0

具有主/从架构的复制与 Sentinel 不同。

设置 redis 只读副本非常容易。

我的 Spring Boot 应用程序 yaml。

redis:
  master:
    host: localhost
    port: 6379
  slaves:
    - host: localhost
      port: 16379
    - host: localhost
      port: 26379

对于上述实例,从属实例 redis 配置应更新如下所示。

################################# REPLICATION #################################

# Master-Replica replication. Use replicaof to make a Redis instance a copy of
# another Redis server. A few things to understand ASAP about Redis replication.
#
#   +------------------+      +---------------+
#   |      Master      | ---> |    Replica    |
#   | (receive writes) |      |  (exact copy) |
#   +------------------+      +---------------+
#
# 1) Redis replication is asynchronous, but you can configure a master to
#    stop accepting writes if it appears to be not connected with at least
#    a given number of replicas.
# 2) Redis replicas are able to perform a partial resynchronization with the
#    master if the replication link is lost for a relatively small amount of
#    time. You may want to configure the replication backlog size (see the next
#    sections of this file) with a sensible value depending on your needs.
# 3) Replication is automatic and does not need user intervention. After a
#    network partition replicas automatically try to reconnect to masters
#    and resynchronize with them.
#
replicaof master 6379

在此处查看 docker 设置。

https://www.vinsguru.com/redis-master-slave-with-spring-boot/

于 2020-11-14T16:25:49.637 回答