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

9 篇文章 0 订阅
8 篇文章 0 订阅

一、Redis做缓存的优势

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

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

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

二、理论准备

    感谢 https://blog.csdn.net/lzl9421na/article/details/76651374

三、实践

    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://blog.csdn.net/forezp/article/details/70991675

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值