一、pom.xml
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>3.6.0</version>
</dependency>
二、统一参数
可以写死或使用其他方式。
package com;
public interface MQ_INFO {
String HOST = "XXXXXX";
String USERNAME = "guest";
String PASSWORD = "guest";
Integer PORT = 5672;
String EXCHANGE = "test";
String QUEUE = "test_logs";
}
三、连接工厂
package com;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
public class ConnectionFactoryUtil {
public static Connection createConnection() {
Connection conn = null;
ConnectionFactory factory = new ConnectionFactory();
factory.setHost(MQ_INFO.HOST);
factory.setUsername(MQ_INFO.USERNAME);
factory.setPassword(MQ_INFO.PASSWORD);
factory.setPort(MQ_INFO.PORT);
try {
// 创建连接
conn = factory.newConnection();
} catch (IOException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
return conn;
}
}
四、创建生产者
package com;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import java.io.IOException;
import java.util.Scanner;
public class Producer {
public static void main(String[] args) {
Thread t1 = new Thread(new Runnable() {
public void run() {
Channel channel = null;
try {
Connection conn = ConnectionFactoryUtil.createConnection();
channel = conn.createChannel();
// 声明要关注的exchange
channel.exchangeDeclare(MQ_INFO.EXCHANGE, "fanout");
} catch (IOException e) {
e.printStackTrace();
}
while (true) {
Scanner scan = new Scanner(System.in);
System.out.println("-------------请输入内容-------------");
String msg = scan.nextLine();
try {
// 发送至消息队列
channel.basicPublish(MQ_INFO.EXCHANGE, MQ_INFO.EXCHANGE, null, msg.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("已发送消息 :" + msg);
}
}
});
t1.start();
}
}
五、创建消费者
package com;
import com.rabbitmq.client.*;
import java.io.IOException;
public class Consumer {
public static void main(String[] args) {
Thread t2 = new Thread(new Runnable() {
public void run() {
Channel channel = null;
try {
// 创建连接
Connection conn = ConnectionFactoryUtil.createConnection();
channel = conn.createChannel();
channel.exchangeDeclare(MQ_INFO.EXCHANGE, "fanout");
channel.queueBind(MQ_INFO.QUEUE, MQ_INFO.EXCHANGE, "");
// 创建消费者,得到消息自动触发
DefaultConsumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
String msg = new String(body, "UTF-8");
System.out.println("-------------接收到消息-------------\r\n" + msg);
}
};
// 消息完成确认
channel.basicConsume(MQ_INFO.QUEUE, true, consumer);
} catch (Exception e) {
e.printStackTrace();
}
}
});
t2.start();
}
}
分别运行生产者和消费者,在生产者输入内容,如果没问题的话,将会在消费者端看到内容。