RabbitMQ入门 (二) Hello World 与 工作队列

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zl_momomo/article/details/83022787
 <dependency>
     <groupId>com.rabbitmq</groupId>
     <artifactId>amqp-client</artifactId>
     <version>5.4.2</version>
 </dependency>

Hello World

建立一对一简单通信

//生产者
public class Send {
    private final static String QUEUE_NAME = "hello world";

    public static void main(String[] args) throws Exception{
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.56.128");
        factory.setUsername("admin");
        factory.setPassword("123456");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        String message = "Hello world";
        //第一个参数 为"" 表示使用默认的Exchange
        channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
        System.out.println("[x] Sent '" + message + "'");
        channel.close();
        connection.close();
    }

}
//消费者
public class Recv {
    private static final String QUEUE_NAME = "hello world";

    public static void main(String[] args) throws Exception{
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.56.128");
        factory.setUsername("admin");
        factory.setPassword("123456");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
        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.print(" [x] Received '" + message + "'");
            }
        };
        channel.basicConsume(QUEUE_NAME, true, consumer);



    }
}

Work Queues

建立一对多通信,和上述例子一致,只是开了多个消费者线程。

//生产者
public class NewTask {
    private final static String QUEUE_NAME = "hello";

    public static void main(String[] args) throws Exception{
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.56.128");
        factory.setUsername("admin");
        factory.setPassword("123456");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.queueDeclare(QUEUE_NAME,false,false,false,null);
        String[] messages = new String[]{"First message.", "Second message..",
                "Third message...", "Fourth message....", "Fifth message....."};
        for(String message : messages){
            channel.basicPublish("",QUEUE_NAME,null,message.getBytes());
            System.out.println("[x] Sent " + message);
        }
        channel.close();
        connection.close();
    }

}
//消费者
public class Worker {
    private static final String QUEUE_NAME = "hello";

    private static void doWork(String task) throws InterruptedException{
        for(char ch : task.toCharArray()){
            if(ch == '.'){
                Thread.sleep(1000);
            }
        }
    }

    public static void main(String[] args) throws Exception{
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.56.128");
        factory.setUsername("admin");
        factory.setPassword("123456");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME,false,false,false,null);
        Consumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                super.handleDelivery(consumerTag, envelope, properties, body);
                String message = new String(body,"UTF-8");
                System.out.println(" [X] received " +message);
                try{
                    doWork(message);//模拟长时工作
                }catch (InterruptedException e){
                    e.printStackTrace();
                }finally {
                    System.out.println(" [x] done");
                }

            }
        };
        //公平分发,RabbitMQ同一时刻最多接收一条消息,在一个worker完成之前不会在分消息给它,会把消息分给不那么忙的worker
        int prefetchCount = 1;
        channel.basicQos(prefetchCount);
        //message acknowledged 消息确认标识
        boolean autoAck = true;
        channel.basicConsume(QUEUE_NAME,autoAck,consumer);

    }

}

开启多个worker消费者时,生产者的消息会循环分发

NewTask

[x] Sent First message.
[x] Sent Second message..
[x] Sent Third message...
[x] Sent Fourth message....
[x] Sent Fifth message.....

worker-1

 [X] received First message.
 [x] done
 [X] received Third message...
 [x] done
 [X] received Fifth message.....
 [x] done

worker-2

 [X] received Second message..
 [x] done
 [X] received Fourth message....
 [x] done

参考:RabbitMQ Tutorials

猜你喜欢

转载自blog.csdn.net/zl_momomo/article/details/83022787