package com.neusoft.smart.pos.mq.rabbitmq;

import java.io.Serializable;
import org.apache.commons.lang3.SerializationUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import com.neusoft.smart.pos.framework.config.RabbitExchangeConfiguration;
import com.neusoft.smart.pos.mq.MQConfig;
import com.neusoft.smart.pos.mq.MqProducer;

@Profile(MQConfig.Impl.RABBIT_MQ)
@Component
public class RabbitMQSender implements MqProducer{
    private static Logger logger = LoggerFactory.getLogger(RabbitMQSender.class);

    @Autowired
    private RabbitExchangeConfiguration configuration;

    /**
     * 发送对象（对象必须定义在common中，且实现Serializable接口。接收端用SerializationUtils.deserialize反序列化）
     * @param exchange 交换机名
     * @param routingKey routingKey
     * @param object 发送的对象
     */
	@Override
    public void sendMessage(String exchange, String routingKey, Serializable object) {
    	logger.info("【消息发送者】发送消息到交换机{}，routingKey为{}，消息内容为: {}", exchange, routingKey, object);
    	byte[] content = SerializationUtils.serialize(object);
    	RabbitTemplate rabbitTemplate = configuration.rabbitTemplate();
    	rabbitTemplate.convertAndSend(exchange, routingKey, content);
    }

    /**
     * 发送字符串
     * @param exchange 交换机名
     * @param routingKey routingKey
     * @param msg 发送的字符串
     */
	@Override
    public void sendMessage(String exchange, String routingKey, String msg) {
    	logger.info("【消息发送者】发送消息到交换机{}，routingKey为{}，消息内容为: {}", exchange, routingKey, msg);
    	RabbitTemplate rabbitTemplate = configuration.rabbitTemplate();
    	rabbitTemplate.convertAndSend(exchange, routingKey, msg);
    }
}