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);
            }
        }
    }
  • 相关阅读:
    对png空白部分取消button事件教程
    Flash Builder4.6破解方案(绝对有效)
    网页程序Flex动态嵌入字体
    老虎机等转动图片思路
    我认为最佳的新手引导制作办法
    26
    sql server 2005建立数据库,表,约束,账户密码,权限,基本查询删除语句
    ASP.NET入门教程:ASP.NET和ASP区别
    .net面试题及答案(一)(转)
    ASP.NET入门教程:认识ASP.NET
  • 原文地址:https://www.cnblogs.com/xiazh/p/2003852.html
Copyright © 2011-2022 走看看