2021-01-11

博客围绕Redis展开,但具体内容缺失。Redis是后端开发中常用的技术,可用于缓存等场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.lea.server.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author Fighting
 * @version RedisTemout, v 0.1 2021/1/11 18:29 Fighting
 * @Content
 */
@RestController
@RequestMapping("/time")
public class RedisTemout {

    @Autowired
    public RedisTemplate redisTemplate;

    /**
     * 第一种设置方式,在向redis中设置数据时,提供ttl
     * 重点是直接在设置值的时候就将对应的值设置进去
     * @return
     */
    @RequestMapping("one")
    public String timeOutTest() throws InterruptedException {
        String key = "time:out";
        String value = "time-out";

        ValueOperations strOps = redisTemplate.opsForValue();
        strOps.set(key,value,10L, TimeUnit.SECONDS);

        //设置睡眠5秒
        Thread.sleep(5000);
        Boolean aBoolean = redisTemplate.hasKey(key);
        Object o = strOps.get(key);
        System.out.println("睡眠5秒后,取到的值为"+aBoolean+"value为:"+o);

        //再设置睡眠5秒
        Thread.sleep(5000);
        Boolean bBoolean = redisTemplate.hasKey(key);
        Object o2 = strOps.get(key);
        System.out.println("睡眠5秒后,取到的值为"+bBoolean+"value为:"+o2);

        return "timeOut success...";
    }

    /**
     * 使用redisTemplate.expire()方法来设置指定的值失效
     *
     * @return
     */
    @RequestMapping("/two")
    public String setRedisTimeOutTwo() throws InterruptedException {
        String key = "time:two";
        String value = "time-out";

        ValueOperations strOps = redisTemplate.opsForValue();
        strOps.set(key,value);
        redisTemplate.expire(key,10L,TimeUnit.SECONDS);

        //设置睡眠5秒
        Thread.sleep(5000);
        Boolean aBoolean = redisTemplate.hasKey(key);//使用此方法来判断redis中是来还存在对应的key
        Object o = strOps.get(key);
        System.out.println("睡眠5秒后,取到的值为"+aBoolean+"value为:"+o);

        //再设置睡眠5秒
        Thread.sleep(5000);
        Boolean bBoolean = redisTemplate.hasKey(key);
        Object o2 = strOps.get(key);
        System.out.println("睡眠5秒后,取到的值为["+bBoolean+"],value为:"+o2);
        return "two success..";
    }


}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值