需求
异步响应 前端等待响应 设置超时,
/**
* 开启定时任务判断响应
* 传入redis的key 获取到value后释放
* @param key
* @return
*/
public String result(String key) {
String lock = "";
AtomicReference<String> data = new AtomicReference<>("");
ScheduledExecutorService scheduled = Executors.newScheduledThreadPool(1);
synchronized (lock) {
// 创建定时任务 一秒一次读取key
scheduled.scheduleAtFixedRate(
() -> {
String s = redisTemplate.opsForValue().get(key);
if (s != null) {
data.set(s);
lock.notify();
scheduled.shutdownNow();
}
}, 0, 1, TimeUnit.SECONDS
);
try {
// 设置等待时间过期 过期后停止定时任务
lock.wait(5000);
scheduled.shutdownNow();
} catch (Exception e) {
log.error(e.getMessage());
scheduled.shutdownNow();
}
}
return data.get();
}