rabbitMQ学习(一)
一般模式
服务端:
import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.QueueingConsumer; public class Recv { //队列名称 public final static String QUEUE_NAME = "hello"; public static void main(String[] argv) throws java.io.IOException, java.lang.InterruptedException { //打开连接和创建频道,与发送端一样 ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); factory.setPort(5672); factory.setUsername("test"); factory.setPassword("test"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); //声明队列,主要为了防止消息接收者先运行此程序,队列还不存在时创建队列。 channel.queueDeclare(QUEUE_NAME, false, false, false, null); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); //创建队列消费者 QueueingConsumer consumer = new QueueingConsumer(channel); //指定消费队列 channel.basicConsume(QUEUE_NAME, true, consumer); while (true) { //nextDelivery是一个阻塞方法(内部实现其实是阻塞队列的take方法) QueueingConsumer.Delivery delivery = consumer.nextDelivery(); String message = new String(delivery.getBody()); System.out.println(" [x] Received '" + message + "'"); } } }
发送
import java.util.Map; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.MessageProperties; public class Send { //队列名称 // private final static String QUEUE_NAME = "dear"; public static void main(String[] argv) throws java.io.IOException { /** * 创建连接连接到MabbitMQ */ ConnectionFactory factory = new ConnectionFactory(); //设置MabbitMQ所在主机ip或者主机名 factory.setHost("localhost"); //创建一个连接 Connection connection = factory.newConnection(); //创建一个频道 Channel channel = connection.createChannel(); //指定一个队列 /** * Recv.QUEUE_NAME 队列名 * durable 持久化(把数据写到磁盘上,当服务器重启后数据还在) * exclusive 占用链接(该队列是否时独占的即连接上来时它占用整个网络连接) * autoDelete 自动删除(当前队列没有连接时,自动删除。即没有消费者对接上来时自动删除) * arguments 其他参数如TTL(队列存活时间)等 */ Map<String, Object> arguments=null; channel.queueDeclare(Recv.QUEUE_NAME, false, false, false, arguments); //发送的消息 String message = "hello "+Recv.QUEUE_NAME+"!"; //往队列中发出一条消息 channel.basicPublish("", Recv.QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes()); System.out.println(" [x] Sent '" + message + "'"); //关闭频道和连接 channel.close(); connection.close(); } }
参考资料:http://www.rabbitmq.com/tutorials/tutorial-one-java.html