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即可

展开阅读全文

没有更多推荐了,返回首页