package com.elab.spring.intercept;

import com.aliyun.openservices.ons.api.SendResult;
import com.elab.mq.model.MessageModel;
import com.elab.mq.msg.ProducerInterceptor;
import com.elab.mq.utils.RocketMonitorUtils;
import com.elab.redis.CacheTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @Module rmq拦截器
 * @Description 基于缓存实现
 * @Author liukaixiong
 * @Date 2020/12/30 17:25
 */
public class RMQCacheProducerInterceptor implements ProducerInterceptor {

    /**
     * 所有客户端共用这一个唯一编号
     */
    private String defaultPrefix = "RMQProducer:index";

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private CacheTemplate cacheTemplate;

    @Override
    public boolean check(MessageModel messageModel, String groupName) {
        // 由于多个客户端发送，如果区分开的话就得维护多个
        String cacheKey = getCacheKey();
        Long producerId = cacheTemplate.string().increment(cacheKey, 1);
        messageModel.setProducerId(producerId.toString());
        return true;
    }

    @Override
    public void success(MessageModel messageModel, String groupName, SendResult result) {
        logger.debug("业务处理成功,携带的消息唯一编号:" + messageModel.getProducerId());
    }

    @Override
    public void error(MessageModel messageModel, String groupName, Throwable e) {
        RocketMonitorUtils.sendProducerMonitorData(messageModel, -1, -1L, e);
        logger.debug("业务处理失败,携带的消息唯一编号:" + messageModel.getProducerId());
    }

    private String getCacheKey() {
        return defaultPrefix;
    }
}
