|
@@ -0,0 +1,74 @@
|
|
|
+package com.backendsys.modules.sdk.comfyui.service.impl;
|
|
|
+
|
|
|
+import com.backendsys.modules.common.config.redis.utils.RedisUtil;
|
|
|
+import com.backendsys.modules.sdk.comfyui.dao.ComfyuiTaskDao;
|
|
|
+import com.backendsys.modules.sdk.comfyui.entity.ComfyuiTask;
|
|
|
+import com.backendsys.modules.sdk.comfyui.service.ComfyuiTaskService;
|
|
|
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
|
|
+import org.springframework.amqp.rabbit.core.RabbitTemplate;
|
|
|
+import org.springframework.beans.factory.annotation.Autowired;
|
|
|
+import org.springframework.data.redis.core.RedisTemplate;
|
|
|
+import org.springframework.stereotype.Service;
|
|
|
+import org.springframework.transaction.annotation.Transactional;
|
|
|
+
|
|
|
+import java.time.Duration;
|
|
|
+
|
|
|
+@Service
|
|
|
+public class ComfyuiTaskServiceImpl implements ComfyuiTaskService {
|
|
|
+
|
|
|
+ @Autowired
|
|
|
+ private RedisUtil redisUtil;
|
|
|
+ @Autowired
|
|
|
+ private RedisTemplate redisTemplate;
|
|
|
+ @Autowired
|
|
|
+ private RabbitTemplate rabbitTemplate;
|
|
|
+
|
|
|
+ private static final String MASTER_EX = "master.job.exchange";
|
|
|
+ private static final String MASTER_RK = "master.job";
|
|
|
+ private static final String TOKEN_KEY = "user:%s:master_token";
|
|
|
+
|
|
|
+
|
|
|
+ @Autowired
|
|
|
+ private ComfyuiTaskDao comfyuiTaskDao;
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 推送主队列任务
|
|
|
+ * 当用户提交新任务、或某任务执行结束后,都调用它
|
|
|
+ */
|
|
|
+ @Transactional
|
|
|
+ public void tryPushNext(long user_id) {
|
|
|
+ // 1. 如果该用户已在主队列里,直接返回
|
|
|
+ String token_key = String.format(TOKEN_KEY, user_id);
|
|
|
+ if (Boolean.TRUE.equals(redisTemplate.hasKey(token_key))) {
|
|
|
+ return;
|
|
|
+ }
|
|
|
+
|
|
|
+ // 2. 抢令牌(原子)
|
|
|
+ Boolean ok = redisTemplate.opsForValue().setIfAbsent(token_key, "1", Duration.ofMinutes(10));
|
|
|
+ if (!Boolean.TRUE.equals(ok)) {
|
|
|
+ return; // 抢失败(并发极小概率)
|
|
|
+ }
|
|
|
+
|
|
|
+ // 3. 取该用户下一条未进主队列的任务
|
|
|
+ LambdaQueryWrapper<ComfyuiTask> wrapperTask = new LambdaQueryWrapper<>();
|
|
|
+ wrapperTask.eq(ComfyuiTask::getUser_id, user_id);
|
|
|
+ wrapperTask.eq(ComfyuiTask::getIn_master, 0);
|
|
|
+ ComfyuiTask comfyuiTask = comfyuiTaskDao.selectOne(wrapperTask);
|
|
|
+
|
|
|
+ if (comfyuiTask == null) { // 用户已没任务
|
|
|
+ redisTemplate.delete(String.format(TOKEN_KEY, user_id));
|
|
|
+ return;
|
|
|
+ }
|
|
|
+
|
|
|
+ // 4. 打标 (进主队列)
|
|
|
+ ComfyuiTask entity = new ComfyuiTask();
|
|
|
+ entity.setIn_master(1);
|
|
|
+ comfyuiTaskDao.update(entity, wrapperTask);
|
|
|
+ comfyuiTask.setIn_master(1);
|
|
|
+
|
|
|
+ // 5. 发消息
|
|
|
+ rabbitTemplate.convertAndSend(MASTER_EX, MASTER_RK, comfyuiTask);
|
|
|
+
|
|
|
+ }
|
|
|
+
|
|
|
+}
|