Springboot整合Redis主从实践

2025-06-12 15:50

本文主要是介绍Springboot整合Redis主从实践,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

《Springboot整合Redis主从实践》:本文主要介绍Springboot整合Redis主从的实例,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教...

前言

SpringBoot版本:2.3.2.RELEASE

原配置

原yml配置内容:

spring:
  # Redis服务器配置
  redis:
    host: 127.0.0.1
    # Redis服务器连接端口
   fLDsJoaSkC port: 6379
    # Redis服务器连接密码
    password: redis@123
    #连接超时时间(毫秒)
    timeout: 30000ms
    jedis:
      # Redis服务器连接池
      pool:
        # 连接池最大连接数(使用负值表示没有限制)
        maxIdle: 400
        #连接池中的最小空闲连接
        minIdle: 100
        #连接池中的最大空闲连接
        maxActive: 400
        # 连接池最大阻塞等待时间(使用负值表示没有限制)
        maxWait: -1ms
    lettuce:
      pool:
        max-idle: 400
        min-idle: 100
        max-active: 400
        max-wait: -1ms

原RedisConfig配置类:

import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
@EnableCaching
@AutoConfigureAfter(RedisAutoConfiguration.class)
public class RedisConfig {

    @Bean
    @ConditionalOnMissingBean(value = StringRedisTemplate.class, name = "stringRedisTemplate")
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory) {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(factory);
        return template;
    }
}

现配置

现yml配置内容:

spring:
  redis:
    # 主节点
    master:
      host: 127.0.0.1
      port: 6379
      password: redis@123
    # 副本节点
    replicas:
      - host: 127.0.0.1
        port: 6380
    #连接超时时间(毫秒)
    timeout: 30000ms
    jedis:
      # Redis服务器连接池
      pool:
        # 连接js池最大连接数(使用负值表示没有限制)
        maxIdle: 400
        #连接池中的最小空闲连接
        minIdle: 100
        #连接池中的最大空闲连接
        maxActive: 400
        # 连接池最大阻塞等待时间(使用负值表示没有限制)
        maxWait: -1ms
    lettuce:
      pool:
        max-idle: 400
        min-idle: 100
        max-active: 400
        max-wait: -1ms

现RedisConfig配置类:

import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import com.juxiao.xchat.manager.cache.properties.RedisMasterReplicaProperties;
import io.lettuce.core.ClientOptions;
import io.lettuce.core.ReadFrom;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.Chttp://www.chinasem.cnonditionalOnMissingBean;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.co编程ntext.annotation.Configuration;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.data.redis.connection.RedisStaticMasterReplicaConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
@EnableCaching
@AutoConfigureAfter(RedisAutoConfiguration.class)
@EnableConfigurationProperties({RedisMasterReplicaProperties.class, RedisProperties.class})
public class RedisConfig {

    private final RedisMasterReplicaProperties properties;
    private final RedisProperties redisProperties;

    public RedisConfig(RedisMasterReplicaProperties redisMasterReplicaProperties, RedisProperties redisProperties) {
        this.properties = redisMasterReplicaProperties;
        this.redisProperties = redisProperties;
    }

    public LettuceConnectionFactory redisConnectionFactory(boolean readFromMaster) {
        RedisStaticMasterReplicaConfiguration config = new RedisStaticMasterReplicaConfiguration(
                properties.getMaster().getHost(), properties.getMaster().getPort()
        );
        String password = properties.getMaster().getPassword();
        if (StringUtils.isNotBlank(password)) {
            config.setPassword(RedisPassword.of(password));
        }
        for (RedisMasterReplicaProperties.Node replica : properties.getReplicas()) {
            config.addNode(replica.getHost(), replica.getPort());
        }

        // 连接池配置
        LettucePoolingClientConfiguration.LettucePoolingClientConfigurationBuilder builder =
                LettucePoolingClientConfiguration.builder().commandTimeout(redisProperties.getTimeout());
        // 使用 application.yml 中的 lettuce.pool 参数
        RedisProperties.Pool poolProps = redisProperties.getLettuce().getPool();
        if (poolProps != null) {
            builder.poolConfig(poolConfig(poolProps));
        }
        // 优先从副本读取
        builder.readFrom(readFromMaster ? ReadFrom.MASTER : ReadFrom.REPLICA_PREFERRED);
        // 断开连接时拒绝命令[而不是再等待连接超时时间后再报错]、启用自动重连
        builder.clientOptions(ClientOptions.builder()
                .disconnectedBehavior(ClientOptions.DisconnectedBehavior.REJECT_COMMANDS)
                .autoReconnect(true)
                .build());
        LettucePoolingClientConfiguration lettucePoolingClientConfiguration = builder.build();
        // 构建连接工厂
        LettuceConnectionFactory factory = new LettuceConnectionFactory(config, lettucePoolingClientConfiguration);
        // 禁用共享连接 默认是true
        // factory.setShareNativeConnection(false);
        // 初始化工厂 否则调用StringRedisTemplate时会空指针 【因为redisConnectionFactory 方法没有使用@Bean注解将LettuceConnectionFactory交给Spring工厂管理 所以需要手动调用afterPropertiesSet方法初始化连接工厂】
        factory.afterPropertiesSet();
        return factory;
    }

