广告
返回顶部
首页 > 资讯 > 数据库 >Redis主从实现读写分离
  • 222
分享到

Redis主从实现读写分离

主从Redis 2022-06-04 17:06:34 222人浏览 安东尼
摘要

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

前言

大家在工作中可能会遇到这样的需求,即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;


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


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


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;


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;


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;


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>

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

您可能感兴趣的文档:

--结束END--

本文标题: Redis主从实现读写分离

本文链接: https://www.lsjlt.com/news/11934.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Redis主从实现读写分离
    前言 大家在工作中可能会遇到这样的需求,即Redis读写分离,目的是为了压力分散化。下面我将为大家介绍借助AWS的ELB实现读写分离,以写主读从为例。 实现 引用库文件 <!-- redis客...
    99+
    2022-06-04
    主从 Redis
  • redis主从同步与读写分离
    一、原理Redis的主从复制功能非常强大,一个master可以拥有多个slave,而一个slave又可以拥有多个slave,如此下去,形成了强大的多级服务器集群架构。下面是关于redis主从复制的一些特点:...
    99+
    2022-10-18
  • mysql主从配置实现一主一从读写分离
    主从介绍Mysql主从又叫Replication、AB复制。简单讲就是A与B两台机器做主从后,在A上写数据,另外一台B也会跟着写数据,实现数据实时同步 mysql主从是基于binlog,主上需开启binlo...
    99+
    2022-10-18
  • mysql主从及读写分离
     主从同步1 主配置把237配置为主数据库服务器  授权用户从42数据库服务器连接自己的时候有拷贝数据的权限grant   replication &nbs...
    99+
    2022-10-18
  • Django搭建MySQL主从实现读写分离
    目录一、MySQL主从搭建操作步骤二、Django实现读写分离自动指定一、MySQL主从搭建 主从配置原理: 主库写日志到 BinLog 从库开个 IO 线程读取...
    99+
    2022-11-12
  • Mycat中间件实现Mysql主从读写分离
    环境规划: IP地址 主机名 角色 备注 10.4.132.50 k8s01 mycat,master 10.4.132.42 k8s02 slave ...
    99+
    2022-10-18
  • SQL Server搭建主从同步实现读写分离
    一、概念简介 1.1、基本概念 1)读写分离概念:是把对数据库的读操作和写操作分离开。在一定程度上,读写分离可以缓解读写操作并发时产生锁的问题。 2)读写分离原理:是让主数据库处理事务性增、删、改操作(INSERT、DELETE、UPDA...
    99+
    2016-01-18
    SQL Server搭建主从同步实现读写分离
  • mysql主从基于docker和django实现读写分离
    目录1.主从搭建实操2.django实现读写分离settings.py配置手动指定读写分离自动指定(写router和配置setting)更细粒度(分库分表时需要)在数据库迁移时,可以指定把哪个app的表结构迁移到哪个库1...
    99+
    2022-08-25
  • amoeba实现mysql读写分离+主从复制架构
    一、环境系统:centos6.5mysql版本:mysql5.6master服务器:192.168.1.21slave服务器: 192.168.1.100master写 slave读二、实现mysql主从复...
    99+
    2022-10-18
  • MyCat怎么实现MySQL一主两从读写分离
    这篇文章主要介绍“MyCat怎么实现MySQL一主两从读写分离”,在日常操作中,相信很多人在MyCat怎么实现MySQL一主两从读写分离问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大...
    99+
    2022-10-18
  • MyCat如何实现MySQL双主一从读写分离
    这篇文章给大家分享的是有关MyCat如何实现MySQL双主一从读写分离的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。1)配置server.xml<user nam...
    99+
    2022-10-18
  • redis读写分离怎么实现
    Redis读写分离可以通过以下几种方式实现:1. 主从复制(Master-Slave):将一个Redis实例作为主节点(Master...
    99+
    2023-09-06
    redis
  • MySQL 主从复制与读写分离
             在实际生产环境中,如果对数据库的读写都在同一块数据库服务器中操作,无论是在安全性、高可用性,还是高并发等各个...
    99+
    2022-10-18
  • SpringBoot环境-MySQL主从复制,读写分离的实现
    目录 概述 环境 主从复制 读写分离 概述  记录在MySQL数据库中主从复制以及SpringBoot环境操作MySQL数据库读写分离的实现步骤。  背景 :因为我们在对数据库进行操作时,如果读写操作都由一台数据库承担的话压...
    99+
    2023-09-06
    mysql 数据库 java linux
  • 利用Amoeba实现MySQL主从复制和读写分离
    在实际生产环境中,如果对数据库的读和写都在同一个数据库服务器中操作,无论是在安全性、高可用性,还是高并发等各个方面都是完全不能满足实际需求的,因此,一般来说都是通过主从复制(Master-Slave)的方式...
    99+
    2022-10-18
  • MySQL中如何实现主从复制与读写分离
    MySQL中如何实现主从复制与读写分离,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。1,mysql的配置CentOS 5.x,6.0编译安装N...
    99+
    2022-10-18
  • Linux如何使用 MyCat 实现 MySQL 主从读写分离
    目录Linux-使用 MyCat 实现 MySQL 主从读写分离 一、MySQL 读写分离1、MySQL 读写分离的概述2、读写分离工作原理3、为什么要读写分离3、实现读写分离的方式...
    99+
    2022-11-12
  • MySQL中怎么实现主从复制及读写分离
    MySQL中怎么实现主从复制及读写分离?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。一、相关概述主从复制:主数据库(Master)发送更新事件到从数据库(Slave),从数...
    99+
    2023-06-14
  • MYSQL的主从复制与读写分离
    在实际生产环境中,如果对数据库的读和写都在同一个数据库服务器中操作,无论是安全性,高可用性,还是高并发性等各个方面都是不能满足实际需求,因此,一般来说都是通过主从复制的方式来同步诗句,再通过读写分离来提升数...
    99+
    2022-10-18
  • springboot结合mysql主从来实现读写分离的方法
    这篇文章主要介绍springboot结合mysql主从来实现读写分离的方法,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!1.实现的功能    基于springboot框架,applica...
    99+
    2023-06-14
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作