redis锁等待随机毫秒数拦截和程序自动过期双重机制
上一个操作加了锁,需要等待上一个操作执行完毕之后,才允许当前操作执行,所以当前操作需要执行锁等待处理。
package com.example.core.mydemo.javaDemo;
import java.time.LocalDateTime;
public class RandomTest {
public static void main(String[] args) {
//1秒以内的随机毫秒数
for (int i = 0; i < 10;i++) {
long time = (long) (Math.random() * 1000);
System.out.println("time=" + time);
}
// String redisKey = "myKey:" + dto.getOrdernumber();
// Boolean haskey = stringRedisTemplate.hasKey(redisKey);
Boolean hasKey = true;
LocalDateTime startTime = LocalDateTime.now();
LocalDateTime endTime = startTime.plusSeconds(5);
//已被锁定,直接返回,等待
while (hasKey && (startTime.isBefore(endTime) || startTime.isEqual(endTime)) ) {
try {
long time = (long) (Math.random() * 1000);
Thread.sleep(time);
//重新查询
// haskey = stringRedisTemplate.hasKey(redisKey);
//重新刷新时间
startTime = LocalDateTime.now();
// log.info("判断锁存在,orderNo=[{}],haskey=[{}],waitTime=[{}]",dto.getOrdernumber(),haskey,time);
System.out.println("waitTime="+time+",startTime="+startTime+",endTime="+endTime);
} catch (InterruptedException e) {
// log.error("exceotion:",e);
e.printStackTrace();
}
}
}
}