redis中的Expire命令用於設置 key 的過期時間,key 過期後將不再可用。不過有些變量我們不需要設置到redis中,只要存到本地就可以了,也需要過期時間,下面是我的實現邏輯,可供大家參考。
1、實現
package com.spring.pro.model;
/**
* @Title: ExpireModel.java
* @ProjectName com.spring.pro.jdk.variable.expire
* @Description:
* @author ybwei
* @date 2019年12月25日 上午10:43:23
*/
public class ExpireModel<T> {
/**
* 值
*
* @author ybwei
*/
private T value;
/**
* 值設置時間(時間戳,毫秒)
*
* @author ybwei
*/
private Long setTime;
/**
* 過期時長(毫秒)
*
* @author ybwei
*/
private Long expireTime;
/**
* @param value
* @param expireTime
*/
public ExpireModel(T value, Long expireTime) {
super();
this.value = value;
this.expireTime = expireTime;
this.setTime = System.currentTimeMillis();
}
/**
* @Description:
* @return
* @Author: ybwei
* @Date: 2019年12月25日 上午10:48:16
*/
public T getValue() {
T result = null;
if (System.currentTimeMillis() - this.setTime <= this.expireTime) {
result = this.value;
}
return result;
}
}
2、測試
/**
* @throws InterruptedException
* @Description:
* @Author: ybwei
* @Date: 2019年12月25日 上午10:53:14
*/
@Test
public void testExpire() throws InterruptedException {
// 失效時間1秒
ExpireModel<String> em = new ExpireModel<>("aa", 1000L);
log.info("value:{}", em.getValue());
// 休眠時間2秒
TimeUnit.SECONDS.sleep(2);
log.info("value:{}", em.getValue());
}
結果展示:
[INFO ] 2019-12-25 11:32:46.680 [main] com.spring.pro.test.model.ExpireTest - value:aa
[INFO ] 2019-12-25 11:32:48.692 [main] com.spring.pro.test.model.ExpireTest - value:null
3、接口
package com.spring.pro.controller;
import javax.annotation.PostConstruct;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.spring.pro.model.ExpireModel;
/**
* @Title: IndexController.java
* @ProjectName com.spring.pro.jdk.variable.expire
* @Description:
* @author ybwei
* @date 2019年12月25日 上午11:35:09
*/
@RestController
public class IndexController {
private ExpireModel<String> em = null;
/**
* 失效時間(2秒)
*
* @author ybwei
*/
private Long expireTime = 10 * 1000L;
private int index = 0;
/**
* @Description:
* @Author: ybwei
* @Date: 2019年12月25日 上午11:14:58
*/
@PostConstruct
public void init() {
em = new ExpireModel<String>("aa", expireTime);
}
/**
* @Description:
* @return
* @Author: ybwei
* @Date: 2019年12月25日 上午11:18:22
*/
@GetMapping("/getValue")
public String getValue() {
String value = em.getValue();
if (value == null) {
value="bb" + index;
em = new ExpireModel<String>(value, expireTime);
index++;
}
return value;
}
}