SpringBoot集成redis缓存

1.使用Spring-data包为redis客户端连接工具

在pom文件中添加以下依赖:

    <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

2.添加redis相关配置

在application.properties中添加以下配置

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

3.添加redisTemplate的bean

添加配置类,代码如下:

@Configuration
public class RedisConfig {

    @Autowired
    JedisConnectionFactory jedisConnectionFactory;

    /**
     * @return redisTemplate 相当于xml中的bean
     */
    @Bean
    RedisTemplate<String, Object> redisTemplate(){
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate();
        redisTemplate.setConnectionFactory(jedisConnectionFactory);
        return redisTemplate;
    }

}

4.测试redis是否可用

在test文件中添加以下单元测试内容,如测试通过则redis配置成功:

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

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Test
    public void redisTest(){
        List<String> nameList= new ArrayList<>();
        nameList.add("name1");
        nameList.add("name2211");
        redisTemplate.opsForValue().set("name",  "demoName");
        redisTemplate.opsForValue().set("nameList", nameList);
        Assert.assertEquals(redisTemplate.opsForValue().get("name"), "demoName");
        System.out.printf(redisTemplate.opsForValue().get("nameList").toString());

    }
}
posted @ 2018-06-03 09:31  代码改变世界-Coding  阅读(608)  评论(0编辑  收藏  举报