English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Redisのマスターからスレーブの読み書き分離の実現

前書き

皆さんが仕事で直面するかもしれないようなニーズがあります。それは、Redisの読み取りと書き込みの分離で、その目的は負荷分散です。以下では、AWSのELBを利用して読み取りと書き込みの分離を実現する方法について、主が書き込み、サブが読み取りの場合を例に説明します。

実装

リファレンスライブラリを参照

  <!-- redisクライアント -->
  <dependency>
   <groupId>redis.clients</groupId>
   <artifactId>jedis</artifactId>
   <version>2.6.2</version>
  </dependency>

方法1、アスペクトを利用して

JedisPoolSelector

このクラスの目的は、読み取りと書き込みに異なるアノテーションを設定し、メインまたはサブを区別するために使用されます。

package com.silence.spring.redis.readwriteseparation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
 * Created by keysilence on 16/10/26.
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface JedisPoolSelector {
  String value();
}

JedisPoolAspect

このクラスの目的は、メインとサブのアノテーションに対して、動的なリンクプール割り当てを行い、メインはメインリンクプールを使用し、サブはサブリンクプールを使用する。

package com.silence.spring.redis.readwriteseparation;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import redis.clients.jedis.JedisPool;
import javax.annotation.PostConstruct;
import java.lang.reflect.Method;
import java.util.Date;
/**
 * Created by keysilence on 16/10/26.
 */
@Aspect
public class JedisPoolAspect implements ApplicationContextAware {
  private ApplicationContext ctx;
  @PostConstruct
  public void init() {
    System.out.println("jedis pool aspectj started @" + new Date());
  }
  @Pointcut("execution(* com.silence.spring.redis.readwriteseparation.util.*.*(..))")
  private void allMethod() {
  }
  @Before("allMethod()")
  public void before(JoinPoint point)
  {
    Object target = point.getTarget();
    String method = point.getSignature().getName();
    Class classz = target.getClass();
    Class<?][] parameterTypes = ((MethodSignature) point.getSignature())
        .getMethod().getParameterTypes();
    try {
      Method m = classz.getMethod(method, parameterTypes);
      if (m != null && m.isAnnotationPresent(JedisPoolSelector.class)) {
        JedisPoolSelector data = m
            .getAnnotation(JedisPoolSelector.class);
        DynamicJedisPoolHolder.putJedisPool(jedisPool);
        catch (Exception e) {
      }
    }
      e.printStackTrace();
    }
  }
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    this.ctx = applicationContext;
  }
}

DynamicJedisPoolHolder

このクラスの目的は、現在使用しているJedisPoolを保存することであり、上記のクラスに割り当てられた結果を保存します。

package com.silence.spring.redis.readwriteseparation;
import redis.clients.jedis.JedisPool;
/**
 * Created by keysilence on 16/10/26.
 */
public class DynamicJedisPoolHolder {
  public static final ThreadLocal<JedisPool> holder = new ThreadLocal<JedisPool>();
  public static void putJedisPool(JedisPool jedisPool) {
    holder.set(jedisPool);
  }
  public static JedisPool getJedisPool() {
    return holder.get();
  }
}

RedisUtils

このクラスの目的は、Redisへの具体的な呼び出しを処理することであり、メインまたはサブの呼び出し方法を含んでいます。

package com.silence.spring.redis.readwriteseparation.util;
import com.silence.spring.redis.readwriteseparation.DynamicJedisPoolHolder;
import com.silence.spring.redis.readwriteseparation.JedisPoolSelector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * Created by keysilence on 16/10/26.
 */
public class RedisUtils {
  private static Logger logger = LoggerFactory.getLogger(RedisUtils.class);
  @JedisPoolSelector("master")
  public String setString(final String key, final String value) {
    String ret = DynamicJedisPoolHolder.getJedisPool().getResource().set(key, value);
    System.out.println("key:" + key + ",value:" + value + ",ret:" + ret);
    return ret;
  }
  @JedisPoolSelector("slave")
  public String get(final String key) {
    String ret = DynamicJedisPoolHolder.getJedisPool().getResource().get(key);
    System.out.println("key:" + key + ",ret:" + ret);
    return ret;
  }
}

