【rabbitMQ】rabbitMQ的入门示例

使用jar:http://mvnrepository.com/artifact/com.rabbitmq/amqp-client/3.6.6

文中这个demo,用高版本会报错。

public class Send {
    private static final String QUEUE_NAME="wj";
    public static void send() throws Exception {
        /**
         * 创建连接连接到MabbitMQ
         */
        ConnectionFactory factory = new ConnectionFactory();
        //设置MabbitMQ所在主机ip或者主机名
        factory.setHost("localhost");
        //创建一个连接
        Connection connection = factory.newConnection();
        //创建一个频道
        Channel channel = connection.createChannel();
        //指定一个队列
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        //发送的消息
        String message = "hello wj!";
        //往队列中发出一条消息
        channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
        System.out.println("发送信息 '" + message + "'");
        //关闭频道和连接
        channel.close();
        connection.close();
    }
}
public class Recv {
    private static final String QUEUE_NAME="wj";
    public static void recv() throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        System.out.println("接收中...");

        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
                    throws IOException {
                String message = new String(body, "UTF-8");
                System.out.println("接收信息 '" + message + "'");
            }
        };
        channel.basicConsume(QUEUE_NAME, true, consumer);
    }

}
import rabbitMq.Recv;
import rabbitMq.Send;

public class Main {
    public static void main(String[] args) throws Exception {
        Send.send();
        Recv.recv();
    }
}

运行结果:

发送信息 'hello wj!'
接收中...
接收信息 'hello wj!'

参考文章:https://blog.csdn.net/lmj623565791/article/details/37607165

官网示例:http://www.rabbitmq.com/tutorials/tutorial-one-java.html

猜你喜欢

转载自blog.csdn.net/heni6560/article/details/82769325