package com.service.impl;

import com.rabbitmq.client.*;
import com.service.MqService;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.IOException;

//@Service("MqServiceImpl")
public class MqServiceImpl implements MqService {
    ConnectionFactory connectionFactory;
    Connection connection;
    Channel channel;
    @PostConstruct
    public void init() {
        connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("47.110.156.18");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("semsx");
        connectionFactory.setVirtualHost("/scanmq");
        connectionFactory.setPassword("sczn2017");
        try {
            connection = connectionFactory.newConnection();
            channel = connection.createChannel();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("init");
    }

    @Override
    public void pushRabbitMessage() {
        try {
            // 获取信道
            AMQP.Queue.DeclareOk declareOk = channel.queueDeclare("0503declare", false, false, true, null);
            System.out.println("队列生成成功");
            channel.basicPublish("","0503declare",null,"messageOH".getBytes());
            System.out.println("队列推送消息成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void listenRabbitQueue() {
        DeliverCallback deliverCallback = (tag,message)->{
            System.out.println(new String(message.getBody()));
        };
        CancelCallback cancelCallback = System.out::println;
        try {
            channel.basicConsume("0503declare",true,deliverCallback,cancelCallback);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
