Java Code Examples for org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus#CONSUME_SUCCESS

The following examples show how to use org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus#CONSUME_SUCCESS . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: WalletPaymentMsgListenerImpl.java    From order-charge-notify with Apache License 2.0 6 votes vote down vote up
/**
 * 钱包扣款关键逻辑
 * @param msgs
 * @param context
 * @return
 */
@Override
public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
    try {
        // 默认msgs只有一条消息
        for (MessageExt msg : msgs) {
            // 消费次数
            int reconsumeTimes = msg.getReconsumeTimes();
            String msgId = msg.getMsgId();
            LOGGER.info("===============msgId={},消费次数={}===============", msgId, reconsumeTimes);
            return walletCharge(msg, msgId);
        }
        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
    } catch (Exception e) {
        LOGGER.error("钱包扣款消费异常,e={}", e);
        return ConsumeConcurrentlyStatus.RECONSUME_LATER;
    }
}
 
Example 2
Source File: RocketMQListenerBindingContainer.java    From spring-cloud-alibaba with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "Duplicates" })
@Override
public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs,
		ConsumeConcurrentlyContext context) {
	for (MessageExt messageExt : msgs) {
		log.debug("received msg: {}", messageExt);
		try {
			long now = System.currentTimeMillis();
			rocketMQListener.onMessage(convertToSpringMessage(messageExt));
			long costTime = System.currentTimeMillis() - now;
			log.debug("consume {} message key:[{}] cost: {} ms",
					messageExt.getMsgId(), messageExt.getKeys(), costTime);
		}
		catch (Exception e) {
			log.warn("consume message failed. messageExt:{}", messageExt, e);
			context.setDelayLevelWhenNextConsume(delayLevelWhenNextConsume);
			return ConsumeConcurrentlyStatus.RECONSUME_LATER;
		}
	}

	return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}
 
Example 3
Source File: ClearUserMessageListener.java    From SpringMVC-Project with MIT License 5 votes vote down vote up
@Override
public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> messageList, ConsumeConcurrentlyContext context) {
    for (MessageExt messageExt : messageList) {
        String message = new String(messageExt.getBody());
        logger.info("收到清除用户消息 | {}", message);
        JSONObject messageJSON = JSON.parseObject(message);
        Long userId = messageJSON.getLong("userId");
        if (userId != null) {
            userLoginLogMapper.deleteAllByUserId(userId);
            logger.info("删除用户登录记录完成 | {}", userId);
        }
    }
    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}
 
Example 4
Source File: RMQDelayListner.java    From rocketmq_trans_message with Apache License 2.0 5 votes vote down vote up
public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs,
    ConsumeConcurrentlyContext consumeConcurrentlyContext) {
    long recvTime = System.currentTimeMillis();
    for (MessageExt msg : msgs) {
        if (isDebug) {
            logger.info(listnerName + ":" + msg);
        }

        msgBodys.addData(new String(msg.getBody()));
        originMsgs.addData(msg);
        msgDelayTimes.addData(Math.abs(recvTime - msg.getBornTimestamp()));
    }
    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}
 
Example 5
Source File: RMQDelayListner.java    From rocketmq-all-4.1.0-incubating with Apache License 2.0 5 votes vote down vote up
public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs,
    ConsumeConcurrentlyContext consumeConcurrentlyContext) {
    long recvTime = System.currentTimeMillis();
    for (MessageExt msg : msgs) {
        if (isDebug) {
            logger.info(listnerName + ":" + msg);
        }

        msgBodys.addData(new String(msg.getBody()));
        originMsgs.addData(msg);
        msgDelayTimes.addData(Math.abs(recvTime - msg.getBornTimestamp()));
    }
    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}
 