spring-datasource.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
  <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
    <!-- プール内の最大リンク数 -->
    <property name="maxTotal" value="100"/>
    <!-- プール内の最大アイドルリンク数 -->
    <property name="maxIdle" value="50"/>
    <!-- プール内の最小アイドルリンク数 -->
    <property name="minIdle" value="20"/>
    <!-- プール内のリンクが尽きた場合、呼び出し元の最大ブロッキング時間。この時間を超えると、例外が発生します。(単位:ミリ秒;デフォルトは-1、タイムアウトしないことを意味します) -->
    <property name="maxWaitMillis" value="1000"/>
    <!-- 参照:http://biasedbit.com/redis-jedispool-設定/ -->
    <!-- 呼び出し元がリンクを取得する際に、現在のリンクの有効性を検出するかどうか。無効であれば、リンクプールから削除し、引き続き取得を試みる。(デフォルトはfalse) -->
    <property name="testOnBorrow" value="true" />
    <!-- リンクプールにリンクを返却する際に、リンクの有効性を検出するかどうか。(デフォルトはfalse) -->
    <property name="testOnReturn" value="true" />
    <!-- 呼び出し元がリンクを取得する際に、アイドルタイムアウトの検出を行うかどうか。タイムアウトすると、削除される(デフォルトはfalse) -->
    <property name="testWhileIdle" value="true" />
    <!-- アイドルリンクの検出スレッドが一度に検出するリンクの数 -->
    <property name="numTestsPerEvictionRun" value="10" />
    <!-- アイドルリンクの検出スレッドの検出周期。負の値の場合、検出スレッドを実行しない。(単位:ミリ秒、デフォルトは-1) -->
    <property name="timeBetweenEvictionRunsMillis" value="60000" />
    <!-- リンクの取得方法。キュー:false;スタック:true -->
    <!--<property name="lifo" value="false" />-->
  </bean>
  <bean id="master" class="redis.clients.jedis.JedisPool">
    <constructor-arg index="0" ref="poolConfig"/>
    <constructor-arg index="1" value="192.168.100.110" type="java.lang.String"/>
    <constructor-arg index="2" value="6379" type="int"/>
  </bean>
  <bean id="slave" class="redis.clients.jedis.JedisPool">
    <constructor-arg index="0" ref="poolConfig"/>
    <!-- ここでホスト設定をELBアドレスにします。 -->
    <constructor-arg index="1" value="192.168.100.110" type="java.lang.String"/>
    <constructor-arg index="2" value="6380" type="int"/>
  </bean>
  <bean id="redisUtils" class="com.silence.spring.redis.readwriteseparation.util.RedisUtils">
  </bean>
  <bean id="jedisPoolAspect" class="com.silence.spring.redis.readwriteseparation.JedisPoolAspect" />
  <aop:aspectj-autoproxy proxy-target-class="true"/>
</beans>

Test

package com.silence.spring.redis.readwriteseparation;
import com.silence.spring.redis.readwriteseparation.util.RedisUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
 * Created by keysilence on 16/10/26.
 */
public class Test {
  public static void main(String[] args) {
    ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-datasource.xml");
    System.out.println(ctx);
    RedisUtils redisUtils = (RedisUtils) ctx.getBean("redisUtils");
    redisUtils.setString("aaa", "111");
    System.out.println(redisUtils.get("aaa"));
  }
}

方法2、依存注入

方法1と似ていますが、メインのプールかサブのプールを使用するかを明示的に指定する必要があります。以下のようになります:
アノテーションを放棄し、メインとサブの両方のリンクプールを具体的な実装クラスに直接注入します。

RedisUtils

package com.silence.spring.redis.readwriteseparation.util;
import com.silence.spring.redis.readwriteseparation.DynamicJedisPoolHolder;
import com.silence.spring.redis.readwriteseparation.JedisPoolSelector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.JedisPool;
/**
 * Created by keysilence on 16/10/26.
 */