    // 连接池参数绑定
    private GenericObjectPoolConfig<?> poolConfig(RedisProperties.Pool poolProps) {
        GenericObjectPoolConfig<?> config = new GenericObjectPoolConfig<>();
        config.setMaxTotal(poolProps.getMaxActive());
        config.setMaxIdle(poolProps.getMaxIdle());
        config.setMinIdle(poolProps.getMinIdle());
        config.setMaxWaitMillis(poolProps.getMaxWait().toMillis());
        return config;
    }

    @Bean
    @ConditionalOnMissingBean(name = "redisTemplate")
    public RedisTemplate<Object, Object> redisTemplate(LettuceConnectionFactory redisConnectionFactory) {
        redisConnectionFactory.setShareNativeConnection(false);
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        //使用fastjson序列化
        FastJsonRedisSerializer<Object> serializer = new FastJsonRedisSerializer<>(Object.class);
        // value值的序列化采用fastJsonRedisSerializer
        template.setValueSerializer(serializer);
        template.setHashValueSerializer(serializer);
        // key的序列化采用StringRedisSerializer
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializepythonr());
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }

    @Bean("masterStringRedisTemplate")
    @ConditionalOnMissingBean(name = "masterStringRedisTemplate")
    public StringRedisTemplate masterStringRedisTemplate() {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(redisConnectionFactory(true));
        return template;
    }

    @Bean("replicaStringRedisTemplate")
    @ConditionalOnMissingBean(name = "replicaStringRedisTemplate")
    public StringRedisTemplate replicaStringRedisTemplate() {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(redisConnectionFactory(false));
        return template;
    }
}

新增RedisMasterReplicaProperties配置类:

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;

import Java.util.ArrayList;
import java.util.List;

@Data
@ConfigurationProperties(prefix = "spring.redis")
public class RedisMasterReplicaProperties {

    /**
     * 主节点
     */
    private Node master;
    /**
     * 从节点
     */
    private List<Node> replicas = new ArrayList<>();

    @Data
    public static class Node {
        /**
         * 主机地址
         */
        private String host;
        /**
         * 端口
         */
        private int port;
        /**
         * 密码(主从模式master、slave密码必须设置一样的)
         */
        private String password;
    }
}

测试

    @Resource(name = "masterStringRedisTemplate")
    private StringRedisTemplate masterStringRedisTemplate;
    @Resource(name = "replicaStringRedisTemplate")
    private StringRedisTemplate replicaStringRedisTemplate;

    @GetMapping("/test")
    public String test() {
        
        masterStringRedisTemplate.opsForValue().set("imu:test", "Hello6");

        String value = replicaStringRedisTemplate.opsForValue().get("imu:test");
        return value;
    }

LettuceConnectionFactory.setShareNativeConnection 方法的作用

代码中这一行被注释,保持了原本的默认配置true

// 禁用共享连接 默认是true
// factory.setShareNativeConnection(false);

在 Spring Data Redis 中,LettuceConnectionFactory 是一个用于管理 Redis 连接的工厂类,而 setShareNativeConnection(boolean shareNativeConnection) 方法用于控制是否 共享底层的 Redis 连接。

true(默认):

  • 适用于 大多数应用,多个 Redis 操作共享同一个底层连接,减少资源占用。
  • 适用于 Spring Boot + RedisTemplate 场景。

false:

  • 适用于 高并发、多线程环境,避免多个线程争抢同一个 Redis 连接。
  • 适用于 WebFlux、Reactive、Pipeline 等场景。

一般来说,除非你的 Redis 操作出现 多线程连接争用问题,否则 不用手动修改 setShareNativeConnection,保持默认值即可!

