1、添加包
1 <dependency> 2 <groupId>org.springframework.boot</groupId> 3 <artifactId>spring-boot-starter-amqp</artifactId> 4 </dependency>
2、配置文件
pring:
# 消息队列
rabbitmq:
username: admin
password: admin
port: 5672
host: 192.168.1.118
listener:
simple:
acknowledge-mode: manual
3、生产者,其中MSGRABBITQUERENAME为队列名称
1 @Component 2 public class RabbitProducer { 3 4 @Autowired 5 AmqpTemplate rabbitTemplate; 6 7 static final String MSGRABBITQUERENAME="chat.send.msg"; 8 9 public void sendMessages(String str) { 10 this.rabbitTemplate.convertAndSend(MSGRABBITQUERENAME,str); 11 } 12 }
4、消费者,我这里为手动确认模式,确保数据有效性。
@Component public class RabbitListener { @org.springframework.amqp.rabbit.annotation.RabbitListener(queues = "leenleda.test") public void onMessage(@Payload String msg, @Headers Map<String, Object> headers, Channel channel) throws Exception{ try { //消息确认,(deliveryTag,multiple是否确认所有消息) channel.basicAck((Long) headers.get(AmqpHeaders.DELIVERY_TAG), false); } catch (Exception e) { //消息拒绝(deliveryTag,multiple,requeue拒绝后是否重新回到队列) channel.basicNack((Long) headers.get(AmqpHeaders.DELIVERY_TAG), false, true); // 拒绝一条 // channel.basicReject(); } } }
然后直接调用就可以了