Springboot整合Redis三种模式的连接方式

Springboot整合Redis三种模式的连接方式

写在前面

本文只是简单整理,并没有过多研究,所以难免有纰漏,还请大家指出。

环境介绍

机器 10.3.50.182
Springboot 2.0.3.RELEASE
Redis redis-4.0.1

maven 依赖

	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-data-redis</artifactId>
	</dependency>
	<dependency>
		<groupId>redis.clients</groupId>
		<artifactId>jedis</artifactId>
		<version>2.9.0</version>
	</dependency>

redis连接

standalone模式

默认配置

配置信息

application.properties中的配置如下(具体配置根据自身情况)

spring.redis.database=3
spring.redis.host=10.3.50.182
spring.redis.port=27000
spring.redis.password=RedisPass
spring.redis.jedis.pool.max-wait=3600
spring.redis.jedis.pool.max-active=1
spring.redis.jedis.pool.max-idle=1
spring.redis.jedis.pool.min-idle=1
spring.redis.timeout=3600
代码调用

在需要使用的类中直接注入RedisTemplate即可

	@Resource
	private RedisTemplate<String, String> redisTemplate;

自定义配置

配置信息

application.properties中的配置如下(具体配置根据自身情况)

#### Server
spring.redis.password=RedisPass
spring.redis.host=10.3.50.182
spring.redis.port=27000
spring.redis.jedis.pool.max-wait=3600
spring.redis.jedis.pool.max-active=1
spring.redis.jedis.pool.max-idle=1
spring.redis.jedis.pool.min-idle=1
spring.redis.timeout=3600
### Redis Server db user
spring.redis.user.database=15
spring.redis.basic.database=14
spring.redis.auction.database=13
spring.redis.default.database=12
代码调用

不同的库,配置不同的RedisTemplate实例

import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class DefaultRedisConfig  {
    @Value("${spring.redis.user.database}")
    private int userDB;
    @Value("${spring.redis.basic.database}")
    private int basicDB;
    @Value("${spring.redis.auction.database}")
    private int auctionDB;
    @Value("${spring.redis.default.database}")
    private int defaultDB;
    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.port}")
    private int port;
    @Value("${spring.redis.password}")
    private String pwd;


    public JedisConnectionFactory defaultRedisConnectionFactory(int db){
        return getJedisConnectionFactory(db, host, port, pwd);
    }

    private JedisConnectionFactory getJedisConnectionFactory(int dbIndex, String host, int port, String pwd) {
        RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
        redisStandaloneConfiguration.setDatabase(dbIndex);
        redisStandaloneConfiguration.setHostName(host);
        redisStandaloneConfiguration.setPort(port);
        redisStandaloneConfiguration.setPassword(RedisPassword.of(pwd));
        return new JedisConnectionFactory(redisStandaloneConfiguration);
    }

    public RedisTemplate defaultRedisTemplate(int db){
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new FastJsonRedisSerializer(Object.class));
        redisTemplate.setValueSerializer(new FastJsonRedisSerializer(Object.class));
        redisTemplate.setConnectionFactory(defaultRedisConnectionFactory(db));
        return redisTemplate;
    }

    @Bean(name = "userRedisTemplate")
    public RedisTemplate userRedis() {
        return defaultRedisTemplate(userDB);
    }

    @Bean(name = "basicRedisTemplate")
    public RedisTemplate basicRedis() {
        return defaultRedisTemplate(basicDB);
    }

    @Bean(name = "auctionRedisTemplate")
    public RedisTemplate auctionRedis() {
        return defaultRedisTemplate(auctionDB);
    }

    @Bean(name = "redisTemplate")
    public RedisTemplate redis() {
        return defaultRedisTemplate(defaultDB);
    }

}

使用的时候根据需要注入不同的RedisTemplate实例即可,如下:

	@Resource(name = "auctionRedisTemplate")
	private RedisTemplate<String, String> auctionRedisTemplate;

sentinel模式(哨兵模式)

配置信息

#### Server
spring.redis.password=RedisPass
spring.redis.host=10.3.50.182
spring.redis.database=15
spring.redis.jedis.pool.max-wait=3600
spring.redis.jedis.pool.max-active=1
spring.redis.jedis.pool.max-idle=1
spring.redis.jedis.pool.min-idle=1
spring.redis.timeout=3600
### Redis Server db user
spring.redis.user.database=15
spring.redis.basic.database=14
spring.redis.auction.database=13
spring.redis.default.database=12
### Redis Sentinel
spring.redis.sentinel.master=masterTest
spring.redis.sentinel.nodes=10.3.50.182:17003,10.3.50.182:17004,10.3.50.182:17005

