TaxReceiver.java 2.52 KB
package com.diligrp.tax.boot.receiver;

import com.diligrp.tax.boot.service.TaxReceiveService;
import com.diligrp.tax.central.domain.MessageContext;
import com.diligrp.tax.central.process.ProcessorChain;
import com.diligrp.tax.central.type.SystemType;
import com.diligrp.tax.central.utils.JsonUtils;
import com.rabbitmq.client.Channel;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Optional;

import static com.diligrp.tax.central.queue.TaxAutoPush.*;


/**
 * @Author: zhangmeiyang
 * @CreateTime: 2024-09-02 16:32
 * @Version: todo
 */
@Component
@Slf4j
public class TaxReceiver {

    @Resource
    private TaxReceiveService taxReceiveService;

    @Resource
    private Map<SystemType, ProcessorChain> processorChainMap;

    @RabbitListener(bindings =
    @QueueBinding(
            value = @Queue(value = NORMAL_QUEUE, autoDelete = "false"),
            exchange = @Exchange(value = NORMAL_EXCHANGE),
            key = NORMAL_ROUTING),
            ackMode = "MANUAL"
    )
    @Transactional
    public void receiveMessage(Channel channel, Message message) throws IOException {
        var content = new String(message.getBody(), StandardCharsets.UTF_8);
        log.info("tax-agent收到消息:{}", content);
        MessageContext ctx = null;
        try {
            ctx = JsonUtils.fromJsonString(content, MessageContext.class);
            taxReceiveService.messagePreHandle(ctx);
            var trans = processorChainMap.get(SystemType.from(ctx.getSystemType())).startProcess(ctx);
            taxReceiveService.recordMapping(trans);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            log.info("tax-agent消息处理成功:{}", content);
        } catch (Exception e) {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            Optional.ofNullable(ctx).ifPresentOrElse(c -> taxReceiveService.recordMappingError(e, c), () -> log.error("tax-agent解析错误:", e));
            log.error("tax-agent消息处理失败:", e);
        }
    }
}