|
|
@@ -0,0 +1,72 @@
|
|
|
+package com.github.microservice.components.data.mongo.queue.service;
|
|
|
+
|
|
|
+import com.github.microservice.components.data.mongo.mongo.helper.DBHelper;
|
|
|
+import com.github.microservice.components.data.mongo.queue.config.ExecQueueConfig;
|
|
|
+import com.github.microservice.components.data.mongo.queue.dao.ExecQueueDao;
|
|
|
+import com.github.microservice.components.data.mongo.queue.domain.ExecQueue;
|
|
|
+import org.springframework.beans.factory.annotation.Autowired;
|
|
|
+import org.springframework.context.ApplicationEvent;
|
|
|
+import org.springframework.stereotype.Component;
|
|
|
+import org.springframework.util.Assert;
|
|
|
+
|
|
|
+@Component
|
|
|
+public class ExecQueueService {
|
|
|
+
|
|
|
+
|
|
|
+ @Autowired
|
|
|
+ private ExecQueueDao execQueueDao;
|
|
|
+
|
|
|
+ @Autowired
|
|
|
+ private ExecQueueConfig execQueueConfig;
|
|
|
+
|
|
|
+ @Autowired
|
|
|
+ private DBHelper dbHelper;
|
|
|
+
|
|
|
+ // 添加
|
|
|
+ public String add(Object o, int maxTryCount, Class<? extends ApplicationEvent> eventClass) {
|
|
|
+ Assert.state(maxTryCount > 0, "最大尝试次数必须大于0");
|
|
|
+ Assert.notNull(eventClass, "事件不能为空");
|
|
|
+
|
|
|
+ final ExecQueue execQueue = new ExecQueue();
|
|
|
+
|
|
|
+ execQueue.setObject(o);
|
|
|
+ execQueue.setObjectClass(o.getClass());
|
|
|
+ execQueue.setEventClass(eventClass);
|
|
|
+
|
|
|
+ execQueue.setCurrentTryCount(1);
|
|
|
+ execQueue.setMaxTryCount(maxTryCount);
|
|
|
+ execQueue.setStatus(ExecQueue.ExecQueueStatus.Wait);
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+ // 更新下次执行时间
|
|
|
+ this.updateNextExecTime(execQueue);
|
|
|
+
|
|
|
+ this.execQueueDao.save(execQueue);
|
|
|
+
|
|
|
+ return execQueue.getId();
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+ // 删除
|
|
|
+ public void delete(String id) {
|
|
|
+ execQueueDao.deleteById(id);
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 更新下次执行时间
|
|
|
+ */
|
|
|
+ public boolean updateNextExecTime(ExecQueue execQueue) {
|
|
|
+ if (execQueue.getCurrentTryCount() > execQueue.getMaxTryCount()) {
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+ final long sleepTime = execQueueConfig.sleepTime(execQueue.getCurrentTryCount());
|
|
|
+ execQueue.setCurrentTryCount(execQueue.getCurrentTryCount() + 1);
|
|
|
+ execQueue.setNextTime(this.dbHelper.getTime() + sleepTime);
|
|
|
+ execQueue.setStatus(ExecQueue.ExecQueueStatus.Wait);
|
|
|
+ return true;
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+}
|