RabbitMQ的消息发送和接收机制
所有 MQ 产品从模型抽象上来说都是一样的过程(哈哈图片是抄的,但是内容是自己写的):
消费者(consumer)订阅某个队列。生产者(producer)创建消息,然后发布到队列(queue)中,最后将消息发送到监听的消费者。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
application.yml配置文件
spring:
rabbitmq:
#mq服务器ip,默认为localhost
host: 192.168.31.164
#mq服务器port,默认为5672
port: 5672
#mq服务器username,默认为gust
username: guest
#mq服务器password,默认为guest
password: guest
#手动关闭消息,接收参数(不需要删除就行)
listener:
simple:
acknowledge-mode: manual
rabbitmq配置文件
/**
* RabbitMQ配置文件
*/
@Configuration
public class RabbitMQConfig {
//队列名字
public static final String QUEUE_NAME = "text_queue_name";
@Bean
public Queue textQueue(){
return new Queue(QUEUE_NAME, true, false, false);
}
}
生产者
@Autowired
private RabbitTemplate rabbitTemplate;
@Test
public void sendRabbitMQMessage(){
rabbitTemplate.convertAndSend(RabbitMQConfig.QUEUE_NAME, "hello word RabbitMQ");
}
消费者
import com.rabbitmq.client.Channel;
import com.staging.config.rabbitMQ.RabbitMQConfig;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;
import java.io.IOException;
@Component
public class MsgReceiver {
/**
* 手动消费案例
* 需要设置成
* listener:
* simple:
* acknowledge-mode: manual
* concurrency 并发数量(创建消费者的数量)、开启20个子线程去消费消息
* @param message
* @param channel
*/
@RabbitListener(queues = RabbitMQConfig.QUEUE_NAME, concurrency = "20")
public void handleMsg(Message message, Channel channel){
//接收消息内容
Object object = message.getPayload();
try {
/**
* 消费消息
* 参数1:消息唯一标记
* 参数2:是否批量处理
*/
channel.basicAck((Long) message.getHeaders().get(AmqpHeaders.DELIVERY_TAG), false);
/**
* 拒绝消费消息(重新返回队列里面)
* 参数1:消息唯一标记
* 参数2:
*/
channel.basicReject((Long) message.getHeaders().get(AmqpHeaders.DELIVERY_TAG), true);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* 自动消费案例
* 不需要设置
* listener:
* simple:
* acknowledge-mode: manual
* @param msg
*/
@RabbitListener(queues = RabbitMQConfig.QUEUE_NAME)
public void handleMsg2(String msg){
System.out.println(msg);
}
}
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_40943748