springboot 2.x整合rabbitmq

本文介绍了如何在SpringBoot 2.x应用中整合RabbitMQ,包括添加依赖、配置文件设置、创建消息转换器、启用RabbitMQ、编写消息生产者和消费者,并提醒在实际使用中应将消费者与生产者模块化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、引入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:这里只是简单整合而已,具体使用要将消费者与生产者分开。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值