③SpringBoot中Redis的使用

本文基于前面的springBoot系列文章进行学习,主要介绍redis的使用。

SpringBoot对常用的数据库支持外,对NoSQL 数据库也进行了封装自动化。

redis介绍

Redis是目前业界使用最广泛的内存数据存储。相比memcached,Redis支持更丰富的数据结构,例如hashes, lists, sets等,同时支持数据持久化。除此之外,Redis还提供一些类数据库的特性,比如事务,HA,主从库。可以说Redis兼具了缓存系统和数据库的一些特性,因此有着丰富的应用场景。本文介绍Redis在Spring Boot中两个典型的应用场景。

如何使用

1、引入 spring-boot-starter-redis

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

2、添加配置文件

# REDIS (RedisProperties)
# Redis数据库索引(默认为0)
spring.redis.database=0 
# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379 
# Redis服务器连接密码(默认为空)
spring.redis.password=  
# 连接池最大连接数(使用负值表示没有限制)
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=300

3、Redis工具类

import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Repository;

@Repository
public class RedisDao {
        @Autowired
        private StringRedisTemplate template;

        /**
         * redis存
         * @param key
         * @param value
         */
        public void setKey(String key,String value){
            ValueOperations<String, String> ops = template.opsForValue();
            ops.set(key,value,1,TimeUnit.MINUTES);//1分钟过期
        }

        /**
         * redis取
         * @param key
         * @return
         */
        public String getValue(String key){
            ValueOperations<String, String> ops = this.template.opsForValue();
            return ops.get(key);
        }
}

4.测试

@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisDaoTest {
        @Test
        public void contextLoads() {
            
        }        

        @Autowired
        private RedisDao redisDao;
        
        @Test
        public void testRedis(){
            redisDao.setKey("name","forezp");
            redisDao.setKey("age","11");
            System.out.println("存到redis中的name为"+redisDao.getValue("name"));
            System.out.println("存到redis中的age为"+redisDao.getValue("age"));
        }
}

 

posted @ 2018-08-06 14:24  shawWey  阅读(247)  评论(0编辑  收藏  举报