- 添加[DisallowConcurrentExecution]属性
- 执行方法时,添加Redis锁
参考如下:
/// <summary> /// 添加 DisallowConcurrentExecution属性 /// 一次只执行一个job,禁止多个job运行 /// </summary> [DisallowConcurrentExecution] public class AutoPass : BaseJob { private readonly ILogger<AutoPass> _logger; public IDatabase _redisDb; private RedisOperate redisHelper; PostgreDbContext _postgreDbContext; public AutoPass(ILogger<AutoPass> logger, IDatabase database, PostgreDbContext postgreDbContext) { _logger = logger; _redisDb = database; redisHelper = new RedisOperate(_redisDb); _postgreDbContext = postgreDbContext; } public override Task ExecuteMethod(IJobExecutionContext context) { _logger.LogError($"AutoPass Execute start..."); return Task.Run(() => { //自动审核逻辑 AutoCheck(); }); } /// <summary> ///自动审核逻辑 /// </summary> private void AutoCheck() { List<string> statusLog = new List<string>(); try { //redis 记录 if (!redisHelper.ActionExecuting("autoverified")) { _logger.LogError($"{DateTime.Now}:AutoCheck 正在批量审核,请稍后再试"); return; } // 业务代码******************** //释放 redis redisHelper.ActionExecuted("autoverified"); _logger.LogError($"{DateTime.Now}:AutoCheck 释放 redis key"); } catch (Exception ex) { //释放 redis redisHelper.ActionExecuted("autoverified"); _logger.LogError($"Error,Message:{ex.Message},StackTrace:{ex.StackTrace}"); } } }
/// <summary> /// 请求开始记录redis,并返回可否继续执行 true:可继续执行 false:不可继续执行 /// </summary> /// <param name="key"></param> /// <returns></returns> public bool ActionExecuting(string key) { var result = _redisDb.HashExistsAsync(key, true); if (!result.Result) { _redisDb.HashIncrementAsync(key, true); _redisDb.KeyExpireAsync(key, new TimeSpan(0, 0, 5, 0)); return true; } else { return false; } } /// <summary> /// 请求结算,删除redis记录 /// </summary> /// <param name="key"></param> public void ActionExecuted(string key) { var result = _redisDb.HashExistsAsync(key, true); if (result.Result) { _redisDb.KeyDeleteAsync(key); } }