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, 
false false false , 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, 
false false false null );
        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 );
        }
    }
}

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值