WeiXinEventConsumer.java 4.07 KB
package com.topdraw.mq.consumer;


import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import com.topdraw.mq.domain.SubscribeBean;
import com.topdraw.resttemplate.RestTemplateClient;
import com.topdraw.util.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.time.LocalDate;
import java.util.Map;

/**
 * 微信事件
 */
@Component
@Slf4j
public class WeiXinEventConsumer {

    @Autowired
    private RestTemplateClient restTemplateClient;

    private static final String QR_CODE_URL = "QR_CODE_URL_";

    @Value("#{rabbitMqErrorLogConfig.getWechatError()}")
    private Map<String, String> error;


    /**
     * 关注和取关事件
     * eg:
     * {
     * "appIdMap": "{\"mpId\":\"234\"}",
     * "allFieldsMap":"{\"FromUserName\":\"4343\",\"MsgType\":\"event\",\"Event\":\"unsubscribe\"}"
     * }
     * @param content
     */
    @RabbitHandler
    @RabbitListener(queues = "#{rabbitMqSourceConfig.getWechatQueue()}",
            containerFactory = "#{rabbitMqSourceConfig.getWechatSource()}",
            autoStartup = "#{rabbitMqSourceConfig.getWechatStartUp()}", ackMode = "AUTO")
    @Transactional
    public void subOrUnSubEvent(Channel channel, Message message, String content) throws IOException {
        try {
            log.info("receive wxu subOrUnSub message, content {}", content);
            JSONObject jsonObject = JSONObject.parseObject(content);

            JSONObject map = jsonObject.getJSONObject("appIdMap");
            JSONObject wechatMsg = jsonObject.getJSONObject("allFieldsMap");
            String appid = map.getString("mpId");
            String unionid = map.getString("unionid");

            String openid = wechatMsg.getString("FromUserName");
            String msgType = wechatMsg.getString("MsgType");

            if ("event".equals(msgType)) {
                String event = wechatMsg.getString("Event");
                String eventKey = wechatMsg.getString("EventKey");

                log.info("event ==>> {}", event);

                SubscribeBean subscribeBean = new SubscribeBean();
                subscribeBean.setAppid(appid);
                subscribeBean.setOpenid(openid);
                subscribeBean.setUnionid(unionid);
                subscribeBean.setEventKey(eventKey);

                if (event.equals("subscribe")) {
                    log.info("send subscribe request start");
                    this.restTemplateClient.subscribe(subscribeBean);
                    log.info("send subscribe request end ");
                }

                if (event.equals("unsubscribe")) {
                    log.info("send unsubscribe request start");
                    this.restTemplateClient.unsubscribe(subscribeBean);
                    log.info("send unsubscribe request end");
                }

//                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            }

        } catch (Exception e) {
            log.error("WXSubscribeConsumer || subOrUnSub msg error || {} || {}", content, e.getMessage());

            channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);

            if (MapUtils.isNotEmpty(error)) {
                String errorStart = this.error.get("start");

                if (errorStart.equalsIgnoreCase("true")) {
                    String fileName = this.error.get("fileName")+"_"+LocalDate.now() +".log";
                    String filePath = this.error.get("filePath");
                    String filePath1 = filePath+fileName;
                    FileUtil.writeStringToFile2(filePath1, content, e.getMessage());
                }

            }

            e.printStackTrace();
            log.info("ucEventConsumer ====>>>> end");
        }

    }

}