1.开启注解
开启基于RabbitMQ的注解
package com.invi;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
//开启基于注解的RabbitMQ
@EnableRabbit
@SpringBootApplication
public class Springboot02AmqpApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot02AmqpApplication.class, args);
}
}
2.监听程序
编写监听服务
package com.invi.service;
import com.invi.bean.Book;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;
@Service
public class BookService {
//数组的方式,可以监听多个队列
@RabbitListener(queues = "invi.news")
public void receive(Book book) {
System.out.println("invi.news队列收到消息:" + book.toString());
}
}
3.发送队列消息
package com.invi;
import com.invi.bean.Book;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
@RunWith(SpringRunner.class)
@SpringBootTest
public class Springboot02AmqpApplicationTests {
@Autowired
RabbitTemplate rabbitTemplate;
//发送-单播(点对点)
@Test
public void testExchangeDirect() {
rabbitTemplate.convertAndSend("exchange.direct", "invi.news", new Book("《挪威森林》", "村上春树"));
}
}
运行测试:
2019-03-05 09:41:13.443 INFO 90011 --- [ Thread-2] o.s.a.r.l.SimpleMessageListenerContainer : Waiting for workers to finish.
invi.news队列收到消息:Book{name='《挪威森林》', author='村上春树'}
2019-03-05 09:41:13.474 INFO 90011 --- [ Thread-2] o.s.a.r.l.SimpleMessageListenerContainer : Successfully waited for workers to finish.
2019-03-05 09:41:13.482 INFO 90011 --- [ Thread-2] o.s.a.r.l.SimpleMessageListenerContainer : Shutdown ignored - container is not active already
网友评论