public class OnceExecutor {
private CacheService cacheService;
public OnceExecutor(CacheService cacheService) {
this.cacheService = cacheService;
}
/**
* 通过缓存记录键来支持只允许一次
*
* @param type
* @param id
* @param callable
* @param <T>
* @return
* @throws Exception
*/
public <T> T runOnce(String type, String id, Callable<T> callable) throws Exception {
String key = Constants.REDIS_KEY_PREFIX_WORK + "_" + type + "_" + id;
String value = cacheService.getString(key);
boolean handled = "true".equals(value);
if (!handled) {
T ret = null;
try {
cacheService.setString(key, "true", 5, TimeUnit.MINUTES);
ret = callable.call();
cacheService.setString(key, "true",5, TimeUnit.MINUTES);
} catch (Exception e) {
cacheService.del(key);
}
return ret;
}
return null;
}
}
private OnceExecutor onceExecutor;
@Autowired
public WorkManager(CacheService cacheService) {
onceExecutor = new OnceExecutor(cacheService);
}
public void updateForStudentHandIn(StudentWork studentWork, Work work) throws Exception {
onceExecutor.runOnce("handIn", studentWork.getStudentWorkId(), () -> {
....
return null;
});
}