Example 6
Source File: RMQDelayListner.java    From rocketmq with Apache License 2.0 5 votes vote down vote up
public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs,
    ConsumeConcurrentlyContext consumeConcurrentlyContext) {
    long recvTime = System.currentTimeMillis();
    for (MessageExt msg : msgs) {
        if (isDebug) {
            logger.info(listenerName + ":" + msg);
        }

        msgBodys.addData(new String(msg.getBody()));
        originMsgs.addData(msg);
        msgDelayTimes.addData(Math.abs(recvTime - msg.getBornTimestamp()));
    }
    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}
 
Example 7
Source File: UacPushMessageListener.java    From paascloud-master with Apache License 2.0 5 votes vote down vote up
/**
 * Consume message consume concurrently status.
 *
 * @param messageExtList             the message ext list
 * @param consumeConcurrentlyContext the consume concurrently context
 *
 * @return the consume concurrently status
 */
@Override
@MqConsumerStore
public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> messageExtList, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
	MessageExt msg = messageExtList.get(0);
	String body = new String(msg.getBody());
	String topicName = msg.getTopic();
	String tags = msg.getTags();
	String keys = msg.getKeys();

	try {
		MqMessage.checkMessage(body, topicName, tags, keys);
		String mqKV = redisService.getKey(keys);
		if (PublicUtil.isNotEmpty(mqKV)) {
			log.error("MQ消费Topic={},tag={},key={}, 重复消费", topicName, tags, keys);
			return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
		}
		if (AliyunMqTopicConstants.MqTopicEnum.TPC_TOPIC.getTopic().equals(topicName)) {
			mqMessageService.deleteMessageTopic(body, tags);
		} else {
			log.info("OPC订单信息消 topicName={} 不存在", topicName);
		}
	} catch (IllegalArgumentException ex) {
		log.error("校验MQ message 失败 ex={}", ex.getMessage(), ex);
	} catch (Exception e) {
		log.error("处理MQ message 失败 topicName={}, keys={}, ex={}", topicName, keys, e.getMessage(), e);
		return ConsumeConcurrentlyStatus.RECONSUME_LATER;
	}

	redisService.setKey(keys, keys, 10, TimeUnit.DAYS);
	return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}
 
Example 8
Source File: RockMqTestCase.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
@Override
public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> messages, ConsumeConcurrentlyContext context) {
    for (MessageExt message : messages) {
        String body = new String(message.getBody(), StringUtility.CHARSET);
        System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "消费响应:msgId : " + message.getMsgId() + ",  msgBody : " + body);// 输出消息内容
        semaphore.release(1);
    }

    // 返回消费状态
    // CONSUME_SUCCESS 消费成功
    // RECONSUME_LATER 消费失败,需要重新消费
    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}
 
Example 9
Source File: RMQDelayListner.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs,
    ConsumeConcurrentlyContext consumeConcurrentlyContext) {
    long recvTime = System.currentTimeMillis();
    for (MessageExt msg : msgs) {
        if (isDebug) {
            logger.info(listenerName + ":" + msg);
        }

        msgBodys.addData(new String(msg.getBody()));
        originMsgs.addData(msg);
        msgDelayTimes.addData(Math.abs(recvTime - msg.getBornTimestamp()));
    }
    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}
 
Example 10
Source File: RMQDelayListner.java    From rocketmq with Apache License 2.0 5 votes vote down vote up
public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs,
    ConsumeConcurrentlyContext consumeConcurrentlyContext) {
    long recvTime = System.currentTimeMillis();
    for (MessageExt msg : msgs) {
        if (isDebug) {
            logger.info(listnerName + ":" + msg);
        }

        msgBodys.addData(new String(msg.getBody()));
        originMsgs.addData(msg);
        msgDelayTimes.addData(Math.abs(recvTime - msg.getBornTimestamp()));
    }
    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}
 
