java操作rabbitmq实现简单的消息发送(socket编程的升级)
准备:
1.下载rabbitmq并搭建环境(和python那篇一样:http://www.cnblogs.com/g177w/p/8176797.html)
2.下载支持的jar包(http://repo1.maven.org/maven2/com/rabbitmq/amqp-client)
生产者方(Productor.java):
1 package RabbitMQTest; 2 3 4 import java.util.HashMap; 5 import java.util.Map; 6 7 import com.rabbitmq.client.AMQP.Queue; 8 import com.rabbitmq.client.Channel; 9 import com.rabbitmq.client.Connection; 10 import com.rabbitmq.client.ConnectionFactory; 11 12 public class Productor { 13 public static String QUEUE_NAME = "STEVEN"; 14 public static void main(String[] args) { 15 //初始化socket链接 16 ConnectionFactory factory = new ConnectionFactory(); 17 //指定链接地址 18 factory.setHost("localhost"); 19 try{ 20 //建立程序和rabbitmq的socket连接 21 Connection connection = factory.newConnection(); 22 //创建管道 23 Channel channel = connection.createChannel(); 24 //声明队列 25 channel.queueDeclare(QUEUE_NAME,false,false,false,null); 26 //让当前线程睡眠8s,以检验rabbitmq的消息轮询 27 Thread.currentThread().sleep(8000); 28 String message = "hello,world"; 29 //发送消息 30 channel.basicPublish("", QUEUE_NAME, null, message.getBytes()); 31 System.out.println("[x] send the message"+message); 32 channel.close(); 33 connection.close(); 34 }catch (Exception e) { 35 System.out.println("程序出错:"+e); 36 } 37 38 } 39 }
消费者方(Consummer.java):
1 package RabbitMQTest; 2 import com.rabbitmq.client.Connection; 3 import com.rabbitmq.client.Channel; 4 import com.rabbitmq.client.ConnectionFactory; 5 import com.rabbitmq.client.QueueingConsumer; 6 import com.rabbitmq.client.QueueingConsumer.Delivery; 7 /** 8 * 本程序为了练习rabbitmq的简单操作 9 * 10 * @author STEVEN 11 * 12 */ 13 public class Consumer { 14 public static void main(String[] args) { 15 try { 16 //创建连接工厂对象 17 ConnectionFactory factory = new ConnectionFactory(); 18 //设置工厂对象的参数,用来连接rabbitmq 19 factory.setHost("localhost"); 20 //建立程序与rabbitmq的socket连接 21 Connection connection = factory.newConnection(); 22 //创建管道 23 Channel channel = connection.createChannel(); 24 //声明队列 25 channel.queueDeclare(Productor.QUEUE_NAME, false, false, false, null); 26 System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); 27 //创建队列消费对象 28 QueueingConsumer consumer = new QueueingConsumer(channel); 29 //设置参数 30 channel.basicConsume(Productor.QUEUE_NAME, true, consumer); 31 //创建接收对象来接收来自服务端的消息 32 Delivery delivery = null; 33 //循环接收,相当于开启了一个监听 34 while (true) { 35 delivery = consumer.nextDelivery(); 36 String message = new String(delivery.getBody()); 37 System.out.println(" [x] Received '" + message + "'"); 38 } 39 } catch (Exception e) { 40 System.out.println(e); 41 } 42 } 43 }