码迷,mamicode.com
首页 > 其他好文 > 详细

RabbitMQ - Hello World!

时间:2017-10-06 13:55:46      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:stat   rod   blog   oid   system   nbsp   lis   lag   gradle   

添加 gradle依赖complie("com.rabbitmq:amqp-client:5.0.0")

Producer:

    private static void helloWorld() {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        try (Connection connection = factory.newConnection(); Channel channel = connection.createChannel();) {

            channel.queueDeclare(QUEUE_NAME, false, false, false, null);
            String message = "Hello, World!";

            channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
            System.out.println("[x] send ‘" + message + "‘");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

Consumer:

    private static void helloWorld() {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");

        try (Connection connection = factory.newConnection(); Channel channel = connection.createChannel();) {
            channel.queueDeclare(QUEUE_NAME, false, false, false, null);

            System.out.println("[*] Waiting for message");

            Consumer consumer = new DefaultConsumer(channel) {
                @Override
                public void handleDelivery(String consumerFlag, Envelope envelope, AMQP.BasicProperties properties,
                        byte[] body) throws UnsupportedEncodingException {
                    String message = new String(body, "UTF-8");
                    System.out.println("[x] Receive message:‘" + message + "‘");
                }
            };
            channel.basicConsume(QUEUE_NAME, consumer);
            System.out.println("aaaa");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

 

RabbitMQ - Hello World!

标签:stat   rod   blog   oid   system   nbsp   lis   lag   gradle   

原文地址:http://www.cnblogs.com/jmbkeyes/p/7631439.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!