您的位置:首页 > 编程语言

通过缓存来使得代码执行一次(防止重复操作)

2017-11-06 09:56 661 查看
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;
});
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