在官方例子https://github.com/spring-projects/spring-amqp-samples/tree/master/helloworld进行整理
一.Producer端:
1.与Producer端连接rabbitmq服务器配置类似,使用相同的队列名,配置连接工厂,发送工具类.
1.Producer端
一.Producer端:
1.定义一个队列名,配置连接工厂,发送工具类.
public static final String helloWorldQueueName = "hello.world.queue";
@Bean
public ConnectionFactory connectionFactory() {
CachingConnectionFactory connectionFactory = new CachingConnectionFactory("192.168.1.118");
return connectionFactory;
}
@Bean
public AmqpAdmin amqpAdmin() {
return new RabbitAdmin(connectionFactory());
}
@Bean
public RabbitTemplate rabbitTemplate() {
//没有指定默认routingKey,由发送时指定
return new RabbitTemplate(connectionFactory());
}
2.设置一个定时计划,每3秒发送一次消息(模拟发送消息)
//配置一个定时计划,每隔3秒发一次消息
@Bean
public BeanPostProcessor postProcessor() {
return new ScheduledAnnotationBeanPostProcessor();
}
@Bean
public ScheduledProducer scheduledProducer() {
return new ScheduledProducer();
}
static class ScheduledProducer {
@Autowired
private volatile RabbitTemplate rabbitTemplate;
private final AtomicInteger counter = new AtomicInteger();
@Scheduled(fixedRate = 3000)
public void sendMessage() {
String msg="Hello World " + counter.incrementAndGet();
System.out.println(msg);
rabbitTemplate.convertAndSend(ProducerConfig.helloWorldQueueName,msg);
}
}
二.Consumer端
1.与Producer端连接rabbitmq服务器配置类似,使用相同的队列名,配置连接工厂,发送工具类.
public static final String helloWorldQueueName = "hello.world.queue";
@Bean
public ConnectionFactory connectionFactory() {
CachingConnectionFactory connectionFactory = new CachingConnectionFactory("192.168.1.118");
return connectionFactory;
}
@Bean
public AmqpAdmin amqpAdmin() {
return new RabbitAdmin(connectionFactory());
}
@Bean
public RabbitTemplate rabbitTemplate() {
//没有指定默认queueName,在接收的监听器指定
return new RabbitTemplate(connectionFactory());
}
2.设置一个接收消息的监听器.
@Bean
public SimpleMessageListenerContainer listenerContainer() {
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
container.setConnectionFactory(connectionFactory());
container.setQueueNames(ConsumerConfig.helloWorldQueueName);
MessageListenerAdapter adapter= new MessageListenerAdapter(new HelloWorldHandler());
//没有指定默认的监听器方法,则使用默认的监听器方法名handleMessage
container.setMessageListener(adapter);
return container;
}
其中HelloWorldHandler.java如下:
public class HelloWorldHandler {
public void handleMessage(String text) {
System.out.println("Received: "+ text);
}
}
三.测试.启动Producer端和Consumer端顺序没有限制.
1.Producer端
public static void main(String[] args) {
new AnnotationConfigApplicationContext(ProducerConfig.class);
}
2.Consumer端
public static void main(String[] args) {
new AnnotationConfigApplicationContext(ConsumerConfig.class);
}