RabbitMQ实践

本文介绍了如何使用Spring Boot集成RabbitMQ,包括依赖配置、连接参数设置、队列、交换机和绑定关系的创建,以及生产者和消费者的实现。通过示例展示了如何发送和接收消息,涉及手动ACK确认和异常处理。
摘要由CSDN通过智能技术生成

1.maven

    <!--RabbitMq-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
            <version>1.5.2.RELEASE</version>
            <exclusions>
                <exclusion>
                    <artifactId>spring-core</artifactId>
                    <groupId>org.springframework</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>spring-boot-starter</artifactId>
                    <groupId>org.springframework.boot</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>spring-beans</artifactId>
                    <groupId>org.springframework</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>httpclient</artifactId>
                    <groupId>org.apache.httpcomponents</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>spring-context</artifactId>
                    <groupId>org.springframework</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>jackson-databind</artifactId>
                    <groupId>com.fasterxml.jackson.core</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>spring-tx</artifactId>
                    <groupId>org.springframework</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>spring-aop</artifactId>
                    <groupId>org.springframework</groupId>
                </exclusion>
            </exclusions>
        </dependency>

2.配置属性

#rabbit
spring.rabbitmq.host=127.0.0.1
spring.rabbitmq.port=5672
spring.rabbitmq.username=root
spring.rabbitmq.password=root
spring.cloud.bus.trace.enabled=true
spring.rabbitmq.listener.acknowledge-mode=manual
spring.rabbitmq.publisher-confirms=true
spring.rabbitmq.publisher-returns=true
spring.rabbitmq.listener.max-concurrency=1
spring.rabbitmq.listener.concurrency=1
spring.rabbitmq.listener.retry.enabled=true

3.配置文件【队列、交换机、绑定关系】

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 
 * @Title: RabbitConfig
 * @ProjectName 
 * @Description: RabbitMq相关配置类
 * @date 
 */
@Slf4j
@Component
@Configuration
public class RabbitConfig {

    @Value("${spring.rabbitmq.host}")
    private String host;

    @Value("${spring.rabbitmq.port}")
    private int port;

    @Value("${spring.rabbitmq.username}")
    private String username;

    @Value("${spring.rabbitmq.password}")
    private String password;

    //----------------------mq配置 start---------------------
    //路由key
    public static final String BOX_INVITE_KEY ="box_invite_rout";
    //交换机
    public static final String BOX_INVITE_EXCHANGE = "box_invite_exchange";
    //队列
    public static final String BOX_INVITE_QUEEN = "box_invite_queen";
    //---------------------mq配置 end---------------------

@Bean//队列
    public Queue boxInviteQueue(){
        return new Queue(BOX_INVITE_QUEEN,true);
    }
    @Bean//交换机
    public DirectExchange boxInviteExchange(){
        return new DirectExchange(BOX_INVITE_EXCHANGE,true,false);
    }
    @Bean//建立绑定关系
    public Binding boxInviteBinding() {
        return BindingBuilder.bind(boxInviteQueue()).to(boxInviteExchange()).with(BOX_INVITE_KEY);
        
    }
}

4.生产者

 //mq推送
        String content = JSONObject.toJSONString(userInfo);
        producer.sendMsg(RabbitConfig.BOX_INVITE_EXCHANGE,RabbitConfig.BOX_INVITE_KEY,content);

5.消费者

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ph.wallet.activity.entity.LuckyStarParticipationRecord;
import com.ph.wallet.activity.service.BoxCommonService;
import com.ph.wallet.activity.service.BoxUserAmountService;
import com.ph.wallet.activity.service.lucky.LuckyStarAgentUserService;
import com.ph.wallet.common.config.rabbit.RabbitConfig;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;

/**
 * {@link BoxInviteConsumer}
 *
 * @author 
 * @version 1.0
 */
@Slf4j
@Component
public class BoxInviteConsumer {
    @Autowired
    private BoxUserAmountService boxUserAmountService;
    @Autowired
    private LuckyStarAgentUserService luckyStarAgentUserService;
    @Resource
    private BoxCommonService boxCommonService;

    @RabbitListener(queues = RabbitConfig.BOX_INVITE_QUEEN)
    public void invitationRewardDistributionProcess(Message message, Channel channel) {
        try {
            JSONObject jsonObject = JSON.parseObject(new String(message.getBody()));
            log.info("################mq队列处理开始,拿到的队列数据为:{}", jsonObject.toJSONString());
            boxUserAmountService.invitationRewardDistributionProcess(jsonObject.getString("id"));
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            log.info("################mq队列处理完成数据==================");
        } catch (Exception e) {
            basicNack(message, channel);
            log.error("mq队列处理异常,重新入队", e);
        }
    }

    void basicNack(Message message, Channel channel) {
        try {
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);//手动消费ack 并删除消息
        } catch (IOException e) {
            log.error("BoxInviteController.basicNack :", e);
        }
    }
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值