您的位置:首页 > 其它

RabbitMQ 消息发送和消息获取 之 rabbitMQ消息生产者和消费者

2014-09-26 00:00 447 查看
//rabbitMQ消息生产者 、发送消息
public static void shenc() throws IOException{
//创建链接工程

ConnectionFactory factory2 = new ConnectionFactory();

factory2.setHost("xx.xx.xx.xx");
factory2.setUsername("name");
factory2.setPassword("pass");
factory2.setVirtualHost("virtualhost 日志文件名称");//本地无需这项set

//创建链接
Connection connection = factory2.newConnection();

//创建消息通道
Channel channel = connection.createChannel();

String message = "Hello World";
String Queue = "Queue";
//生命一个消息队列
channel.queueDeclare(Queue, true, false, false, null);

//发布消息,第一个参数表示路由(Exchange名称),未""则表示使用默认消息路由
channel.basicPublish("", Queue,
MessageProperties.PERSISTENT_TEXT_PLAIN,message
.getBytes());

log.info("传送信息完毕");

System.out.println(" [x] Sent '"+message+"'");

//关闭消息通道和链接
channel.close();
connection.close();

}

//消费者、获取MQ消息
public static void xiaofei() throws IOException, ShutdownSignalException, ConsumerCancelledException, InterruptedException{

//创建链接工厂
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("xx.xx.xx.xx");
factory.setUsername("name");
factory.setPassword("pass");
factory.setVirtualHost("virtualhost 日志文件名称");//本地无需这项set
//创建链接
Connection connection = factory.newConnection();
String Queue = "Queue";
//创建消息信道
Channel channel = connection.createChannel();
//生命消息队列
channel.queueDeclare(Queue,true,false,false,null);

//消费者用于获取消息信道绑定的消息队列中的信息
QueueingConsumer consumer = new QueueingConsumer(channel);

channel.basicConsume(Queue, true,consumer);

while(true){

//循环获取消息队列中的信息
QueueingConsumer.Delivery delivery = consumer.nextDelivery();
String message = new String(delivery.getBody());
System.out.println("[x] Received '"+message+"'");

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: