spring boot整合RabbitMQ(Direct模式)
springboot集成RabbitMQ非常简单,如果只是简单的使用配置非常少,springboot提供了spring-boot-starter-amqp项目对消息各种支持。
1.新建一个SpringBoot工程,命名为:“rabbitmq-hello”。
在pom.xml中引入如下依赖内容,其中spring-boot-starter-amqp用于支持RabbitMQ。
org.springframework.boot spring-boot-starter-amqp
2.在application.properties中配置关于RabbitMQ的连接和用户信息,用户可以回到上面的安装内容,在管理页面中创建用户。
spring.application.name=rabbitmq-hello spring.rabbitmq.host=localhost spring.rabbitmq.port=5672 spring.rabbitmq.username=admin spring.rabbitmq.password=123456
3.创建消息生产者Sender。通过注入AmqpTemplate接口的实例来实现消息的发送,AmqpTemplate接口定义了一套针对AMQP协议的基础操作。
在SpringBoot中会根据配置来注入其具体实现。在该生产者,我们会产生一个字符串,并发送到名为hello的队列中。
@Component publicclassSender{ @Autowired privateAmqpTemplaterabbitTemplate; publicvoidsend(){ Stringcontext="hello"+newDate(); System.out.println("Sender:"+context); this.rabbitTemplate.convertAndSend("hello",context); } }
4.创建消息消费者Receiver。
通过@RabbitListener注解定义该类对hello队列的监听,并用@RabbitHandler注解来指定对消息的处理方法。所以,该消费者实现了对hello队列的消费,消费操作为输出消息的字符串内容。
@Component @RabbitListener(queues="hello") publicclassReceiver{ @RabbitHandler publicvoidprocess(Stringhello){ System.out.println("Receiver:"+hello); } }
5.创建RabbitMQ的配置类RabbitConfig,用来配置队列、交换器、路由等高级信息。这里我们以入门为主,先以最小化的配置来定义,以完成一个基本的生产和消费过程。
@Configuration publicclassRabbitConfig{ @Bean publicQueuehelloQueue(){ returnnewQueue("hello"); } }
6.创建应用主类:
@SpringBootApplication publicclassHelloApplication{ publicstaticvoidmain(String[]args){ SpringApplication.run(HelloApplication.class,args); } }
7.创建单元测试类,用来调用消息生产:
@RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes=HelloApplication.class) publicclassHelloApplicationTests{ @Autowired privateSendersender; @Test publicvoidhello()throwsException{ sender.send(); } }
8.启动应用主类,从控制台中,我们看到如下内容,程序创建了一个访问127.0.0.1:5672中admin的连接。
o.s.a.r.c.CachingConnectionFactory:Creatednewconnection:SimpleConnection@29836d32[delegate=amqp://admin@127.0.0.1:5672/]
同时,我们通过RabbitMQ的控制面板,可以看到Connection和Channels中包含当前连接的条目。
9.运行单元测试类,我们可以看到控制台中输出下面的内容,消息被发送到了RabbitMQServer的hello队列中。
Sender:helloSunSep2511:06:11CST2016
10.切换到应用主类的控制台,我们可以看到类似如下输出,消费者对hello队列的监听程序执行了,并输出了接受到的消息信息。
Receiver:helloSunSep2511:06:11CST2016
通过上面的示例,我们在SpringBoot应用中引入spring-boot-starter-amqp模块,进行简单配置就完成了对RabbitMQ的消息生产和消费的开发内容。
需要注意的地方,Direct模式相当于一对一模式,一个消息被发送者发送后,会被转发到一个绑定的消息队列中,然后被一个接收者接收!
实际上RabbitMQ还可以支持发送对象:当然由于涉及到序列化和反序列化,该对象要实现Serilizable接口.HelloSender做出如下改写:
publicvoidsend(){ Useruser=newUser();//实现Serializable接口 user.setUsername("hlhdidi"); user.setPassword("123"); template.convertAndSend("queue",user); } HelloReceiver做出如下改写: @RabbitListener(queues="queue")//监听器监听指定的Queue publicvoidprocess1(Useruser){//用User作为参数 System.out.println("Receive1:"+user); }
以上所述是小编给大家介绍的springboot整合RabbitMQ(Direct模式),希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!