Simple MQ
在此之前,先安装rabbitMQ,我是在docker上直接部署的,docker-compose.yml
如下:
version: '3'
services:
rabbitmq:
image: rabbitmq:management-alpine
container_name: rabbitmq
environment:
- RABBITMQ_DEFAULT_USER=你的用户名 # 创建rabbitMQ用户名和密码
- RABBITMQ_DEFAULT_PASS=你的密码
restart: always
ports:
- "15672:15672"
- "5672:5672"
logging:
driver: "json-file"
options:
max-size: "200k"
max-file: "10"
建议大家,以后的部署全部在docker上完成,这是非常方便的。部署完成后直接在浏览器中输入:
你的ip:15672
就能访问rabbitMQ客户端了。比如我的 192.168.116.128:15672,就能看到下面的内容:
输入你刚才设置的账号和密码,即可进入客户端。
rabbitMQ使用阶段
最简单的消息队列,官网传送门:
包含一个消费者,一个生产者,一个MQ
接下来引入需要的依赖:
<dependencies>
<!-- https://mvnrepository.com/artifact/com.rabbitmq/amqp-client -->
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>5.7.3</version>
</dependency>
</dependencies>
包含一个消费者,一个生产者,代码如下:
建立连接(连接工具类):
public class RabbitConnection {
public static Connection getConnection() throws IOException, TimeoutException {
ConnectionFactory factory = new ConnectionFactory();
// address
factory.setHost("192.168.119.129"); // 这是我的linux主机地址,docker下安装MQ
factory.setUsername("king");
factory.setPassword("123456");
factory.setVirtualHost("/vhosts"); // 节点
return factory.newConnection();
}
}
生产者:
public class Send {
private static final String QUEUE_NAME = "simple_mq"; //消息队列名称
public static void main(String[] args) throws IOException, TimeoutException {
Connection connection = RabbitConnection.getConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
String message = "hello simple_mq"; // 发送的消息
channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
System.out.println(" [x] Sent.......... '" + message + "'");
}
}
消费者:
public class ReceiV {
private static final String QUEUE_NAME = "simple_mq";
public static void main(String[] args) throws IOException, TimeoutException {
Connection connection = RabbitConnection.getConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
DeliverCallback deliverCallback = (consumerTag, delivery) -> {
String message = new String(delivery.getBody(), "UTF-8");
System.out.println(" [x] Received '" + message + "'");
};
channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> { });
}
}
如果这里报错 lambda ~~~~level 5之类的错误,加上下面的内容到pom中:
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
这里我们启动两个Application,发现,只要是启动一次send,消费者后台就会接收到message,进行消费。