RabbitMQ生产者和消费者代码

生产者

package com.rabbitMQ.pro;  

import com.rabbitmq.client.ConnectionFactory;  
import com.rabbitmq.client.Connection;  
import com.rabbitmq.client.Channel;  

public class Producer {  

    private final static String QUEUE_NAME = "hello2";// 队列名不能重复 之前已有就会失败  

    public static void main(String[] argv) throws java.io.IOException {  

        /* 使用工厂类建立Connection和Channel,并且设置参数 */  
        ConnectionFactory factory = new ConnectionFactory();  
        factory.setHost("192.168.10.111");// MQ的IP  
        factory.setPort(5672);// MQ端口  
        factory.setUsername("asdf");// MQ用户名  
        factory.setPassword("123456");// MQ密码  
        Connection connection = factory.newConnection();  
        Channel channel = connection.createChannel();  

        /* 创建消息队列,并且发送消息 */  
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);  
        String message = "消息2";  
        channel.basicPublish("", QUEUE_NAME, null, message.getBytes());  
        System.out.println("生产了个'" + message + "'");  

        /* 关闭连接 */  
        channel.close();  
        connection.close();  
    }  

}  

消费者

package com.rabbitMQ.pro;  

import com.rabbitmq.client.ConnectionFactory;  
import com.rabbitmq.client.Connection;  
import com.rabbitmq.client.Channel;  
import com.rabbitmq.client.QueueingConsumer;  

public class Consumer {  

    private final static String QUEUE_NAME = "hello2";  

    public static void main(String[] argv) throws java.io.IOException,  
            java.lang.InterruptedException {  
        /* 建立连接 */  
        ConnectionFactory factory = new ConnectionFactory();  
        factory.setHost("192.168.10.111");// MQ的IP  
        factory.setPort(5672);// MQ端口  
        factory.setUsername("asdf");// MQ用户名  
        factory.setPassword("123456");// MQ密码  
        Connection connection = factory.newConnection();  
        Channel channel = connection.createChannel();  

        /* 声明要连接的队列 */  
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);  
        System.out.println("等待消息产生:");  

        /* 创建消费者对象,用于读取消息 */  
        QueueingConsumer consumer = new QueueingConsumer(channel);  
        channel.basicConsume(QUEUE_NAME, true, consumer);  

        /* 读取队列,并且阻塞,即在读到消息之前在这里阻塞,直到等到消息,完成消息的阅读后,继续阻塞循环 */  
        while (true) {  
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();  
            String message = new String(delivery.getBody());  
            System.out.println("收到消息'" + message + "'");  
        }  
    }  
}  
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值