spring boot整合rabbitMq(AmqpAdmin的使用)

开发过程中遇到的场景:需要spring boot整合rabbitMQ,并且对外提供rabbitMQ的服务,包括:rabbitMq的创建与配置、消息的发布publish,网上搜了很多都没找到这种场景相关的记录,整体过程记录如下:

  1. 国际惯例,添加依赖
    在这里插入图片描述
  2. application.yml(property)配置
    在这里插入图片描述
  3. rabbitConfig配置类
@Configuration
public class RabbitConfig {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${spring.rabbitmq.host}")
    private String host;
    @Value("${spring.rabbitmq.port}")
    private Integer port;
    @Value("${spring.rabbitmq.username}")
    private String userName;
    @Value("${spring.rabbitmq.password}")
    private String password;
    @Value("${spring.rabbitmq.virtual-host}")
    private String virtualHost;

    @Bean
    public ConnectionFactory connectionFactory(){
        CachingConnectionFactory factory = new CachingConnectionFactory();
        factory.setUsername(userName);
        factory.setPassword(password);
        factory.setVirtualHost(virtualHost);
        factory.setHost(host);
        factory.setPort(port);
        factory.setPublisherConfirmType(CachingConnectionFactory.ConfirmType.CORRELATED);
        factory.setPublisherReturns(true);
        return factory;
    }

    @Bean
    public RabbitTemplate rabbitTemplate(){
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory());
        //消息发送失败返回到队列中, yml需要配置 publisher-returns: true
        rabbitTemplate.setMandatory(true);
        //消息返回确认是否到队列
        rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> {
            String correlationId = message.getMessageProperties().getCorrelationId();
            logger.error("消息:{} 发送失败, 应答码:{} 原因:{} 交换机: {}  路由键: {}", correlationId, replyCode, replyText, exchange, routingKey);
        });
        //消息确认是否发送到exchange
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            if (ack) {
                if (correlationData != null) {
                    logger.info("消息发送到exchange成功,id: {}", correlationData.getId());
                }
            } else {
                logger.error("消息发送到exchange失败,原因: {}", cause);
            }
        });
        return rabbitTemplate;
    }
}
  1. 消息发布逻辑
/**
 * 发布消息,适用于direct、topic、fanout
 * @param mqMessage 消息
 * @return boolean
 */
@Override
    public Boolean sendMsg(MqMessage mqMessage) {
        logger.info("send queue msg: " + JSON.toJSONString(mqMessage));
        try {
            this.rabbitTemplate.convertAndSend(mqMessage.getExchangeName(), mqMessage.getRoutingKey(), mqMessage.getMsgContent(),
                    new CorrelationData(mqMessage.getMsgId()));
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    } 

通过rabbitTemplate.convertAndsend进行消息发布。适用于direct(一对一)、topic(主题订阅)及fanout(广播)模式。direct及topic需要routingKey,fanout可以不需要。

  1. 模拟消息消费
 	/**
     * TEST消息监听
     * @param massage 消息
     */
    @RabbitListener(bindings = {@QueueBinding(value = @Queue(value = "q1", durable = "true"),
    exchange = @Exchange(value = "ex1", type = "topic"),
    key = "t.message")})
    public void processFanoutMsg(Message massage) {
        String msg = new String(massage.getBody(), StandardCharsets.UTF_8);
        logger.info("*************************** direct : {}", msg);
    }

应用启动,就会收到logger.info消息。

  1. Mq创建配置服务
    对外提供自定义创建exchange、queue、binding服务,通过AmqpAdmin实现。代码如下:
@Override
    public Boolean createTopic(MqTopic mqTopic) {
        logger.info("创建topicMq!");
        logger.info("mqTopic为:{}", JSON.toJSONString(mqTopic));
        String exchangeName = mqTopic.getExchangeName();
        try {
            amqpAdmin.declareExchange(new TopicExchange(exchangeName));
            mqTopic.getMqInfos().forEach(e -> {
                amqpAdmin.declareQueue(new Queue(e.getQueueName()));
                amqpAdmin.declareBinding(new Binding(e.getQueueName(), Binding.DestinationType.QUEUE, exchangeName, e.getRoutingKey(), null));
            });
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

AmqpAdmin:创建删除Queue、Exchange、Binding。declare开头的方法负责创建,delete开头的方法进行删除。

  1. 总结
    简要记录整合过程,说明不算详细,欢迎大佬指正以便完善。
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring BootRabbitMQ整合可以通过使用Spring AMQP实现。下面是一个简单的步骤: 1. 添加依赖:在`pom.xml`文件中添加以下依赖关系: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency> ``` 2. 配置RabbitMQ连接:在`application.properties`或`application.yml`文件中配置RabbitMQ的连接信息,例如: ```properties spring.rabbitmq.host=localhost spring.rabbitmq.port=5672 spring.rabbitmq.username=guest spring.rabbitmq.password=guest ``` 3. 创建生产者:创建一个简单的生产者,用于向RabbitMQ发送消息。你可以使用`RabbitTemplate`类来发送消息,例如: ```java import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class MessageProducer { @Autowired private RabbitTemplate rabbitTemplate; public void sendMessage(String message) { rabbitTemplate.convertAndSend("exchangeName", "routingKey", message); } } ``` 4. 创建消费者:创建一个简单的消费者,用于接收RabbitMQ发送的消息。你可以使用`@RabbitListener`注解来定义一个消息监听器,例如: ```java import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.stereotype.Component; @Component public class MessageConsumer { @RabbitListener(queues = "queueName") public void receiveMessage(String message) { System.out.println("Received message: " + message); } } ``` 5. 启用RabbitMQ:通过在Spring Boot应用程序的主类上添加`@EnableRabbit`注解来启用RabbitMQ功能,例如: ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.amqp.rabbit.annotation.EnableRabbit; @SpringBootApplication @EnableRabbit public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 这就是整合Spring BootRabbitMQ的基本步骤。你可以根据自己的需求进行更多的高级配置和定制。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

冰红茶不会渴

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值