package com.xhpc.wxma.rabbitm;

import com.rabbitmq.client.*;
import com.xhpc.common.util.ConnectionRabbitMQUtil;
import com.xhpc.wxma.socket.OrderNotificationWebSocket;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author yuyang
 * @date 2021/8/11 20:58
 */
@Component
public class RabbitmConsumer implements ApplicationRunner {
    //队列名称
    private final static String NAME="webSocket";

    @Override
    public void run(ApplicationArguments args) throws Exception {
        try {
            // 获取到连接
            Connection connection = ConnectionRabbitMQUtil.getConnection();
            // 2、从连接中创建通道，使用通道才能完成消息相关的操作
            Channel channel = connection.createChannel();
            // 3、声明（创建）队列
            channel.queueDeclare(NAME, false, false, false, null);
            //实现消费方法
            DefaultConsumer consumer = new DefaultConsumer(channel){
                // 获取消息，并且处理，这个方法类似事件监听，如果有消息的时候，会被自动调用
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    String msg = new String(body,"utf-8");
                    String[] split = msg.split("##");
                    OrderNotificationWebSocket.sendMessage(split[0],split[1]);
                }
            };
            channel.basicConsume(NAME, true, consumer);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
