欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Redis主从实现读写分离

程序员文章站 2022-04-01 08:39:39
前言 大家在工作中可能会遇到这样的需求,即redis读写分离,目的是为了压力分散化。下面我将为大家介绍借助aws的elb实现读写分离,以写主读从为例。 实现 引用库文...

前言

大家在工作中可能会遇到这样的需求,即redis读写分离,目的是为了压力分散化。下面我将为大家介绍借助aws的elb实现读写分离,以写主读从为例。

实现

引用库文件

  <!-- redis客户端 -->
  <dependency>
   <groupid>redis.clients</groupid>
   <artifactid>jedis</artifactid>
   <version>2.6.2</version>
  </dependency>

方式一,借助切面

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);
        jedispool jedispool = (jedispool) ctx.getbean(data.value());
        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-configuration/ -->
    <!-- 调用者获取链接时,是否检测当前链接有效性。无效则从链接池中移除,并尝试继续获取。(默认为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"/>
    <!-- 此处host配置成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"));
  }

}

方式二,依赖注入

与方式一类似,但是需要写死具体使用主的池还是从的池,思路如下:
放弃注解的方式,直接将主和从的两个链接池注入到具体实现类中。

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-configuration/ -->
    <!-- 调用者获取链接时,是否检测当前链接有效性。无效则从链接池中移除,并尝试继续获取。(默认为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>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。