首页 > 其他 > 详细

RabbitMQ - Hello World!

时间:2017-10-06 13:45:23      阅读:262      评论:0      收藏:0      [点我收藏+]

添加 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!

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!