注意:springboot支持的amqp规范的中间件只有rabbitmq
第一步:添加依赖
<!-- amqp --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency>
第二步:配置application.yml
spring: application: name: boot-rabbitmq rabbitmq: host: 192.168.175.13 port: 5672 username: liuy password: 123456
第三步:编写amqp队列配置
package com.liuy.config; import org.springframework.amqp.core.Queue; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * amqp队列配置 * @description amqp队列配置 * @author luis * @version 1.0 * @date:2017年8月22日下午12:33:36 */ @Configuration public class AmqpConfiguration { @Bean public Queue queue() { return new Queue("test.queue"); } }
第四步:编写监听与发送
package com.liuy.component; import org.springframework.amqp.core.AmqpTemplate; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** * 监听与发送 * @description 监听与发送 * @author luis * @version 1.0 * @date:2017年8月22日下午12:34:55 */ @Component public class AmqpComponent { @Autowired private AmqpTemplate amqpTemplate; public void send(String msg) { this.amqpTemplate.convertAndSend("test.queue", msg); } @RabbitListener(queues = "test.queue") public void receiveQueue(String text) { System.out.println("接受到:" + text); } }
第五步:编写启动类
package com.liuy; import org.springframework.amqp.rabbit.annotation.EnableRabbit; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.ServletComponentScan; /** * 集成rabbitmq--启动类 * @description 集成rabbitmq--启动类 * @author luis * @version 1.0 * @date:2017年8月22日下午12:39:04 */ @EnableRabbit @ServletComponentScan @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
第六步:测试
package com.liuy; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import com.liuy.component.AmqpComponent; /** * 集成rabbitmq监听与发送测试 * @description 集成rabbitmq监听与发送测试 * @author luis * @version 1.0 * @date:2017年8月22日下午12:35:43 */ @RunWith(SpringRunner.class) @SpringBootTest public class AmqpComponentTest { @Autowired private AmqpComponent amqpComponent; @Test public void send() { amqpComponent.send("集成rabbitmq监听与发送测试"); } }
效果:
时间: 2024-11-02 05:08:26