zoukankan      html  css  js  c++  java
  • RabbitMQ (一)第一个hello world

    RabbitMQ是一个消息中间件,负责消息的接收和投递。它可以从生产者那里接收消息,并且投递到消费者。在这期间,它可以路由、缓存,并且可以根据你给的规则持久化消息。

     图例说明:

    表示生产者 (发信人)

    表示队列 (信箱)

    表示消费者(收信人)

    第一个“hello world” 实例的简单实现:

      

     本实例基于java的实现:

    消息发送者:

     

    import com.rabbitmq.client.*;
    public class ClientSender {
        
    public static void main(String[] args) throws java.io.IOException {
            ConnectionFactory factory
    =new ConnectionFactory();
            factory.setHost(
    "localhost");
            factory.setUsername(
    "guest");
            factory.setPassword(
    "123456");
            factory.setVirtualHost(
    "/");
            Connection conn
    =factory.newConnection();
            Channel channel
    =conn.createChannel();
            String queueName
    ="myqueue";
            channel.queueDeclare(queueName, 
    falsefalsefalse,null);
            String message
    ="hello world"+Math.random();
            channel.basicPublish(
    "",queueName, null,message.getBytes());
            System.out.print(
    "send '"+message+"'");
            channel.close();
            conn.close();

        }
    }

    消息接收者

     

    import com.rabbitmq.client.*;
    public class ClientReceiver {
        
    private final static String queueName="myqueue";
        
    public static void main(String[] args) throws java.io.IOException,java.lang.InterruptedException{
            ConnectionFactory factory
    =new ConnectionFactory();
            factory.setHost(
    "localhost");
            factory.setUsername(
    "guest");
            factory.setPassword(
    "123456");
            Connection conn
    =factory.newConnection();
            Channel channel
    =conn.createChannel();
            channel.queueDeclare(queueName, 
    falsefalsefalsenull);
            System.out.println(
    " [*] Waiting for messages. To exit press CTRL+C");
            QueueingConsumer consumer
    =new QueueingConsumer(channel);
            channel.basicConsume(queueName, 
    true,consumer);
            
    while (true) {
                QueueingConsumer.Delivery delivery
    =consumer.nextDelivery();    
                String message
    =new String(delivery.getBody());
                System.out.println(
    " [x] Received '" + message + "'");
                Thread.sleep(
    100);
            }
        }
    }
  • 相关阅读:
    总结类初始化时的代码执行顺序
    Calcite数据源适配器对时间字段的操作问题
    如何自定义一个Calcite对Tablesaw查询的适配器
    Redis集群 Redis Cluster
    培养代码逻辑
    在线查看office文件的两种方法
    WPF Prism框架合集(9.Dialog)
    WPF Prism框架合集(8.Navigation)
    WPF Prism框架合集(7.Mvvm)
    springboot @OneToOne 解决JPA双向死循环/返回json数据死循环
  • 原文地址:https://www.cnblogs.com/xiazh/p/2003852.html
Copyright © 2011-2022 走看看