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..";
}
}