Administrator
2026-08-13 696aae63b18f8a84f2c81955af7b25900704daf6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package com.xcong.excoin.modules.gateApi;
 
import com.xcong.excoin.configurations.RabbitMqConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;
 
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.nio.charset.StandardCharsets;
 
/**
 * JAR 启动时动态创建专属命令队列 QUEUE_GATE_CMD_{apiKeyMd5}
 */
@Slf4j
@Component
@DependsOn("gateWebSocketClientManager")
public class CommandQueueInitializer {
 
    @Resource
    private AmqpAdmin amqpAdmin;
 
    @Resource
    private GateWebSocketClientManager manager;
 
    private volatile String queueName;
 
    @PostConstruct
    public void init() {
        try {
            // manager.config 此时已由 Manager 的 @PostConstruct 加载完成
            String apiKey = manager.getConfig().getApiKey();
            String apiKeyMd5 = md5(apiKey);
            String routingKey = "cmd." + apiKeyMd5;
            queueName = "QUEUE_GATE_CMD_" + apiKeyMd5;
 
            DirectExchange exchange = new DirectExchange(RabbitMqConfig.EXCHANGE_GATE);
            Queue queue = new Queue(queueName, true, false, true); // durable, non-exclusive, auto-delete
            Binding binding = BindingBuilder.bind(queue).to(exchange).with(routingKey);
 
            amqpAdmin.declareQueue(queue);
            amqpAdmin.declareBinding(binding);
 
            log.info("[Gate] 命令队列已注册, queue={}, routingKey={}", queueName, routingKey);
        } catch (Exception e) {
            log.error("[Gate] 命令队列注册失败, 策略启停指令将无法接收", e);
            queueName = null;
        }
    }
 
    /** 返回队列名,供 @RabbitListener 引用 */
    public String getQueueName() {
        return queueName;
    }
 
    private static String md5(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] digest = md.digest(input.getBytes(StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder();
            for (byte b : digest) sb.append(String.format("%02x", b));
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            return Integer.toHexString(input.hashCode());
        }
    }
}