而:

  • shareNativeConnection = true
  • (默认)时,Spring 只会创建 一个共享的 StatefulRedisConnection,那么 连接池的 max-active、max-idle、min-idle 这些配置不会生效。
  • shareNativeConnection = false 时,每次请求都会新建连接,这时连接池才会管理多个连接,此时 max-active 等参数才会起作用。
  • 也就是说我们在yml配置文件中配置的连接池信息都将不起作用
    jedis:
      # Redis服务器连接池
      pool:
        # 连接池最大连接数(使用负值表示没有限制)
        maxIdle: 400
        #连接池中的最小空闲连接
        minIdle: 100
        #连接池中的最大空闲连接
        maxActive: 400
        # 连接池最大阻塞等待时间(使用负值表示没有限制)
        maxWait: -1ms
    lettuce:
      pool:
        max-idle: 400
        min-idle: 100
        max-active: 400
        max-wait: -1ms

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持China编程(www.chinasem.cn)。

这篇关于Springboot整合Redis主从实践的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1155027

相关文章

java中pdf模版填充表单踩坑实战记录(itextPdf、openPdf、pdfbox)

《java中pdf模版填充表单踩坑实战记录(itextPdf、openPdf、pdfbox)》:本文主要介绍java中pdf模版填充表单踩坑的相关资料,OpenPDF、iText、PDFBox是三... 目录准备Pdf模版方法1:itextpdf7填充表单(1)加入依赖(2)代码(3)遇到的问题方法2:pd

Java Stream流之GroupBy的用法及应用场景

《JavaStream流之GroupBy的用法及应用场景》本教程将详细介绍如何在Java中使用Stream流的groupby方法,包括基本用法和一些常见的实际应用场景,感兴趣的朋友一起看看吧... 目录Java Stream流之GroupBy的用法1. 前言2. 基础概念什么是 GroupBy?Stream

SpringBoot监控API请求耗时的6中解决解决方案

《SpringBoot监控API请求耗时的6中解决解决方案》本文介绍SpringBoot中记录API请求耗时的6种方案,包括手动埋点、AOP切面、拦截器、Filter、事件监听、Micrometer+... 目录1. 简介2.实战案例2.1 手动记录2.2 自定义AOP记录2.3 拦截器技术2.4 使用Fi

最新Spring Security的基于内存用户认证方式

《最新SpringSecurity的基于内存用户认证方式》本文讲解SpringSecurity内存认证配置,适用于开发、测试等场景,通过代码创建用户及权限管理,支持密码加密,虽简单但不持久化,生产环... 目录1. 前言2. 因何选择内存认证?3. 基础配置实战❶ 创建Spring Security配置文件

Spring Security 单点登录与自动登录机制的实现原理

《SpringSecurity单点登录与自动登录机制的实现原理》本文探讨SpringSecurity实现单点登录(SSO)与自动登录机制,涵盖JWT跨系统认证、RememberMe持久化Token... 目录一、核心概念解析1.1 单点登录(SSO)1.2 自动登录(Remember Me)二、代码分析三、

springboot自定义注解RateLimiter限流注解技术文档详解

《springboot自定义注解RateLimiter限流注解技术文档详解》文章介绍了限流技术的概念、作用及实现方式,通过SpringAOP拦截方法、缓存存储计数器,结合注解、枚举、异常类等核心组件,... 目录什么是限流系统架构核心组件详解1. 限流注解 (@RateLimiter)2. 限流类型枚举 (

Java Thread中join方法使用举例详解

《JavaThread中join方法使用举例详解》JavaThread中join()方法主要是让调用改方法的thread完成run方法里面的东西后,在执行join()方法后面的代码,这篇文章主要介绍... 目录前言1.join()方法的定义和作用2.join()方法的三个重载版本3.join()方法的工作原

Redis MCP 安装与配置指南

《RedisMCP安装与配置指南》本文将详细介绍如何安装和配置RedisMCP,包括快速启动、源码安装、Docker安装、以及相关的配置参数和环境变量设置,感兴趣的朋友一起看看吧... 目录一、Redis MCP 简介二、安www.chinasem.cn装 Redis MCP 服务2.1 快速启动(推荐)2.

Spring AI使用tool Calling和MCP的示例详解

《SpringAI使用toolCalling和MCP的示例详解》SpringAI1.0.0.M6引入ToolCalling与MCP协议,提升AI与工具交互的扩展性与标准化,支持信息检索、行动执行等... 目录深入探索 Spring AI聊天接口示例Function CallingMCPSTDIOSSE结束语

Java获取当前时间String类型和Date类型方式

《Java获取当前时间String类型和Date类型方式》:本文主要介绍Java获取当前时间String类型和Date类型方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,... 目录Java获取当前时间String和Date类型String类型和Date类型输出结果总结Java获取