package com.lovecoding.rabbitmq.producer;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.impl.AMQImpl;
import org.junit.jupiter.api.Test;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

@SpringBootTest
class ProducerApplicationTests {

    @Resource
    RabbitTemplate rabbitTemplate;

    /**
     * work queue 模式发送消息
     * @throws InterruptedException
     */
    @Test
    void t1() throws InterruptedException {
        for (int i = 0; i < 100; i++) {
            rabbitTemplate.convertAndSend(
                    "testQueue", "测试消息ID ：" + i );
            Thread.sleep(100);
        }
    }

    /**
     * fanout 模式发送消息
     */
    @Test
    void t2(){
        rabbitTemplate.convertAndSend(
                "com.lc.fanout.demo", "", "广播模式的消息发送" );
    }

    /**
     * direct 模式发送消息
     */
    @Test
    void t3(){
        rabbitTemplate.convertAndSend(
                "com.lc.direct.demo", "北京", "晴转多云" );
    }

    /**
     * direct 模式发送消息
     */
    @Test
    void t4(){
        rabbitTemplate.convertAndSend(
                "com.lc.direct.demo", "哈尔滨", "多云有雷阵雨" );
    }

    @Test
    void t5(){
        rabbitTemplate.convertAndSend(
                "topicExchange", "com.lc.haerbin", "多云" );
    }

    @Test
    void t6(){
        rabbitTemplate.convertAndSend(
                "topicExchange", "com.lc.beijing", "雷阵雨" );
    }

    @Test
    void t7(){
        rabbitTemplate.convertAndSend(
                "topicExchange", "com.lc.shenzhen", "雾霾" );
    }

    @Test
    void t8(){
        for (int i = 0; i < 10; i++) {
            rabbitTemplate.convertAndSend(
                    "deadDirectExchangeDemo", "tianqi", "雾霾" + i );
        }
    }

    /**
     * 手工发送消息
     * @throws IOException
     * @throws TimeoutException
     */
    @Test
    void sendMsg() throws IOException, TimeoutException {
        //创建一个连接
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("localhost");
        connectionFactory.setPort(25672);
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("123456");
        Connection connection = connectionFactory.newConnection();

        //创建一个通道
        Channel channel = connection.createChannel();

        //创建一个队列
        String queueName = "testQueue";
        channel.queueDeclare( queueName, false, false, false, null );

        //推送一个基本消息
        channel.basicPublish( "", queueName,
                null, "Hello MQ".getBytes(StandardCharsets.UTF_8) );

    }

}
