GetResponse.java 2.7 KB
package com.tianbo.analysis.rabbitmq;

import com.rabbitmq.client.*;
import com.tianbo.util.RabitMq.MqResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
import java.util.regex.*;

/**
 * 获取MQ队列信息并保存到本地存储文件夹
 */
@Slf4j
public class GetResponse extends DefaultConsumer {

    private MqResponse mqResponse;

    private String receptDir;

    private  static GetResponse getResponse;

    public GetResponse(Channel channel) {
        super(channel);
    }
    public GetResponse(Channel channel,String dir) {
        super(channel);
        this.receptDir = dir;
    }
    /**
     * 处理回来的信息
     * @param consumerTag
     * @param envelope
     * @param properties
     * @param body
     * @throws IOException
     */
    @Override
    public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
//        System.err.println("-----------consume message----------");
//        System.err.println("consumerTag: " + consumerTag);
//        System.err.println("envelope: " + envelope);
//        System.err.println("properties: " + properties);
//        System.err.println("body: " + new String(body));
        this.mqResponse = new MqResponse(consumerTag,envelope,properties,new String(body, StandardCharsets.UTF_8));
        log.info("-----------获取到报文----------\n{}",mqResponse.getContent());
        writeToReadDir(mqResponse.getContent());

        //写入回执目录
    }

    public void writeToReadDir(String content)throws  IOException{
        if(content !=null && !content.isEmpty()){
            //todo:下边过去xml文件报头代码在TCS服务器上部署的时候最好去掉.这段过滤代码是为了能转发到IMF
            content = content.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>","");
            //查找报文中的messageid作为文件名
            String pattern = "<MessageID>(\\w+)</MessageID>";
            Pattern r = Pattern.compile(pattern);
            Matcher matcher = r.matcher(content);
            String fileName  = this.receptDir + UUID.randomUUID().toString()+".xml";
            //新舱单部署要去掉下面更改名称代码
//            if (matcher.find()){
//                fileName = this.receptDir+ matcher.group(1)+".xml";
//            }
            log.info("-----------{}报文保存成功----------",fileName);
            File fileToDirectory = new File(fileName);
            FileUtils.writeStringToFile(fileToDirectory,content,"UTF-8");
        }

    }

}