public class RedisUtils {
  private static Logger logger = LoggerFactory.getLogger(RedisUtils.class);
  private JedisPool masterJedisPool;
  private JedisPool slaveJedisPool;
  public void setMasterJedisPool(JedisPool masterJedisPool) {
    this.masterJedisPool = masterJedisPool;
  }
  public void setSlaveJedisPool(JedisPool slaveJedisPool) {
    this.slaveJedisPool = slaveJedisPool;
  }
  public String setString(final String key, final String value) {
    String ret = masterJedisPool.getResource().set(key, value);
    System.out.println("key:" + key + ",value:" + value + ",ret:" + ret);
    return ret;
  }
  public String get(final String key) {
    String ret = slaveJedisPool.getResource().get(key);
    System.out.println("key:" + key + ",ret:" + ret);
    return ret;
  }
}

spring-datasource.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
  <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
    <!-- プール内の最大リンク数 -->
    <property name="maxTotal" value="100"/>
    <!-- プール内の最大アイドルリンク数 -->
    <property name="maxIdle" value="50"/>
    <!-- プール内の最小アイドルリンク数 -->
    <property name="minIdle" value="20"/>
    <!-- プール内のリンクが尽きた場合、呼び出し元の最大ブロッキング時間。この時間を超えると、例外が発生します。(単位:ミリ秒;デフォルトは-1、タイムアウトしないことを意味します) -->
    <property name="maxWaitMillis" value="1000"/>
    <!-- 参照:http://biasedbit.com/redis-jedispool-設定/ -->
    <!-- 呼び出し元がリンクを取得する際に、現在のリンクの有効性を検出するかどうか。無効であれば、リンクプールから削除し、引き続き取得を試みる。(デフォルトはfalse) -->
    <property name="testOnBorrow" value="true" />
    <!-- リンクプールにリンクを返却する際に、リンクの有効性を検出するかどうか。(デフォルトはfalse) -->
    <property name="testOnReturn" value="true" />
    <!-- 呼び出し元がリンクを取得する際に、アイドルタイムアウトの検出を行うかどうか。タイムアウトすると、削除される(デフォルトはfalse) -->
    <property name="testWhileIdle" value="true" />
    <!-- アイドルリンクの検出スレッドが一度に検出するリンクの数 -->
    <property name="numTestsPerEvictionRun" value="10" />
    <!-- アイドルリンクの検出スレッドの検出周期。負の値の場合、検出スレッドを実行しない。(単位:ミリ秒、デフォルトは-1) -->
    <property name="timeBetweenEvictionRunsMillis" value="60000" />
    <!-- リンクの取得方法。キュー:false;スタック:true -->
    <!--<property name="lifo" value="false" />-->
  </bean>
  <bean id="masterJedisPool" class="redis.clients.jedis.JedisPool">
    <constructor-arg index="0" ref="poolConfig"/>
    <constructor-arg index="1" value="192.168.100.110" type="java.lang.String"/>
    <constructor-arg index="2" value="6379" type="int"/>
  </bean>
  <bean id="slaveJedisPool" class="redis.clients.jedis.JedisPool">
    <constructor-arg index="0" ref="poolConfig"/>
    <constructor-arg index="1" value="192.168.100.110" type="java.lang.String"/>
    <constructor-arg index="2" value="6380" type="int"/>
  </bean>
  <bean id="redisUtils" class="com.silence.spring.redis.readwriteseparation.util.RedisUtils">
    <property name="masterJedisPool" ref="masterJedisPool"/>
    <property name="slaveJedisPool" ref="slaveJedisPool"/>
  </bean>
</beans>

これで本文のすべての内容が終わります。皆様の学習に役立てば幸いですし、もっと「ナイアラベクトル」をサポートしていただけると嬉しいです。

声明:本文の内容はインターネットから取得しており、著作権者に帰属します。インターネットユーザーにより自発的に提供されたコンテンツであり、本サイトは所有権を有しておらず、編集も行われていません。著作権侵害が疑われる内容がある場合は、以下のメールアドレスまでご連絡ください:notice#oldtoolbag.com(メール送信時は、#を@に変更してください。報告を行い、関連する証拠を提供してください。一旦確認がとれましたら、本サイトは即座に侵害する可能性のある内容を削除します。)

おすすめ