package com.yonge.cooleshow.biz.dal.redisson;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RTopic;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Redisson消息发布订阅服务
 */
@Slf4j
@Service
public class RedissonMessageService {

    // 订阅消息通知
    public static final String TOPIC_MESSAGE = "klx:topic:message";
    // 直播在线人数
    public static final String LIVE_ROOM_MEMBER = "klx:delayQueue:liveRoomMember:";
    public static final String LIVE_ROOM_MEMBER_LOCK = "klx:LOCK:liveRoomMember:";

    private final RedissonClient redissonClient;

    @Autowired
    public RedissonMessageService(RedissonClient redissonClient) {

        this.redissonClient = redissonClient;
    }

    /**
     * 订阅消息
     * @param topic 消息主题
     * @param listener MessageListener
     */
    public void subscribe(String topic, MessageListener listener) {
        RTopic messageTopic = redissonClient.getTopic(topic);
        messageTopic.addListener(String.class, (channel, msg) -> listener.onMessage(msg));
    }

    /**
     * 发布消息
     * @param topic 消息主题
     * @param message 消息内容
     */
    public void publish(String topic, String message) {
        RTopic messageTopic = redissonClient.getTopic(topic);
        messageTopic.publish(message);
    }

    /**
     * 消息监听
     */
    public interface MessageListener {
        void onMessage(String message);
    }

}
