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());
|
}
|
}
|
}
|