/*
 * Copyright (c) 2023 codvision.com All Rights Reserved.
 */

package com.codvision.mqcore.service.impl;

import com.codvision.mqcore.bean.CommonMessage;
import com.codvision.mqcore.service.MQSender;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;

/**
 * 消息队列redis实现
 *
 * @author lingee
 * @date 2023/8/22
 */
@Slf4j
public class MQSenderByRedis implements MQSender {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private ObjectMapper objectMapper;

    public static final String DELAYED_QUEUE_MSG_PREFIX = "delayed:";

    @Override
    public void sendMessage(String queueName, CommonMessage commonMessage) {
        try {
            String msg = objectMapper.writeValueAsString(commonMessage);
            log.info("【MQ消息生产者】queueName:{},message:{}", queueName, msg);
            sendMessage(queueName, commonMessage);
        } catch (Exception e) {
            log.error("【MQ消息生产者】发送消息失败", e);
            throw new RuntimeException(e.getMessage());
        }
    }

    @Override
    public void sendMessage(String queueName, Object message) {
        try {
            log.info("【MQ消息生产者】queueName:{},message:{}", queueName, message);
            redisTemplate.convertAndSend(queueName, message);
        } catch (Exception e) {
            log.error("【MQ消息生产者】发送消息失败", e);
            throw new RuntimeException(e.getMessage());
        }
    }

    @Override
    public void sendDelayMessage(String queueName, Object message, long delaySeconds) {
        try {
            String msg = objectMapper.writeValueAsString(message);
            log.info("【MQ延时消息生产者】queueName:{},message:{},delaySeconds:{}", queueName, msg, delaySeconds);
            String key = DELAYED_QUEUE_MSG_PREFIX + queueName;
            redisTemplate.opsForZSet().add(key, message, System.currentTimeMillis() + delaySeconds * 1000);
        } catch (Exception e) {
            log.error("【MQ延时消息生产者】发送延时消息失败", e);
            throw new RuntimeException(e.getMessage());
        }
    }
}
