RabbitMQ与SpringBoot 集成
1、添加依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency>
2、添加配置
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
spring.rabbitmq.virtual-host=/
3、guest用户默认是不支持远程连接的
操作:在/usr/local/rabbitmq/etc/rabbitmq下创建rabbitmq.conf
并写入[{rabbit, [{loopback_users, []}]}].
重启rabbitmq
4、简单例子(direct模式)
4.1、ioc注入
@Configuration public class MQConfig { public static final String QUEUE = "queue"; @Bean public Queue queue() { return new Queue(QUEUE, true); } }
4.2、发送者
@Service public class MQSender { private Logger logger = LoggerFactory.getLogger(getClass()); @Autowired private AmqpTemplate amqpTemplate; public void send(String message){ logger.info("send message:{}",message); amqpTemplate.convertAndSend(MQConfig.QUEUE,message); } }
4.3、接收者
@Service public class MQReceiver { private Logger logger = LoggerFactory.getLogger(getClass()); @RabbitListener(queues = MQConfig.QUEUE) public void receiver(String message){ logger.info("receiver message:{}",message); } }
本文来自博客园,作者:咔咔皮卡丘,转载请注明原文链接:https://www.cnblogs.com/anquing/p/17638100.html