Administrator
2026-08-13 9b950b7875bfec96a08983a6db31d2ac9d53e723
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
71
72
package com.xcong.excoin.modules.gateApi;
 
import com.alibaba.fastjson.JSON;
import com.xcong.excoin.configurations.RabbitMqConfig;
import com.xcong.excoin.modules.station.model.GateStatsEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
 
import java.util.UUID;
 
/**
 * JAR 侧 — 统一消息发送器(心跳 / ACK / 策略事件 / Stats)
 */
@Slf4j
@Component
public class StatsEventProducer {
 
    private final RabbitTemplate rabbitTemplate;
 
    /** RabbitTemplate 是 prototype,必须用构造器注入(参考 OrderProducer) */
    @Autowired
    public StatsEventProducer(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
    }
 
    /**
     * 发送心跳 / ACK 到 heartbeat 路由
     */
    public void sendHeartbeat(GateStatsEvent event) {
        send(RabbitMqConfig.EXCHANGE_GATE, RabbitMqConfig.ROUTINGKEY_GATE_HEARTBEAT, event);
    }
 
    /**
     * 发送策略事件到 stats 路由
     */
    public void sendStats(GateStatsEvent event) {
        send(RabbitMqConfig.EXCHANGE_GATE, RabbitMqConfig.ROUTINGKEY_GATE_STATS, event);
    }
 
    private void send(String exchange, String routingKey, GateStatsEvent event) {
        CorrelationData cd = new CorrelationData(event.getEventId());
        rabbitTemplate.convertAndSend(exchange, routingKey, JSON.toJSONString(event), cd);
        log.debug("[StatsProducer] 发送: type={}, apiKeyMd5={}", event.getType(), event.getApiKeyMd5());
    }
 
    // ==================== 便捷工厂方法 ====================
 
    public GateStatsEvent newHeartbeat(String apiKeyMd5, Object payload) {
        return build("HEARTBEAT", apiKeyMd5, payload);
    }
 
    public GateStatsEvent newCmdAck(String apiKeyMd5, Object payload) {
        return build("CMD_ACK", apiKeyMd5, payload);
    }
 
    public GateStatsEvent newStats(String type, String apiKeyMd5, Object payload) {
        return build(type, apiKeyMd5, payload);
    }
 
    private GateStatsEvent build(String type, String apiKeyMd5, Object payload) {
        return GateStatsEvent.builder()
                .eventId(UUID.randomUUID().toString())
                .type(type)
                .apiKeyMd5(apiKeyMd5)
                .timestamp(System.currentTimeMillis())
                .payload(JSON.toJSONString(payload))
                .build();
    }
}