Example 11
Source File: ChatRecordMessageListener.java    From SpringMVC-Project with MIT License 5 votes vote down vote up
@Override
public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> messageList, ConsumeConcurrentlyContext context) {
    for (MessageExt messageExt : messageList) {
        String message = new String(messageExt.getBody());
        logger.info("收到聊天记录消息 | {}", message);
        JSONObject messageJSON = JSON.parseObject(message);
        chatService.saveChatRecord(messageJSON.getString("userName"), messageJSON.getString("content"), messageJSON.getLongValue("timestamp"));
    }
    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}
 
Example 12
Source File: ConsumeMessageConcurrentlyServiceTest.java    From rocketmq with Apache License 2.0 5 votes vote down vote up
@Ignore
@Test
public void testPullMessage_ConsumeSuccess() throws InterruptedException, RemotingException, MQBrokerException, NoSuchFieldException,Exception {
    final CountDownLatch countDownLatch = new CountDownLatch(1);
    final MessageExt[] messageExts = new MessageExt[1];

    ConsumeMessageConcurrentlyService  normalServie = new ConsumeMessageConcurrentlyService(pushConsumer.getDefaultMQPushConsumerImpl(), new MessageListenerConcurrently() {
        @Override
        public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs,
                                                        ConsumeConcurrentlyContext context) {
            messageExts[0] = msgs.get(0);
            countDownLatch.countDown();
            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        }
    });
    pushConsumer.getDefaultMQPushConsumerImpl().setConsumeMessageService(normalServie);

    PullMessageService pullMessageService = mQClientFactory.getPullMessageService();
    pullMessageService.executePullRequestImmediately(createPullRequest());
    countDownLatch.await();

    Thread.sleep(1000);

    org.apache.rocketmq.common.protocol.body.ConsumeStatus stats = normalServie.getConsumerStatsManager().consumeStatus(pushConsumer.getDefaultMQPushConsumerImpl().groupName(),topic);

    ConsumerStatsManager mgr  =   normalServie.getConsumerStatsManager();

    Field statItmeSetField = mgr.getClass().getDeclaredField("topicAndGroupConsumeOKTPS");
    statItmeSetField.setAccessible(true);

    StatsItemSet itemSet = (StatsItemSet)statItmeSetField.get(mgr);
    StatsItem item = itemSet.getAndCreateStatsItem(topic + "@" + pushConsumer.getDefaultMQPushConsumerImpl().groupName());

    assertThat(item.getValue().get()).isGreaterThan(0L);
    assertThat(messageExts[0].getTopic()).isEqualTo(topic);
    assertThat(messageExts[0].getBody()).isEqualTo(new byte[] {'a'});
}
 
Example 13
Source File: AbstractMQPushConsumer.java    From rocketmq-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
/**
 * 原生dealMessage方法,可以重写此方法自定义序列化和返回消费成功的相关逻辑
 *
 * @param list 消息列表
 * @param consumeConcurrentlyContext 上下文
 * @return 消费状态
 */
public ConsumeConcurrentlyStatus dealMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
    for(MessageExt messageExt : list) {
        log.debug("receive msgId: {}, tags : {}" , messageExt.getMsgId(), messageExt.getTags());
        // parse message body
        T t = parseMessage(messageExt);
        // parse ext properties
        Map<String, Object> ext = parseExtParam(messageExt);
        if( null != t && !process(t, ext)) {
            log.warn("consume fail , ask for re-consume , msgId: {}", messageExt.getMsgId());
            return ConsumeConcurrentlyStatus.RECONSUME_LATER;
        }
    }
    return  ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}
 
Example 14
Source File: RMQDelayListner.java    From rocketmq-read with Apache License 2.0 5 votes vote down vote up
public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs,
    ConsumeConcurrentlyContext consumeConcurrentlyContext) {
    long recvTime = System.currentTimeMillis();
    for (MessageExt msg : msgs) {
        if (isDebug) {
            logger.info(listenerName + ":" + msg);
        }

        msgBodys.addData(new String(msg.getBody()));
        originMsgs.addData(msg);
        msgDelayTimes.addData(Math.abs(recvTime - msg.getBornTimestamp()));
    }
    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}
 
