1. 程式人生 > >rabbitmq收發訊息小例子

rabbitmq收發訊息小例子

發訊息:
package com.mgkj.msg.rabbit.producer;

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

public class SendMsg {

public static void main(String[] args) throws Exception {
	
	ConnectionFactory factory = null;
	Connection conn = null;
	Channel channel = null;

	factory = new ConnectionFactory();
	conn = factory.newConnection();
	channel = conn.createChannel();
		
	String queueName = "hello";
	channel.queueDeclare(queueName, false, false, false, null);
		
	String message = "Hello World2!";
	channel.basicPublish("", queueName, null, message.getBytes());
		
	channel.close();
	conn.close();

}

}

收訊息:
package com.mgkj.msg.rabbit.consumer;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import com.rabbitmq.client.BasicProperties;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

public class ReceiveMsg {

public static void main(String[] args) throws Exception {
	ConnectionFactory factory = null;
	Connection conn = null;
	Channel channel = null;
		factory = new ConnectionFactory();
		conn = factory.newConnection();
		channel = conn.createChannel();
		
		String queueName = "hello";
		channel.queueDeclare(queueName, false, false, false, null);
		
		Consumer consumer = new DefaultConsumer(channel) {
			public void handleDelivery(String consumerTag, Envelope envelope,
					BasicProperties properties, byte[] body) throws IOException {
				String msg = new String(body,"UTF-8");
				System.out.println("=====接收到的訊息:========"+msg);
			}
		};
		
		channel.basicConsume(queueName, consumer);
}

}

pom.xml里加入rabbitmq引用:

com.rabbitmq
amqp-client
5.3.0