代码调用

import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.data.redis.connection.RedisSentinelConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;

@Configuration
public class DefaultRedisConfig  {
    @Value("${spring.redis.user.database}")
    private int userDB;
    @Value("${spring.redis.basic.database}")
    private int basicDB;
    @Value("${spring.redis.auction.database}")
    private int auctionDB;
    @Value("${spring.redis.default.database}")
    private int defaultDB;
    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.password}")
    private String pwd;
    @Value("${spring.redis.sentinel.master}")
    private String master;
    @Value("${spring.redis.sentinel.nodes}")
    private String nodes;

    @Bean
    public JedisPoolConfig jedisPoolConfig() {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        // 最大建立连接等待时间
        jedisPoolConfig.setMaxWaitMillis(3600);
        // 逐出连接的最小空闲时间 默认1800000毫秒(30分钟)
//        jedisPoolConfig.setMinEvictableIdleTimeMillis(1800000);
        // 每次逐出检查时 逐出的最大数目 如果为负数就是 : 1/abs(n), 默认3
        jedisPoolConfig.setNumTestsPerEvictionRun(3);
        // 逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认-1
        jedisPoolConfig.setTimeBetweenEvictionRunsMillis(-1);
        // 是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个
        jedisPoolConfig.setTestOnBorrow(true);
        // 在空闲时检查有效性, 默认false
        jedisPoolConfig.setTestWhileIdle(false);
        return jedisPoolConfig;
    }

    public JedisConnectionFactory defaultRedisConnectionFactory(int db){
        return getJedisConnectionFactory(db, nodes, master, pwd);
    }

    private JedisConnectionFactory getJedisConnectionFactory(int db, String nodes, String master, String pwd) {
        String[] split = nodes.split(",");
        RedisSentinelConfiguration redisSentinelConfiguration = new RedisSentinelConfiguration();
        for (int i = 0; i < split.length; i++) {
            String[] node = split[i].split(":");
            RedisNode redisNode = new RedisNode(node[0], Integer.parseInt(node[1]));
            redisNode.setName(master);
            redisSentinelConfiguration.addSentinel(redisNode);
        }
        redisSentinelConfiguration.setDatabase(db);
        redisSentinelConfiguration.setMaster(master);
        redisSentinelConfiguration.setPassword(RedisPassword.of(pwd));
        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(redisSentinelConfiguration);
		 //TODO :重要
        jedisConnectionFactory.afterPropertiesSet();

        return jedisConnectionFactory;
    }

    public RedisTemplate defaultRedisTemplate(int db){
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new FastJsonRedisSerializer(Object.class));
        redisTemplate.setValueSerializer(new FastJsonRedisSerializer(Object.class));
        redisTemplate.setConnectionFactory(defaultRedisConnectionFactory(db));
        return redisTemplate;
    }

    @Bean(name = "userRedisTemplate")
    public RedisTemplate userRedis() {
        return defaultRedisTemplate(userDB);
    }

    @Bean(name = "basicRedisTemplate")
    public RedisTemplate basicRedis() {
        return defaultRedisTemplate(basicDB);
    }

    @Bean(name = "auctionRedisTemplate")
    public RedisTemplate auctionRedis() {
        return defaultRedisTemplate(auctionDB);
    }

    @Bean(name = "redisTemplate")
    public RedisTemplate redis() {
        return defaultRedisTemplate(defaultDB);
    }

}

cluster模式(集群模式)

配置信息

spring.redis.host=10.3.50.182
spring.redis.password=RedisPass
spring.redis.jedis.pool.max-wait=3600
spring.redis.jedis.pool.max-active=1
spring.redis.jedis.pool.max-idle=1
spring.redis.jedis.pool.min-idle=1
spring.redis.timeout=3600
spring.redis.cluster.nodes=10.1.2.159:27001,10.1.2.159:27002,10.1.2.159:27003,10.1.2.159:27004,10.1.2.159:27005,10.1.2.159:27006
# 设置为0可以让master宕机后,slave马上成为master
spring.redis.cluster.max-redirects=5
spring.redis.cluster.timeout=5000

代码调用