Example 15
Source File: RMQDelayListner.java    From rocketmq-4.3.0 with Apache License 2.0 5 votes vote down vote up
public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs,
    ConsumeConcurrentlyContext consumeConcurrentlyContext) {
    long recvTime = System.currentTimeMillis();
    for (MessageExt msg : msgs) {
        if (isDebug) {
            logger.info(listenerName + ":" + msg);
        }

        msgBodys.addData(new String(msg.getBody()));
        originMsgs.addData(msg);
        msgDelayTimes.addData(Math.abs(recvTime - msg.getBornTimestamp()));
    }
    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}
 
Example 16
Source File: RMQDelayListner.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs,
    ConsumeConcurrentlyContext consumeConcurrentlyContext) {
    long recvTime = System.currentTimeMillis();
    for (MessageExt msg : msgs) {
        if (isDebug) {
            logger.info(listenerName + ":" + msg);
        }

        msgBodys.addData(new String(msg.getBody()));
        originMsgs.addData(msg);
        msgDelayTimes.addData(Math.abs(recvTime - msg.getBornTimestamp()));
    }
    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}
 
Example 17
Source File: SecKillChargeOrderListenerImpl.java    From seckill-rocketmq with Apache License 2.0 4 votes vote down vote up
/**
 * 秒杀核心消费逻辑
 * @param msgs
 * @param context
 * @return
 */
