|
| 1 | +package com.code.repository.study.rabbitmq; |
| 2 | + |
| 3 | +import com.rabbitmq.client.Channel; |
| 4 | +import com.rabbitmq.client.Connection; |
| 5 | +import com.rabbitmq.client.ConnectionFactory; |
| 6 | + |
| 7 | +import java.io.IOException; |
| 8 | +import java.util.Scanner; |
| 9 | +import java.util.concurrent.TimeoutException; |
| 10 | + |
| 11 | +/** |
| 12 | + * rabbit MQ 发送端 |
| 13 | + */ |
| 14 | +public class SenderMQ { |
| 15 | + |
| 16 | + private final static String QUEUE_NAME = "Hello"; |
| 17 | + |
| 18 | + public static void main(String[] args) throws IOException, TimeoutException { |
| 19 | + // connection是socket连接的抽象,并且为我们管理协议版本协商(protocol version negotiation), |
| 20 | + // 认证(authentication )等等事情。这里我们要连接的消息代理在本地,因此我们将host设为“localhost”。 |
| 21 | + // 如果我们想连接其他机器上的代理,只需要将这里改为特定的主机名或IP地址。 |
| 22 | + ConnectionFactory factory = new ConnectionFactory(); |
| 23 | + factory.setHost("localhost"); |
| 24 | + factory.setPort(5672); //默认端口号 |
| 25 | + factory.setUsername("guest");//默认用户名 |
| 26 | + factory.setPassword("guest");//默认密码 |
| 27 | + Connection connection = factory.newConnection(); |
| 28 | + Channel channel = connection.createChannel(); |
| 29 | + // 接下来,我们创建一个channel,绝大部分API方法需要通过调用它来完成。 |
| 30 | + // 发送之前,我们必须声明消息要发往哪个队列,然后我们可以向队列发一条消息: |
| 31 | + channel.queueDeclare(QUEUE_NAME, false, false, false, null); |
| 32 | + |
| 33 | + Scanner input=new Scanner(System.in); |
| 34 | + |
| 35 | + while(input.hasNextLine()){ |
| 36 | + String message = input.nextLine(); |
| 37 | + channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8")); |
| 38 | + System.out.println(" [x] Sent '" + message + "'"); |
| 39 | + } |
| 40 | + |
| 41 | + System.out.println("send is end!"); |
| 42 | + |
| 43 | + channel.close(); |
| 44 | + connection.close(); |
| 45 | + } |
| 46 | +} |
0 commit comments