import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.MapPropertySource;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class DefaultRedisConfig {
    @Value("${spring.redis.database}")
    private int db;
    @Value("${spring.redis.cluster.nodes}")
    private String nodes;
    @Value("${spring.redis.password}")
    private String pwd;
    @Value("${spring.redis.cluster.max-redirects}")
    private int redirects;


    @Bean
    public JedisPoolConfig jedisPoolConfig() {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        // 最大建立连接等待时间
        jedisPoolConfig.setMaxWaitMillis(3600);
        // 逐出连接的最小空闲时间 默认1800000毫秒(30分钟)
//        jedisPoolConfig.setMinEvictableIdleTimeMillis(1800000);
        // 每次逐出检查时 逐出的最大数目 如果为负数就是 : 1/abs(n), 默认3
        jedisPoolConfig.setNumTestsPerEvictionRun(3);
        // 逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认-1
        jedisPoolConfig.setTimeBetweenEvictionRunsMillis(-1);
        // 是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个
        jedisPoolConfig.setTestOnBorrow(true);
        // 在空闲时检查有效性, 默认false
        jedisPoolConfig.setTestWhileIdle(false);
        return jedisPoolConfig;
    }


    public JedisConnectionFactory defaultRedisConnectionFactory(){
        return getJedisConnectionFactory(nodes, pwd, redirects);
    }

    private JedisConnectionFactory getJedisConnectionFactory(String nodes, String pwd, int redirects) {
        Map<String, Object> source = new HashMap<>();
        source.put("spring.redis.cluster.nodes", nodes);
        source.put("spring.redis.cluster.timeout", 5000);
        RedisClusterConfiguration conf = new RedisClusterConfiguration(new MapPropertySource("RedisClusterConfiguration", source));
        conf.setPassword(RedisPassword.of(pwd));
        conf.setMaxRedirects(redirects);
        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(conf);
        // TODO: 下面这步很重要
        jedisConnectionFactory.afterPropertiesSet();
        return jedisConnectionFactory;
    }

    public RedisTemplate defaultRedisTemplate(){
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new FastJsonRedisSerializer<>(Object.class));
        redisTemplate.setValueSerializer(new FastJsonRedisSerializer<>(Object.class));
        redisTemplate.setConnectionFactory(defaultRedisConnectionFactory());
        return redisTemplate;
    }

    @Bean(name = "redisTemple")
    public RedisTemplate redisTemplate() {
        return defaultRedisTemplate();
    }
}

调用时直接注入RedisTemplate即可

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在使用Spring Boot整合Redis时,可以实现主从复制的配置。主从复制是指在Redis集群中,有一个主节点负责处理写操作,并且将写操作同步到多个从节点上。这种配置可以提高系统的读取性能和可用性。 要实现Spring Boot整合Redis的主从复制,可以按照以下步骤进行操作: 1. 首先,在pom.xml文件中引入相关依赖。可以使用Spring Boot提供的`spring-boot-starter-data-redis`依赖来简化配置,同时需要引入`commons-pool2`依赖以支持连接池: ``` <!-- redis --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <!-- spring2.X集成redis所需common-pool2 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> <version>2.6.0</version> </dependency> ``` 2. 然后,在application.properties或application.yml文件中进行相关的配置。可以配置主节点和从节点的连接信息,例如: ``` # Redis主节点配置 spring.redis.host=主节点地址 spring.redis.port=主节点端口 spring.redis.password=主节点密码 # Redis从节点配置 spring.redis.sentinel.master=主节点名称 spring.redis.sentinel.nodes=从节点地址1,从节点地址2,从节点地址3 ``` 3. 最后,在Spring Boot的配置类中进行Redis的相关配置。可以使用`RedisSentinelConfiguration`类来配置主从节点的连接信息,例如: ``` @Configuration public class RedisConfig { @Value("${spring.redis.sentinel.master}") private String master; @Value("${spring.redis.sentinel.nodes}") private String nodes; @Bean public RedisSentinelConfiguration redisSentinelConfiguration() { RedisSentinelConfiguration configuration = new RedisSentinelConfiguration(); String[] nodeArray = nodes.split(","); for (String node : nodeArray) { String[] hostPort = node.split(":"); String host = hostPort<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [springboot整合redis代码](https://download.csdn.net/download/qq_34531925/10412347)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [redis整合springboot](https://blog.csdn.net/weixin_45397764/article/details/118828384)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [Java企业报表管理系统源码](https://download.csdn.net/download/m0_55416028/88269629)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值