@Override
public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
    try {
        for (MessageExt msg : msgs) {
            // 消息解码
            String message = new String(msg.getBody());
            int reconsumeTimes = msg.getReconsumeTimes();
            String msgId = msg.getMsgId();
            String logSuffix = ",msgId=" + msgId + ",reconsumeTimes=" + reconsumeTimes;
            LOGGER.info("[秒杀订单消费者]-SecKillChargeOrderConsumer-接收到消息,message={},{}", message, logSuffix);

            // 反序列化协议实体
            ChargeOrderMsgProtocol chargeOrderMsgProtocol = new ChargeOrderMsgProtocol();
            chargeOrderMsgProtocol.decode(message);
            LOGGER.info("[秒杀订单消费者]-SecKillChargeOrderConsumer-反序列化为秒杀入库订单实体chargeOrderMsgProtocol={},{}", chargeOrderMsgProtocol.toString(), logSuffix);

            // 消费幂等:查询orderId对应订单是否已存在
            String orderId = chargeOrderMsgProtocol.getOrderId();
            OrderInfoDobj orderInfoDobj = secKillOrderService.queryOrderInfoById(orderId);
            if (orderInfoDobj != null) {
                LOGGER.info("[秒杀订单消费者]-SecKillChargeOrderConsumer-当前订单已入库,不需要重复消费!,orderId={},{}", orderId, logSuffix);
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }

            // 业务幂等:同一个prodId+同一个userPhoneNo只有一个秒杀订单
            OrderInfoDO orderInfoDO = new OrderInfoDO();
            orderInfoDO.setProdId(chargeOrderMsgProtocol.getProdId())
                    .setUserPhoneNo(chargeOrderMsgProtocol.getUserPhoneNo());
            Result result = secKillOrderService.queryOrder(orderInfoDO);
            if (result != null && result.getCode().equals(CodeMsg.SUCCESS.getCode())) {
                LOGGER.info("[秒杀订单消费者]-SecKillChargeOrderConsumer-当前用户={},秒杀的产品={}订单已存在,不得重复秒杀,orderId={}",
                        orderInfoDO.getUserPhoneNo(), orderInfoDO.getProdId(), orderId);
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }

            // 秒杀订单入库
            OrderInfoDO orderInfoDODB = new OrderInfoDO();
            BeanUtils.copyProperties(chargeOrderMsgProtocol, orderInfoDODB);

            // 库存校验
            String prodId = chargeOrderMsgProtocol.getProdId();
            SecKillProductDobj productDobj = secKillProductService.querySecKillProductByProdId(prodId);
            // 取库存校验
            int currentProdStock = productDobj.getProdStock();
            if (currentProdStock <= 0) {
                LOGGER.info("[decreaseProdStock]当前商品已售罄,消息消费成功!prodId={},currStock={}", prodId, currentProdStock);
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
            // 正式下单
            if (secKillOrderService.chargeSecKillOrder(orderInfoDODB)) {
                LOGGER.info("[秒杀订单消费者]-SecKillChargeOrderConsumer-秒杀订单入库成功,消息消费成功!,入库实体orderInfoDO={},{}", orderInfoDO.toString(), logSuffix);
                // 模拟订单处理,直接修改订单状态为处理中
                secKillOrderService.updateOrderStatusDealing(orderInfoDODB);
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
            return ConsumeConcurrentlyStatus.RECONSUME_LATER;
        }
    } catch (Exception e) {
        LOGGER.info("[秒杀订单消费者]消费异常,e={}", LogExceptionWapper.getStackTrace(e));
    }
    return ConsumeConcurrentlyStatus.RECONSUME_LATER;
}
 
Example 18
Source File: OptPushMessageListener.java    From paascloud-master with Apache License 2.0 4 votes vote down vote up
/**
 * Consume message consume concurrently status.
 *
 * @param messageExtList             the message ext list
 * @param consumeConcurrentlyContext the consume concurrently context
 *
 * @return the consume concurrently status
 */
@Override
@MqConsumerStore
public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> messageExtList, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
	MessageExt msg = messageExtList.get(0);
	String body = new String(msg.getBody());
	String topicName = msg.getTopic();
	String tags = msg.getTags();
	String keys = msg.getKeys();
	log.info("MQ消费Topic={},tag={},key={}", topicName, tags, keys);
	ValueOperations<String, String> ops = srt.opsForValue();
	// 控制幂等性使用的key
	try {
		MqMessage.checkMessage(body, topicName, tags, keys);
		String mqKV = null;
		if (srt.hasKey(keys)) {
			mqKV = ops.get(keys);
		}
		if (PublicUtil.isNotEmpty(mqKV)) {
			log.error("MQ消费Topic={},tag={},key={}, 重复消费", topicName, tags, keys);
			return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
		}
		if (AliyunMqTopicConstants.MqTopicEnum.SEND_SMS_TOPIC.getTopic().equals(topicName)) {
			optSendSmsTopicService.handlerSendSmsTopic(body, topicName, tags, keys);
		}
		if (AliyunMqTopicConstants.MqTopicEnum.SEND_EMAIL_TOPIC.getTopic().equals(topicName)) {
			optSendEmailTopicService.handlerSendEmailTopic(body, topicName, tags, keys);
		}
		if (AliyunMqTopicConstants.MqTopicEnum.TPC_TOPIC.getTopic().equals(topicName)) {
			mqMessageService.deleteMessageTopic(body, tags);
		}
		if (AliyunMqTopicConstants.MqTopicEnum.MDC_TOPIC.getTopic().equals(topicName)) {
			mdcTopicConsumer.handlerSendSmsTopic(body, topicName, tags, keys);
		} else {
			log.info("OPC订单信息消 topicName={} 不存在", topicName);
		}
	} catch (IllegalArgumentException ex) {
		log.error("校验MQ message 失败 ex={}", ex.getMessage(), ex);
	} catch (Exception e) {
		log.error("处理MQ message 失败 topicName={}, keys={}, ex={}", topicName, keys, e.getMessage(), e);
		return ConsumeConcurrentlyStatus.RECONSUME_LATER;
	}
	ops.set(keys, keys, 10, TimeUnit.DAYS);
	return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}
 
