• linkedu视频
  • 平面设计
  • 电脑入门
  • 操作系统
  • 办公应用
  • 电脑硬件
  • 动画设计
  • 3D设计
  • 网页设计
  • CAD设计
  • 影音处理
  • 数据库
  • 程序设计
  • 认证考试
  • 信息管理
  • 信息安全
菜单
linkedu.com
  • 网页制作
  • 数据库
  • 程序设计
  • 操作系统
  • CMS教程
  • 游戏攻略
  • 脚本语言
  • 平面设计
  • 软件教程
  • 网络安全
  • 电脑知识
  • 服务器
  • 视频教程
  • MsSql
  • Mysql
  • oracle
  • MariaDB
  • DB2
  • SQLite
  • PostgreSQL
  • MongoDB
  • Redis
  • Access
  • 数据库其它
  • sybase
  • HBase
您的位置:首页 > 数据库 >Redis > Redis主从实现读写分离

Redis主从实现读写分离

作者:KeySilenceM 字体:[增加 减小] 来源:互联网 时间:2017-05-11

KeySilenceM通过本文主要向大家介绍了redis主从配置,redis主从复制,redis主从,redis主从切换,redis主从同步等相关知识,希望本文的分享对您有所帮助

前言

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

实现

引用库文件

  <!-- redis客户端 -->
  <dependency>
   <groupId>redis.clients</groupId>
   <artifactId>jedis</artifactId>
   <version>2.6.2</version>
  </dependency>
</div>

方式一,借助切面

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();

}

</div>

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;
  }

}

</div>

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();
  }

}

</div>

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;
  }

}

</div>

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.JedisPoo
  


 
分享到:QQ空间新浪微博腾讯微博微信百度贴吧QQ好友复制网址打印

您可能想查找下面的文章:

  • Redis主从实现读写分离
  • Redis教程(九):主从复制配置实例
  • Redis主从复制问题和扩容问题的解决思路

相关文章

  • 2017-05-11Redis02 使用Redis数据库(String类型)全面解析
  • 2017-05-11Redis实现分布式队列浅析
  • 2017-05-11Redis的11种Web应用场景简介
  • 2017-05-11Redis 对比 Memcached 并在 CentOS 下进行安装配置详解
  • 2017-05-11Redis Stat的安装指南
  • 2017-07-23redis主动向页面push数据
  • 2017-05-11利用Redis实现SQL伸缩的方法
  • 2017-05-11一起raid数据恢复及回迁成功的案例
  • 2017-05-11详解Centos7下配置Redis并开机自启动
  • 2017-09-08Redis4基于CentOS6集群搭建

文章分类

  • MsSql
  • Mysql
  • oracle
  • MariaDB
  • DB2
  • SQLite
  • PostgreSQL
  • MongoDB
  • Redis
  • Access
  • 数据库其它
  • sybase
  • HBase

最近更新的内容

    • EasyCMS在幼儿园视频直播项目实战中以redis操作池的方式应对高并发的redis操作问题
    • 浅析PHP分布式中Redis实现Session的方法
    • 简介Lua脚本与Redis数据库的结合使用
    • Redis实现信息已读未读状态提示
    • Redis服务器的启动过程分析
    • redis配置文件redis.conf中文版(基于2.4)
    • 详解redis是如何实现队列消息的ack
    • Redis教程(十一):虚拟内存介绍
    • Redis操作命令总结
    • Redis2.8配置文件中文详解

关于我们 - 联系我们 - 免责声明 - 网站地图

©2020-2025 All Rights Reserved. linkedu.com 版权所有