1、引入POM包

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

2、yml中添加连接信息

spring:
  redis:
    database: 0
    host: 127.0.0.1
    port: 6379
    password:     # 密码(默认为空)
    timeout: 6000  # 连接超时时长(毫秒)
    pool:
        max-active: 1000  # 连接池最大连接数(使用负值表示没有限制)
        max-wait: -1      # 连接池最大阻塞等待时间(使用负值表示没有限制)
        max-idle: 10      # 连接池中的最大空闲连接
        min-idle: 5       # 连接池中的最小空闲连接    
    order:
        host: 127.0.0.1
        port: 6379
        password: 
        database: 1

3、增加Redis连接工厂

package com.tyteam.base.config;

import org.apache.commons.lang.StringUtils;
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.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;

import redis.clients.jedis.JedisPoolConfig;

@Configuration
public class RedisConfig {

	 //order
    @Value("${spring.redis.order.host}")
    private String orderHost;
 
    @Value("${spring.redis.order.port}")
    private String orderPort;
 
    @Value("${spring.redis.order.password}")
    private String orderPassword;
    
    @Value("${spring.redis.order.database}")
    private Integer orderDatabase;
 
 
    private static final int MAX_IDLE = 200; //最大空闲连接数
    private static final int MAX_TOTAL = 1024; //最大连接数
    private static final long MAX_WAIT_MILLIS = 10000; //建立连接最长等待时间
 
 
    //配置工厂
    public RedisConnectionFactory connectionFactory(String host, int port, String password, int maxIdle,
                                                    int maxTotal, long maxWaitMillis, int index) {
        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();
        jedisConnectionFactory.setHostName(host);
        jedisConnectionFactory.setPort(port);
 
        if (!StringUtils.isEmpty(password)) {
            jedisConnectionFactory.setPassword(password);
        }
 
        if (index != 0) {
            jedisConnectionFactory.setDatabase(index);
        }
 
        jedisConnectionFactory.setPoolConfig(poolConfig(maxIdle, maxTotal, maxWaitMillis, false));
        jedisConnectionFactory.afterPropertiesSet();
        return jedisConnectionFactory;
    }
 
    //连接池配置
    public JedisPoolConfig poolConfig(int maxIdle, int maxTotal, long maxWaitMillis, boolean testOnBorrow) {
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxIdle(maxIdle);
        poolConfig.setMaxTotal(maxTotal);
        poolConfig.setMaxWaitMillis(maxWaitMillis);
        poolConfig.setTestOnBorrow(testOnBorrow);
        return poolConfig;
    }
    
    @Bean(name = "orderRedisTemplate")
    public RedisTemplate<String, Object> redisOrderTemplate() 
    {
    	RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
        template.setConnectionFactory(
                connectionFactory(orderHost, Integer.parseInt(orderPort), orderPassword, MAX_IDLE, MAX_TOTAL, MAX_WAIT_MILLIS, orderDatabase));
		
        //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
        Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jacksonSeial.setObjectMapper(om);

        // 值采用json序列化
        template.setValueSerializer(jacksonSeial);
        //使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());

        // 设置hash key 和value序列化模式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(jacksonSeial);
        template.afterPropertiesSet();
        
        return template;
    }
}

4、使用2个Redis进行操作

我们在设置session时使用了2个Redis分别存储在了数据库1和数据库2上。

package com.kingteam.session;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * kingteam Session 管理类:负责session的注册、及使用
 * @author 秦晓宇
 * @date: 2020年10月15日 下午6:20:14 
 * @record:
 */
@Service
public class KtSessionService {

	@Autowired
	@Qualifier("redisTemplate")
    protected RedisTemplate<String, Object> redisTemplate;
	
	@Autowired
	@Resource(name = "orderRedisTemplate")
	RedisTemplate<String, Object> orderRedisTemplate;
	
	/**   
	 * @Description: session 过期时间:-1,永久不过期,其他:xxx秒
	 * @author: qin   
	 * @date: 2020年10月18日 上午11:35:48 
	 */
	public static final long sessionExpires = 60*60*24*30;
	
	public enum SessionStatus
	{
		NoToken,
		
	};
	
	
	/** 
	* @Description: 为登录的用户产生UUID token令牌 并以userId作为主键,将token存储到Redis中 
	* @Title: setSession 
	* @param Session void
	* @author qin
	* @date 2020年10月16日上午12:16:12
	*/ 
	public Session setSession(Session session)
	{
		String token = UUID.randomUUID().toString();
		session.setToken(token);
		redisTemplate.opsForValue().set(
			token,							//令牌token
			session, 						//用户上下文信息	
			sessionExpires,					//超时时间
			TimeUnit.SECONDS				//超时的单位定义
		);
		
		orderRedisTemplate.opsForValue().set(token, // 令牌token
				session, // 用户上下文信息
				sessionExpires, // 超时时间
				TimeUnit.SECONDS // 超时的单位定义
		);
				
		return session;
	}
	
	/** 
	* @Description: 使对应的令牌失效 
	* @Title: removeSession 
	* @param token void
	* @author qin
	* @date 2020年10月16日上午12:41:45
	*/ 
	public void removeSession(String token)
	{
		redisTemplate.delete(token);
	}
	
	/** 
	* @Description: 获得用户session 
	* @Title: getSession 
	* @param token
	* @return Session
	* @author qin
	* @date 2020年10月16日上午12:48:09
	*/ 
	public Session getSession(String token)
	{
		return (Session) redisTemplate.opsForValue().get(token);
	}
	
	/** 
	* @Description: 刷新token的时间 
	* @Title: refreshToken 
	* @param token void
	* @author qin
	* @date 2020年10月16日下午3:14:14
	*/ 
	public void refreshToken(String token)
	{
		//System.out.println("KtSessionService:refreshToken = "+token);
		//若传入的token不合法,则不进行token续租
		if(token == null || token.length()!= 36) return;
		try {
			redisTemplate.expire(token,sessionExpires,TimeUnit.SECONDS);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}	
}

5、实操效果

我们在Reids中看到了2条一样的数据,存储成功。

redis-3.0.0连接池 redis连接池有哪些_redis-3.0.0连接池

6、如何驱动更多张数据表

在yml文件中配置其他想写入的表

redis-3.0.0连接池 redis连接池有哪些_redis_02

在如下位置添加新的连接的信息

redis-3.0.0连接池 redis连接池有哪些_多表_03

如下位置添加新的连接工厂,把redisOrderTemplate拷贝下来,改改Bean注解,改改连接的host、port、数据库就行了。该改的地方都用红框画出来了。

redis-3.0.0连接池 redis连接池有哪些_多连接_04

在想使用的地方引入

redis-3.0.0连接池 redis连接池有哪些_多连接_05

在想使用的地方调用一下

redis-3.0.0连接池 redis连接池有哪些_springboot_06