您的位置:首页 > 数据库 > Redis

个人网站的搭建(七)——SpringBoot集成Redis 缓存

2018-06-29 10:27 393 查看
版权声明: https://blog.csdn.net/weixin_42074377/article/details/80852612

一、Redis做缓存的优势

    Redis是一个典型的非关系型数据库。其内部是一个key-value存储系统,比较而言,它支持存储的value类型更多,包括:

  • String(字符串)
  • list(链表)
  • set(集合)
  • zset(sorted set   有序集合)
  • hash(哈希,类似于map)

Redis基于内存运行并支持持久化的NoSql数据库,是当前最热门的数据库之一。

二、理论准备

    感谢 https://www.geek-share.com/detail/2712768007.html

三、实践

    1. 引入依赖包

                <!--Redis 缓存-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

    2. 编辑配置文件  

spring:
redis:
host: localhost
port: 6379
#    password:
database: 1
timeout: 5000
#连接超时时间(毫秒)
pool:
max-idle: 500
#最大空闲连接
min-idle: 0
#最小空闲连接
max-wait: -1
#连接池最大阻塞等待时间
max-active: 8
#连接池最大等待时间(使用负值表示没有限制)

    3. 新建RedisDao访问Redis服务。

@Repository
public class RedisDao {

@Autowired
private StringRedisTemplate template;

public  void setKey(String key,String value){
ValueOperations<String, String> ops = template.opsForValue();
ops.set(key,value,30, TimeUnit.SECONDS);//表示30秒过期

}

public String getValue(String key){
ValueOperations<String, String> ops = this.template.opsForValue();
return ops.get(key);
}
}

    4. 测试

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

@Autowired
RedisDao redisDao;

@Test
public void testSetRedis(){
redisDao.setKey("name","bian");
redisDao.setKey("age","18");
redisDao.setKey("professional","farmers");
System.out.println(redisDao.getValue("name"));
System.out.println(redisDao.getValue("age"));
System.out.println(redisDao.getValue("professional"));
}

@Test
public void TestGetValue(){
System.out.println("==========="+redisDao.getValue("name"));
System.out.println("==========="+redisDao.getValue("age"));
System.out.println("==========="+redisDao.getValue("professional"));
}
}

        执行testSetRedis( )方法,


        30s 以后执行TestGetValue( )方法,

    可见,Redis服务器生效了。

四、感谢

    感谢大牛 https://www.geek-share.com/detail/2704482315.html

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: