設置一個考試,給考試上鎖
reditsUtil緩存工具類
package com.rc.common.redis.utils;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import com.rc.common.mapper.JsonMapper;
import com.rc.common.utils.SpringContextHolder;
import com.rc.common.utils.StringUtils;
public class RedisUtil {
public static RedisTemplate<String, Object> redisTemplate;
public static RedisTemplate<String, Object> getTmp() {
if (redisTemplate == null) {
redisTemplate = SpringContextHolder.getBean("redisSOTemplate");
}
return redisTemplate;
}
// =============================common============================
/**
* redis分佈式鎖
* @param key
* @param time 秒
* @return
*/
public static boolean setIfAbsent(String key, long time) {
return getTmp().opsForValue().setIfAbsent(key, 1, Duration.ofSeconds(time));
}
/**
*
* 指定緩存失效時間
*
* @param key 鍵
*
* @param time 時間(秒)
*
* @return
*
*/
public static boolean expire(String key, long time) {
try {
if (time > 0) {
getTmp().expire(key, time, TimeUnit.SECONDS);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
*
* 刪除緩存
*
* @param key 可以傳一個值 或多個
*
*/
@SuppressWarnings("unchecked")
public static void del(String... key) {
if (key != null && key.length > 0) {
if (key.length == 1) {
getTmp().delete(key[0]);
} else {
getTmp().delete(CollectionUtils.arrayToList(key));
}
}
}
public static void delAll(String key) {
if (key != null) {
Set<String> kes = getTmp().keys(key);
getTmp().delete(kes);
}
}
}
考試校驗
//考試校驗
public boolean kscheck(String paperId){
String id = RedisUtil.getString(paperId);
if (StringUtils.isBlank(id)) {
ExamPaper paper = MongoUtils.checkGet(paperId, ExamPaper.class, "試卷");
//判斷是否開始考試或者結束考試
//沒開始提示
//結束提示試卷作答結束
//在考試的時間段
try {
//加鎖,設置失效時間爲30秒
if (RedisUtil.setIfAbsent(paperId + "ExamPaper", 30)) {
//設置失效時間,指定緩存失效時間
// DateUtils.pastMinutesByTime(paper.getEndTime()這個方法就是取考試結束時間-當前時間所得到的秒數
RedisUtil.expire(paperId, DateUtils.pastMinutesByTime(paper.getEndTime()));
return true;
}
} catch (Exception e) {
Ast.astFalse("請刷新頁面");
} finally {
//無論怎麼都刪除鎖
RedisUtil.del(paperId + "ExamPaper");
}
} else {
return true;
}
return false;
}
得到考試結束時間-當前時間所得到的秒數的方法,我把它寫在 DateUtils工具類裏了
/**
* 判斷某一時間離當前時間的秒數
*/
public static long pastMinutesByTime(String date) {
long t = parseDate(date).getTime() - new Date().getTime();
return t / 1000;
}