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