1、创建Consumer的接口RabbitMqService:
package com.java996.consumer.service;
public interface RabbitMqService {
/**
* 接收消息
*/
public void receiveMessage();
}
2、创建Consumer的接口的实现RabbitMqServiceImpl:
package com.java996.consumer.service.impl;
import com.java996.consumer.service.RabbitMqService;
import com.java996.producer.config.RabbitMqConfig;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
@Service("RabbitMqService")
public class RabbitMqServiceImpl implements RabbitMqService {
@Resource
private AmqpTemplate amqpTemplate;
/**
* receiveAndConvert(String queueName),参数说明:队列名称
*/
@Override
public void receiveMessage() {
String message = (String)amqpTemplate.receiveAndConvert(RabbitMqConfig.DIRECT_QUEUE);
System.out.println("接收到的消息:"+message);
}
}
3、启动,测试接收消息
package com.java996.consumer;
import com.java996.consumer.service.RabbitMqService;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication
public class ConsumerApp {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(ConsumerApp.class,args);
RabbitMqService rabbitMqService = (RabbitMqService) context.getBean("RabbitMqService");
rabbitMqService.receiveMessage();
}
}
4、结果:
这种方式只能拿到一条数据,所以需要换一种方式
5、监听队列,首先保证队列中有多条消息,启动项中的消费代码已注释或删除
@Override
@RabbitListener(queues = {RabbitMqConfig.DIRECT_QUEUE}) //监听队列
public void receiveMessage2(String message) {
System.out.println("接收到的消息:"+message);
}
6、结果: