|
@@ -0,0 +1,76 @@
|
|
|
+package com.fire.common.redis;
|
|
|
+
|
|
|
+import lombok.extern.slf4j.Slf4j;
|
|
|
+import org.apache.logging.log4j.util.Strings;
|
|
|
+import org.springframework.stereotype.Component;
|
|
|
+import redis.clients.jedis.JedisCluster;
|
|
|
+
|
|
|
+import javax.annotation.PostConstruct;
|
|
|
+import javax.annotation.Resource;
|
|
|
+import java.util.Arrays;
|
|
|
+
|
|
|
+import static com.fire.dto.enums.RedisKey.PRIORITY_QUEUE;
|
|
|
+
|
|
|
+@Slf4j
|
|
|
+@Component
|
|
|
+public class RedisPriorityQueueScript {
|
|
|
+ @Resource
|
|
|
+ private JedisCluster jedisCluster;
|
|
|
+
|
|
|
+ private String runCode = "";
|
|
|
+
|
|
|
+ /*
|
|
|
+ *初始化
|
|
|
+ */
|
|
|
+ @PostConstruct
|
|
|
+ public void initScript() {
|
|
|
+ String slotKey = PRIORITY_QUEUE.key();
|
|
|
+ //LUA脚本
|
|
|
+ String SCRIPT = "local index = KEYS[1]"+
|
|
|
+ " local operating = ARGV[1]" +
|
|
|
+ " local score = ARGV[2]" +
|
|
|
+ " local content = ARGV[3]" +
|
|
|
+ " local res = 0" +
|
|
|
+ " if operating == 'get' then"+
|
|
|
+ " local ks=redis.call('ZRANGE', index, '0', '0')" +
|
|
|
+ " for _, item in ipairs(ks) do" +
|
|
|
+ " res = redis.call('ZREM', index, item)"+
|
|
|
+ " if res > 0 then" +
|
|
|
+ " return item" +
|
|
|
+ " end" +
|
|
|
+ " end" +
|
|
|
+ " elseif operating == 'add' then" +
|
|
|
+ " res = redis.call('ZADD', index, score, content)" +
|
|
|
+ " return res" +
|
|
|
+ " end" +
|
|
|
+ " return nil";
|
|
|
+ if (Strings.isBlank(runCode) || !jedisCluster.scriptExists(runCode, slotKey)) {
|
|
|
+ //redis支持脚本缓存,返回哈希码,后续可以继续用来调用脚本
|
|
|
+ runCode = jedisCluster.scriptLoad(SCRIPT, slotKey);
|
|
|
+ } else {
|
|
|
+ log.info("脚本已加载");
|
|
|
+ }
|
|
|
+ }
|
|
|
+ /*
|
|
|
+ * 获取优先级队列分发订单内容
|
|
|
+ * 返回 null:失败 获取数据:成功
|
|
|
+ */
|
|
|
+ public String getContent() {
|
|
|
+ String priorityQueue = PRIORITY_QUEUE.key();
|
|
|
+ Object res = jedisCluster.evalsha(runCode, Arrays.asList(priorityQueue), Arrays.asList("get","",""));
|
|
|
+ return res.toString();
|
|
|
+ }
|
|
|
+ /*
|
|
|
+ * 添加优先级队列分发订单内容
|
|
|
+ * 1.score 排序序号
|
|
|
+ * 2.content 分发记录类容
|
|
|
+ * 返回 0:覆盖 1:成功
|
|
|
+ */
|
|
|
+ public String addContent(Long score,String content) {
|
|
|
+ String priorityQueue = PRIORITY_QUEUE.key();
|
|
|
+ Object res = jedisCluster.evalsha(runCode, Arrays.asList(priorityQueue), Arrays.asList("add",String.valueOf(score),content));
|
|
|
+ return res.toString();
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+}
|