Example 19
Source File: NotifySendListenerImpl.java    From order-charge-notify with Apache License 2.0 4 votes vote down vote up
/**
 * 进行通知POST报文发送
 * @param reconsumeTimes
 * @param logSuffix
 * @param protocol
 * @param notifyUrl
 * @param purseId
 * @param chargeNotifyRequest
 * @return
 * @throws MQClientException
 * @throws RemotingException
 * @throws MQBrokerException
 * @throws InterruptedException
 */
private ConsumeConcurrentlyStatus sendNotifyByPost(int reconsumeTimes, String logSuffix, OrderResultNofityProtocol protocol, String notifyUrl, String purseId, ChargeNotifyRequest chargeNotifyRequest) throws MQClientException, RemotingException, MQBrokerException, InterruptedException {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    //  封装参数,千万不要替换为Map与HashMap,否则参数无法传递
    MultiValueMap<String, String> params= new LinkedMultiValueMap<String, String>();
    params.add("order_status", chargeNotifyRequest.getOrder_status());
    params.add("channel_orderid", chargeNotifyRequest.getChannel_orderid());
    params.add("plat_orderid", chargeNotifyRequest.getPlat_orderid());
    params.add("finish_time", chargeNotifyRequest.getFinish_time());
    params.add("sign", chargeNotifyRequest.getSign());
    HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(params, headers);
    ResponseEntity<String> notifyResponse = restTemplate.exchange(
            notifyUrl, HttpMethod.POST, requestEntity, String.class);
    // 返回参校验
    if (notifyResponse == null) {
        LOGGER.error("[通知发送消息消费者]-OrderNotifySendProducer-当前商户通知返回为空,等待下次通知.purseId={},{}", purseId, logSuffix);
        return ConsumeConcurrentlyStatus.RECONSUME_LATER;
    }
    if (reconsumeTimes > MAX_RECONSUME_TIMES) {
        // TODO 入冲发表
        LOGGER.info("[通知发送消息消费者]-OrderNotifySendProducer-当前商户通知次数大于5次,不再通知,purseId={},{}", purseId, logSuffix);
        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
    }
    // 解析返回参
    String notifyBody = notifyResponse.getBody();
    LOGGER.info("[通知发送消息消费者]-OrderNotifySendProducer-订单结果通知出参:[{}],{}", notifyBody, logSuffix);
    if (!NotifyConstant.NOTIFY_RETURN_SUCC.equals(notifyBody)) {
        LOGGER.info("[通知发送消息消费者]-OrderNotifySendProducer-订单结果通知[失败],等待下次通知.purseId={},{}", purseId, logSuffix);
        return ConsumeConcurrentlyStatus.RECONSUME_LATER;
    }
    // 通知成功,发送订单状态更新消息,事件=EVENT_UPDATE_NOTIFY_OD_STATUS
    OrderStatusUpdateProtocol orderStatusUpdateProtocol = new OrderStatusUpdateProtocol();
    orderStatusUpdateProtocol.setTopicName(MessageProtocolConst.ORDER_STATUS_UPDATE_TOPIC.getTopic());
    orderStatusUpdateProtocol.setOrderId(protocol.getOrderId())
            .setChargeMoney(protocol.getChargeMoney())
            .setPurseId(protocol.getPurseId())
            .setMerchantName(protocol.getMerchantName())
            .setEventType(UpdateEventTypeConst.EVENT_UPDATE_NOTIFY_OD_STATUS.getEventType());
    Message updateOrderStatusMsg =
            new Message(MessageProtocolConst.ORDER_STATUS_UPDATE_TOPIC.getTopic(),
                    orderStatusUpdateProtocol.encode().getBytes());
    orderStatusUpdateProducer.getProducer().send(updateOrderStatusMsg);
    LOGGER.info("[通知发送消息消费者]-OrderNotifySendProducer-发送通知状态更新消息结束,purseId={},{}", purseId, logSuffix);
    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}
 
