ProducerMessage.java 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package com.sf.hello;
  2. import com.rabbitmq.client.Channel;
  3. import com.rabbitmq.client.Connection;
  4. import com.rabbitmq.client.ConnectionFactory;
  5. /**
  6. * 消息的发送者
  7. */
  8. public class ProducerMessage {
  9. //声明一个队列
  10. private static final String QUEUE_NAME="hello";
  11. public static void main(String[] args) throws Exception {
  12. //创建连接RabbitMQ服务器的连接
  13. ConnectionFactory connectionFactory = new ConnectionFactory();
  14. connectionFactory.setHost("192.168.180.133");
  15. connectionFactory.setPort(5672);
  16. //用户名和密码不用设置 都是默认的guest
  17. //创建一个连接
  18. Connection connection = connectionFactory.newConnection();
  19. Channel channel = connection.createChannel();
  20. //声明一个队列,现在只关注第1个参数,队列名称,后面其他参数会在下面的例子中一个个讲解
  21. channel.queueDeclare(QUEUE_NAME,false,false,false,null);
  22. String message = "hello2";
  23. /*
  24. 向队列中发送上面的message消息
  25. 里面涉及到两个参数
  26. 第2个参数 routingKey : 指定发送队列的名称
  27. 第4个参数 body : 设置需要发送的消息,byte数组格式
  28. 其它参数会在后面介绍其它功能时详解
  29. */
  30. channel.basicPublish("",QUEUE_NAME,null,message.getBytes());
  31. System.out.println(" [x] Sent '" + message + "'");
  32. //关闭频道和连接
  33. channel.close();
  34. connection.close();
  35. }
  36. }