一、引入pom.xml
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency>
二、在application.yml或application.properties进行配置
spring: rabbitmq: #配置rabbitmq安装的主机IP地址 host: 192.168.24.130 #rabbitmq使用的端口 port: 5672 #访问的用户名 username: admin #密码 password: 445221abcd #虚拟主机名 virtual-host: /
三、编写Rabbitmq配置类,往容器中添加消息转换器
/** * RabbitmqConfig:Rabbitmq配置类 * * @author chen * @date 2019/03/11 */ @Configuration public class RabbitmqConfig { /** * 往容器中添加 消息转换器(json格式) * * @return */ @Bean public MessageConverter messageConverter(){ MessageConverter messageConverter = new Jackson2JsonMessageConverter(); return messageConverter; } }
四、在主启动类添加@EnableRabbit注解,启用Rabbitmq
/** * SpringbootAmqpDemoApplication:主启动类 * * @author chen * @date 2019/03/11 */ @SpringBootApplication @EnableRabbit public class SpringbootAmqpDemoApplication { public static void main(String[] args) { SpringApplication.run(SpringbootAmqpDemoApplication.class, args); } }
五、编写消息生产者
@Service public class ProducerServiceImpl implements ProducerService { @Autowired private RabbitMessagingTemplate rabbitMessagingTemplate; /** * 将消息发送到指定 exchange * * @param exchange * @param routingKey * @param user */ @Override public void produce(String exchange, String routingKey, User user) { rabbitMessagingTemplate.convertAndSend(exchange,routingKey,user); } }
六、编写消息消费者
* ConsumerServiceImpl:消息消费业务接口 * * @author chen * @date 2019/03/11 */ @Service public class ConsumerServiceImpl implements ConsumerService { /** * 消费消息 * * @Payload 将消息体内容映射到对象中 * @RabbitListener中配置绑定会在 rabbitmq上自动生成 * */ @Override @RabbitListener(bindings = {@QueueBinding( value = @Queue(name = "mq.queue",durable = "true"), exchange = @Exchange(name = "mq.direct",type = ExchangeTypes.DIRECT,durable = "true"), key = "mq.news" ) }) public void consume(@Payload User user) { System.out.println(user.toString()); } }
七、进行测试,这里略过
PS:这里只是简单整合而已,具体使用要将消费者与生产者分开。