package com.tuoheng.admin.websocket.listener;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;

import javax.websocket.Session;
import java.io.IOException;

/**
 * @author: ww
 * @create: 2023/2/06
 * @description: 创建消息订阅监听者类
 **/
@Slf4j
@Component
public class RedisMessageListener implements MessageListener {

    /**
     * websocket客户端连接会话对象
     */
    private Session session;

    public Session getSession() {
        return session;
    }

    public void setSession(Session session) {
        this.session = session;
    }

    @Override
    public void onMessage(Message message, byte[] bytes) {
        String msg = new String(message.getBody());
        if (session != null && session.isOpen()) {
            try {
                session.getBasicRemote().sendText(msg);
            } catch (IOException e) {
                log.error("RedisSubListener消息订阅监听异常：" + e.getMessage());
            }
        }
    }
}