Example 20
Source File: WalletPaymentMsgListenerImpl.java    From order-charge-notify with Apache License 2.0 4 votes vote down vote up
/**
 * 钱包扣款,并插入扣款流水
 *
 * @param msg
 */
private ConsumeConcurrentlyStatus walletCharge(MessageExt msg, String msgId) {
    String message = new String(msg.getBody());
    LOGGER.info("msgId={},钱包扣款消费者接收到消息,message={}", msgId, message);
    WalletPaymentProtocol payProtocol = new WalletPaymentProtocol();
    payProtocol.decode(message);

    // 幂等消费逻辑: 根据订单号查询扣款流水,如果存在则直接返回消费成功
    String orderId = payProtocol.getOrderId();
    ChargeRecordEntity chargeRecordEntity = walletService.queryChargeRecordByOrderId(orderId);
    if (chargeRecordEntity != null) {
        LOGGER.info("[扣款本地事务回查]-本地已经存在orderId=[{}]对应的扣款流水,不需要重复消费,msgId={}", orderId, msgId);
        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
    }

    try {
        // 组装半消息:扣款成功修改订单状态为成功,消息事件=修改订单支付状态
        OrderStatusUpdateProtocol orderStatusUpdateProtocol = new OrderStatusUpdateProtocol();
        orderStatusUpdateProtocol.setTopicName(MessageProtocolConst.ORDER_STATUS_UPDATE_TOPIC.getTopic());
        orderStatusUpdateProtocol.setOrderId(payProtocol.getOrderId())
                .setChargeMoney(payProtocol.getChargeMoney())
                .setPurseId(payProtocol.getPurseId())
                .setMerchantName(payProtocol.getMerchantName())
                .setEventType(UpdateEventTypeConst.EVENT_UPDATE_PAY_STATUS.getEventType());

        Message updateOrderStatusMsg =
                new Message(MessageProtocolConst.ORDER_STATUS_UPDATE_TOPIC.getTopic(),
                        orderStatusUpdateProtocol.encode().getBytes());
        // 半消息发送
        TransactionSendResult transactionSendResult = orderStatusUpdateProducer.getProducer()
                /**
                 * sendMessageInTransaction(final Message msg,
                 * final Object arg) 第二个参数为回调参数,可以为null,
                 * 该参数和LocalTransactionState executeLocalTransaction(Message msg, Object arg)第二个参数为同一个值
                 */
                .sendMessageInTransaction(updateOrderStatusMsg, null);
        if (transactionSendResult == null) {
            // 发送未知重新消费
            LOGGER.info("msgId={},订单状态更新半消息发送状态未知,消费状态[RECONSUME_LATER],等待重新消费,orderId={}", msgId, payProtocol.getOrderId(), message);
            return ConsumeConcurrentlyStatus.RECONSUME_LATER;
        }
        if (transactionSendResult.getLocalTransactionState().equals(LocalTransactionState.COMMIT_MESSAGE)) {
            LOGGER.info("msgId={},订单状态更新半消息发送成功,消费状态[CONSUME_SUCCESS],orderId={},sendResult={}", msgId, payProtocol.getOrderId(), transactionSendResult);
            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        }
        if (transactionSendResult.getLocalTransactionState().equals(LocalTransactionState.UNKNOW)) {
            LOGGER.warn("msgId={},订单状态更新本地事务执行状态未知,半消息发送未知,消费状态[RECONSUME_LATER],orderId={},sendResult={}", msgId, payProtocol.getOrderId(), transactionSendResult);
            return ConsumeConcurrentlyStatus.RECONSUME_LATER;
        }
    } catch (Exception e) {
        LOGGER.error("msgId={},订单状态更新半消息发送异常,消费状态[RECONSUME_LATER],e={}", msgId, LogExceptionWapper.getStackTrace(e));
    }
    return ConsumeConcurrentlyStatus.RECONSUME_LATER;
}