RabbitMQ

RabbitMQ

配置

    import org.springframework.amqp.core.*;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
​
​
    @Configuration
    public class OARabbitMqConfig {
​
        //
        //更新OA 交换机
        public static final String OA_EXCHANGE = "oa.info.exchange";
        //更新OA 路由的 key
        public static final String OA_ROUTING_KEY = "oa.info.key";
        //更新OA 队列名称
        public static final String OA_QUEUE = "oa.info.queue";
​
​
        //更新OA 死信交换机
        public static final String OA_ERROR_EXCHANGE = "oa.error.exchange";
        public static final String OA_ERROR_ROUTING_KEY = "oa.error.key";
        public static final String OA_ERROR_QUEUE = "oa.error.queue";
​
​
        //OA 队列声明
        @Bean
        public Queue oaQueue() {
            return QueueBuilder.durable(OA_QUEUE)
                    .deadLetterExchange(OA_ERROR_EXCHANGE)
                    .deadLetterRoutingKey(OA_ERROR_ROUTING_KEY)
                    .ttl(1296000000)
                    .build();
        }
​
        //OA 直连交换机
        @Bean
        public DirectExchange oaExchange() {
            return ExchangeBuilder.directExchange(OA_EXCHANGE).delayed().durable(true).build();
        }
​
​
        //OA 队列绑定
        @Bean
        public Binding oaBinding() {
            return BindingBuilder.bind(oaQueue()).to(oaExchange()).with(OA_ROUTING_KEY);
        }
​
​
        @Bean
        public DirectExchange oaErrorExchange() {
            return new DirectExchange(OA_ERROR_EXCHANGE);
        }
​
​
        @Bean
        public Queue oaErrorQueue() {
            return QueueBuilder
                    //指定队列名称,并持久化
                    .durable(OA_ERROR_QUEUE)
                    //设置队列的超时时间,15天
                    .ttl(1296000000)
                    //指定死信交换机
                    .build();
        }
​
        @Bean
        public Binding oaErrorBinding() {
            return BindingBuilder.bind(oaErrorQueue()).to(oaErrorExchange()).with(OA_ERROR_ROUTING_KEY);
        }
​
​
    }

 

消费者

获取rabbitMQ消息队列里面的数据

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;
​
import java.io.IOException;
import java.util.List;
​
@Component
@Slf4j
public class OAConsumer {
​
​
    @RabbitHandler
    @RabbitListener(queues = OARabbitMqConfig.OA_QUEUE)
    public void receive(Message message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) throws IOException {
        try {
            ObjectMapper objectMapper = SpringUtils.getBean(ObjectMapper.class);
            OAQueueMessage oaQueueMessage = objectMapper.readValue(message.getBody(), OAQueueMessage.class);
            if (OAProducer.FLOW_TYPE_RCV.intValue() == oaQueueMessage.getFlowType().intValue()) {
                ObjectMapper mapper = SpringUtils.getBean(ObjectMapper.class);
                List<Long> oaIds = mapper.readValue(oaQueueMessage.getJsonParams(), new TypeReference<List<Long>>() {
                });
                IUfCgddtxmService ufCgddtxmService = SpringUtils.getBean(IUfCgddtxmService.class);
                //sql server in 只支持2100的数量
                int batchSize = 2000;
                int totalData = oaIds.size();
                int startIndex = 0;
                while (startIndex < totalData) {
                    int endIndex = Math.min(startIndex + batchSize, totalData);
                    List<Long> subOAIds = oaIds.subList(startIndex, endIndex);
                    ufCgddtxmService.updateSfyshByIds(subOAIds);
                    startIndex += batchSize;
                }
            }
            log.info("oa:timeAt:[{}];deliveryTag:[{}];message:[{}]", DateUtils.dateTimeNow(), deliveryTag, oaQueueMessage);
            //不批量的ACK该消息
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            log.info("oa:timeAt:[{}];deliveryTag:[{}];errorMsh:[{}]", DateUtils.dateTimeNow(), deliveryTag, e.getMessage());
            //不批量的NACK该消息,并且投入死信队列
            channel.basicNack(deliveryTag, false, false);
        }
    }
​
}

 

生产者

/**
 *
 */
@Component
@Slf4j
public class OAProducer {
​
    //已收货
    public static final Integer FLOW_TYPE_RCV = 1;
​
    @Autowired
    private RabbitTemplate rabbitTemplate;
​
    @Autowired
    private ConfirmCallback confirmCallback;
​
    @Autowired
    ObjectMapper objectMapper;
​
​
    @PostConstruct
    public void init() {
        //消息发送给交换机会调用该类的confirm方法
        rabbitTemplate.setConfirmCallback(confirmCallback);
    }
​
    /**
     *
     */
    public void sendMessage(String jsonParams, Integer flowType) {
        try {
            OAQueueMessage oaQueueMessage = new OAQueueMessage();
            oaQueueMessage.setJsonParams(jsonParams);
            oaQueueMessage.setFlowType(flowType);
            byte[] bytes = objectMapper.writeValueAsString(oaQueueMessage).getBytes(StandardCharsets.UTF_8);
            CorrelationData correlationData = new CorrelationData();
            Message message = MessageBuilder.withBody(bytes)
                    .setDeliveryMode(MessageDeliveryMode.PERSISTENT)
                    .build();
            correlationData.setReturnedMessage(message);
            rabbitTemplate.convertAndSend(OARabbitMqConfig.OA_EXCHANGE, OARabbitMqConfig.OA_ROUTING_KEY, message, correlationData);
        } catch (JsonProcessingException e) {
            throw new UtilException("发送消息异常" + e.getMessage());
        }
    }
}

 

应用层

直接调用生产者的sendMessage方法

//发送更新oa数据消息<已收货>
oaProducer.sendMessage(BeanUtils.toJson(oaIds), OAProducer.FLOW_TYPE_RCV);

 

posted @ 2024-01-25 09:28  jessi呀  阅读(5)  评论(0编辑  收藏  举报