spring data redis主从配置

2024-03-20

以下是我的 jedis 配置

@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主服务器和多个redis从服务器。根据 redis 文档,读取应该从从属设备发生,写入应该从主设备发生。如何更改上述配置以使用主机进行写入和从机进行读取?

假设我的主服务器位于 192.168.10.10,从服务器位于 localhost。

Thanks!


目前 Spring Data Redis 中没有配置选项可以实现所需的行为。也没有Jedis它自己为这种情况提供支持(请参阅绝地武士 #458 https://github.com/xetorthio/jedis/issues/458). RedisConnection执行操作时向工厂请求连接。此时,所请求资源的使用目的尚不清楚,因为命令可能是r, w or 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对于专用的read, write目的。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

spring data redis主从配置 的相关文章

  • Java中如何合并两个数组?

    它不是连接而是合并两个数组 使它们成为名称值对的数组 firstarray a aa aaa secondarray b bb bbb result a b aa bb aaa bbb 最好的方法是什么 in Java public sta
  • selenium 2.0 中的 isElementPresent

    大家好 我正在使用 webdriver 所以如果我想使用 selenium s rc 函数 isElementPresent 我必须模拟 selenium rc 所以我会执行以下操作 import org openqa selenium B
  • Java中的字节和字符转换

    如果我将一个字符转换为byte然后回到char 那个角色神秘地消失了 变成了别的东西 这怎么可能 这是代码 char a line 1 byte b byte a line 2 char c char b line 3 System out
  • Java中如何对对象数组进行排序?

    我的数组不包含任何字符串 但它包含对象引用 每个对象引用都通过 toString 方法返回名称 id 作者和发布者 public String toString return name n id n author n publisher n
  • java中%%是什么意思?

    我是一名 PHP 程序员 想知道这行代码的含义 System out printf exp 3f is 3f n x Math exp x 3f 3f n 和逗号 x 是什么意思 它与C类似printf http java sun com
  • 使用 SSL 和代理设置的 Rest 客户端获取连接超时

    我正在使用带有忽略 ssl 的 Rest 客户端 它工作正常 但在将来我尝试使用客户端证书进行的生产中将无法工作 我有 ca 证书和客户端证书 我用它创建了一个客户端 但我收到错误 Exception in thread main com
  • Android Studio:如果设置项目的背景颜色,ListView OnClick 动画将不起作用

    在我的项目中 我在 ListView 内设置了项目 由插入 ConstraintLayout 中的多个元素组成 的背景颜色 但如果背景颜色不是至少一点透明 则单击和长按的默认动画会消失 事实上 随着透明度的降低 点击元素的效果越来越不明显
  • Mockito mockStatic 无法解析符号

    我正在使用 Spring Boot 并在单元测试中 我试图模拟Files delete myFile toPath method 为此 我尝试使用Mockito mockStatic 方法 但是当我尝试使用它时 我的 IDE Intelli
  • Map:为 Integer 和 Double 类型定义方法,但不为 String 类型定义方法

    我正在尝试定义一个方法putIfGreaterThan 为了我的新Map class 给定一个键 仅当新值大于旧值时 它才会用新值替换旧值 我知道我可以通过组合来实现这一点 通过有一个private final Map
  • 在spring mvc中修改请求URI

    我有一个基于 spring mvc 的应用程序 我想在请求 URI 到达控制器之前修改它 例如 控制器的 RequestMapping 是 abc xyz 但传入的请求是 abc 1 xyz 我想修改传入请求以将其映射到控制器 解决方案1
  • 如何在 PuTTY 中保存并运行 Java 文件?

    我是 AWS 亚马逊网络服务 的新手 所以这可能是一个基本问题 我在 AWS 上创建了一个 EC2 实例 我有一台 Windows 计算机 因此我使用 PUTTY 来连接 Linux 实例 连接到我的 EC2 实例后 我使用以下命令编写 J
  • Spring Boot 中 application.properties 可用的属性列表?

    Spring Boot文档说我们可以在application properties文件中设置属性 但我找不到列出可以设置的可用属性的文档 我在哪里可以找到这样的文档 例如 我想为嵌入式servlet设置documentRoot 我发现set
  • 从侦听器中修改 JFrame [重复]

    这个问题在这里已经有答案了 可能的重复 如何在框架可见后调用 setUndecorated https stackoverflow com questions 875132 how to call setundecorated after
  • 运行 Espresso 测试时在 Android studio 中找不到属性 android:forceQueryable

    我已经使用 android studio 录制了我的 Android 应用程序 Espresso 测试记录浓缩咖啡测试选项中Run菜单 在记录的最后 我用自己的文件名保存了测试 单击保存按钮后 IDE 会自动在以下位置创建文件Android
  • Java环境变量设置方法

    我已将以下行插入 bash profile export GOOGLE APPLICATION CREDENTIALS Users jun Downloads export PATH PATH GOOGLE APPLICATION CRED
  • 为什么 OOP 中静态类的最佳实践有所不同?

    我目前正在阅读有关 Java 最佳实践的内容 我发现根据这本书 https rads stackoverflow com amzn click com 0321356683我们必须优先选择静态类而不是非静态类 我记得在 C 最佳实践中 我们
  • java - 简单计算在多线程中比在单线程中花费更长的时间

    我试图了解如何利用多线程 我写了一个简单的程序来增加i 比方说 使用两种方式 400 000 次 单线程方式 0 到 400 000 和多线程方式 在我的例子中 4 次 0 到 100 000 线程数等于Runtime getRuntime
  • 在edittext android中插入imageview

    我想将 imageview 放在 edittext 中 可能吗 我检查了 evernote 应用程序 它能够将照片放在编辑文本部分 我想让我的应用程序完全相同 我如何才能将从图库中选择的图像视图放入编辑文本中 我首先尝试将 imagevie
  • 如何在 tomcat 上部署 Java Web 应用程序 (.war)?

    我有一个 warJava Web 应用程序的文件 现在我想将它上传到我的 ftp 服务器 以便我可以执行它 我应该执行哪些步骤来运行它 webapp的上下文路径是 mywebapp Edit 实际上 我的 ftp 服务器名称是ftp bil
  • ImageIO.read(...) - 非常慢,有更好的方法吗?

    我正在加载大量将在我的应用程序中使用的图标 我计划在服务器启动时从 jar 中加载所有这些 然而 由于数百张图像加起来刚刚超过 9MB 执行此任务仍然需要 30 秒多的时间 我现在正在一个单独的线程中执行此操作 但这让我想知道我是否在代码中

随机推荐