springboot连接redis并动态切换database(db0到db15)

redis db0到db15

可以理解为数据库表这是redis默认提供的16个表
我们可以把不同的数据存在不同的db上
取得时候可以在不同的db拿到不同类型数据

springboot连接redis

pom.xml文件中引入spring-boot-starter-redis,


    org.springframework.boot
    spring-boot-starter-redis
    1.3.8.RELEASE


添加配置文件application.properties

# Redis数据库索引(默认为0)
spring.redis.database=0  
# Redis服务器地址
spring.redis.host=localhost
# Redis服务器连接端口
spring.redis.port=6379  
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制) 默认 8
spring.redis.lettuce.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
spring.redis.lettuce.pool.max-wait=-1
# 连接池中的最大空闲连接 默认 8
spring.redis.lettuce.pool.max-idle=8
# 连接池中的最小空闲连接 默认 0
spring.redis.lettuce.pool.min-idle=0

测试是否连接成功

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
public class TestCRedis{

    protected static Logger LOGGER = LoggerFactory.getLogger(TestCRedis.class);

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Test
    public void t1(){
        ValueOperations stringStringValueOperations = stringRedisTemplate.opsForValue();
        stringStringValueOperations.set("test","大湿胸");
        String testkey = stringStringValueOperations.get("test");
        LOGGER.info(testkey);
    }

}

运行TestCRedis.t1(),控制台打印“大湿胸”redis连接成功

redis动态切换database

package com.niceteam.web.bm;

import com.niceteam.common.excel.ExcelDownloadUtil;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;

@RunWith(SpringRunner.class)
@SpringBootTest
public class NiceteamWebBasemanagerApplicationTests {


    private static Logger log = LoggerFactory.getLogger(ExcelDownloadUtil.class);
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Test
    public void contextLoads() {

        for (int i = 0; i <= 2; i++) {
            LettuceConnectionFactory lettuceConnectionFactory = (LettuceConnectionFactory) stringRedisTemplate.getConnectionFactory();
            lettuceConnectionFactory.setDatabase(i);
            stringRedisTemplate.setConnectionFactory(lettuceConnectionFactory);
            lettuceConnectionFactory.resetConnection();
            ValueOperations valueOperations = stringRedisTemplate.opsForValue();
            valueOperations.set(i+"",i+"");
            String test = (String) valueOperations.get(i+"");
            log.info(test);
            System.out.println("拿到的数据"+test);
        }
    }

}



springboot连接redis并动态切换database(db0到db15)_第1张图片

你可能感兴趣的:(redis)