|
291 | 291 |
|
292 | 292 | #### 定时消息
|
293 | 293 |
|
294 |
| -在分布式定时调度触发、任务超时处理等场景,需要实现精准、可靠的定时事件触发。使用 RocketMQ 的定时消息可以简化定时调度任务的开发逻辑,实现高性能、可扩展、高可靠的定时触发能力。定时消息仅支持在 MessageType 为 Delay 的主题内使用,即定时消息只能发送至类型为定时消息的主题中,发送的消息的类型必须和主题的类型一致。 |
| 294 | +在分布式定时调度触发、任务超时处理等场景,需要实现精准、可靠的定时事件触发。使用 RocketMQ 的定时消息可以简化定时调度任务的开发逻辑,实现高性能、可扩展、高可靠的定时触发能力。定时消息仅支持在 MessageType 为 Delay 的主题内使用,即定时消息只能发送至类型为定时消息的主题中,发送的消息的类型必须和主题的类型一致。在 4.x 版本中,只支持延时消息,默认分为18个等级分别为:1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h,也可以在配置文件中增加自定义的延时等级和时长。在 5.x 版本中,开始支持定时消息,在构造消息时提供了 3 个 API 来指定延迟时间或定时时间。 |
295 | 295 |
|
296 | 296 | 基于定时消息的超时任务处理具备如下优势:
|
297 | 297 |
|
|
319 | 319 |
|
320 | 320 | #### 事务消息
|
321 | 321 |
|
322 |
| -保证本地事务与发送消息是原子性的操作 |
| 322 | +事务消息是 Apache RocketMQ 提供的一种高级消息类型,支持在分布式场景下保障消息生产和本地事务的最终一致性。简单来讲,就是将本地事务(数据库的DML操作)与发送消息合并在同一个事务中。例如,新增一个订单。在事务未提交之前,不发送订阅的消息。发送消息的动作随着事务的成功提交而发送,随着事务的回滚而取消。当然真正地处理过程不止这么简单,包含了半消息、事务监听和事务回查等概念,下面有更详细的说明。 |
323 | 323 |
|
324 | 324 | ## 关于发送消息
|
325 | 325 |
|
@@ -540,6 +540,210 @@ emmm,就两个字—— **幂等** 。在编程中一个*幂等* 操作的特
|
540 | 540 |
|
541 | 541 | 你还需要注意的是,在 `MQ Server` 指向系统 B 的操作已经和系统 A 不相关了,也就是说在消息队列中的分布式事务是——**本地事务和存储消息到消息队列才是同一个事务**。这样也就产生了事务的**最终一致性**,因为整个过程是异步的,**每个系统只要保证它自己那一部分的事务就行了**。
|
542 | 542 |
|
| 543 | +实践中会遇到的问题:事务消息需要一个事务监听器来监听本地事务是否成功,并且事务监听器接口只允许被实现一次。那就意味着需要把各种事务消息的本地事务都写在一个接口方法里面,必将会产生大量的耦合和类型判断。采用函数 Function 接口来包装整个业务过程,作为一个参数传递到监听器的接口方法中。再调用 Function 的 apply() 方法来执行业务,事务也会在 apply() 方法中执行。让监听器与业务之间实现解耦,使之具备了真实生产环境中的可行性。 |
| 544 | + |
| 545 | +1.模拟一个添加用户浏览记录的需求 |
| 546 | +```java |
| 547 | +@PostMapping("/add") |
| 548 | +@ApiOperation("添加用户浏览记录") |
| 549 | +public Result<TransactionSendResult> add(Long userId, Long forecastLogId) { |
| 550 | + |
| 551 | + // 函数式编程:浏览记录入库 |
| 552 | + Function<String, Boolean> function = transactionId -> viewHistoryHandler.addViewHistory(transactionId, userId, forecastLogId); |
| 553 | + |
| 554 | + Map<String, Long> hashMap = new HashMap<>(); |
| 555 | + hashMap.put("userId", userId); |
| 556 | + hashMap.put("forecastLogId", forecastLogId); |
| 557 | + String jsonString = JSON.toJSONString(hashMap); |
| 558 | + |
| 559 | + // 发送事务消息;将本地的事务操作,用函数Function接口接收,作为一个参数传入到方法中 |
| 560 | + TransactionSendResult transactionSendResult = mqProducerService.sendTransactionMessage(jsonString, MQDestination.TAG_ADD_VIEW_HISTORY, function); |
| 561 | + return Result.success(transactionSendResult); |
| 562 | +} |
| 563 | +``` |
| 564 | + |
| 565 | +2.发送事务消息的方法 |
| 566 | +```java |
| 567 | +/** |
| 568 | + * 发送事务消息 |
| 569 | + * |
| 570 | + * @param msgBody |
| 571 | + * @param tag |
| 572 | + * @param function |
| 573 | + * @return |
| 574 | + */ |
| 575 | +public TransactionSendResult sendTransactionMessage(String msgBody, String tag, Function<String, Boolean> function) { |
| 576 | + // 构建消息体 |
| 577 | + Message<String> message = buildMessage(msgBody); |
| 578 | + |
| 579 | + // 构建消息投递信息 |
| 580 | + String destination = buildDestination(tag); |
| 581 | + |
| 582 | + TransactionSendResult result = rocketMQTemplate.sendMessageInTransaction(destination, message, function); |
| 583 | + return result; |
| 584 | +} |
| 585 | +``` |
| 586 | + |
| 587 | +3.生产者消息监听器,只允许一个类去实现该监听器 |
| 588 | +```java |
| 589 | +@Slf4j |
| 590 | +@RocketMQTransactionListener |
| 591 | +public class TransactionMsgListener implements RocketMQLocalTransactionListener { |
| 592 | + |
| 593 | + @Autowired |
| 594 | + private RedisService redisService; |
| 595 | + |
| 596 | + /** |
| 597 | + * 执行本地事务(在发送消息成功时执行) |
| 598 | + * |
| 599 | + * @param message |
| 600 | + * @param o |
| 601 | + * @return commit or rollback or unknown |
| 602 | + */ |
| 603 | + @Override |
| 604 | + public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) { |
| 605 | + |
| 606 | + // 1、获取事务ID |
| 607 | + String transactionId = null; |
| 608 | + try { |
| 609 | + transactionId = message.getHeaders().get("rocketmq_TRANSACTION_ID").toString(); |
| 610 | + // 2、判断传入函数对象是否为空,如果为空代表没有要执行的业务直接抛弃消息 |
| 611 | + if (o == null) { |
| 612 | + //返回ROLLBACK状态的消息会被丢弃 |
| 613 | + log.info("事务消息回滚,没有需要处理的业务 transactionId={}", transactionId); |
| 614 | + return RocketMQLocalTransactionState.ROLLBACK; |
| 615 | + } |
| 616 | + // 将Object o转换成Function对象 |
| 617 | + Function<String, Boolean> function = (Function<String, Boolean>) o; |
| 618 | + // 执行业务 事务也会在function.apply中执行 |
| 619 | + Boolean apply = function.apply(transactionId); |
| 620 | + if (apply) { |
| 621 | + log.info("事务提交,消息正常处理 transactionId={}", transactionId); |
| 622 | + //返回COMMIT状态的消息会立即被消费者消费到 |
| 623 | + return RocketMQLocalTransactionState.COMMIT; |
| 624 | + } |
| 625 | + } catch (Exception e) { |
| 626 | + log.info("出现异常 返回ROLLBACK transactionId={}", transactionId); |
| 627 | + return RocketMQLocalTransactionState.ROLLBACK; |
| 628 | + } |
| 629 | + return RocketMQLocalTransactionState.ROLLBACK; |
| 630 | + } |
| 631 | + |
| 632 | + /** |
| 633 | + * 事务回查机制,检查本地事务的状态 |
| 634 | + * |
| 635 | + * @param message |
| 636 | + * @return |
| 637 | + */ |
| 638 | + @Override |
| 639 | + public RocketMQLocalTransactionState checkLocalTransaction(Message message) { |
| 640 | + |
| 641 | + String transactionId = message.getHeaders().get("rocketmq_TRANSACTION_ID").toString(); |
| 642 | + |
| 643 | + // 查redis |
| 644 | + MqTransaction mqTransaction = redisService.getCacheObject("mqTransaction:" + transactionId); |
| 645 | + if (Objects.isNull(mqTransaction)) { |
| 646 | + return RocketMQLocalTransactionState.ROLLBACK; |
| 647 | + } |
| 648 | + return RocketMQLocalTransactionState.COMMIT; |
| 649 | + } |
| 650 | +} |
| 651 | +``` |
| 652 | + |
| 653 | +4.模拟的业务场景,这里的方法必须提取出来,放在别的类里面.如果调用方与被调用方在同一个类中,会发生事务失效的问题. |
| 654 | +```java |
| 655 | +@Component |
| 656 | +public class ViewHistoryHandler { |
| 657 | + |
| 658 | + @Autowired |
| 659 | + private IViewHistoryService viewHistoryService; |
| 660 | + |
| 661 | + @Autowired |
| 662 | + private IMqTransactionService mqTransactionService; |
| 663 | + |
| 664 | + @Autowired |
| 665 | + private RedisService redisService; |
| 666 | + |
| 667 | + /** |
| 668 | + * 浏览记录入库 |
| 669 | + * |
| 670 | + * @param transactionId |
| 671 | + * @param userId |
| 672 | + * @param forecastLogId |
| 673 | + * @return |
| 674 | + */ |
| 675 | + @Transactional |
| 676 | + public Boolean addViewHistory(String transactionId, Long userId, Long forecastLogId) { |
| 677 | + // 构建浏览记录 |
| 678 | + ViewHistory viewHistory = new ViewHistory(); |
| 679 | + viewHistory.setUserId(userId); |
| 680 | + viewHistory.setForecastLogId(forecastLogId); |
| 681 | + viewHistory.setCreateTime(LocalDateTime.now()); |
| 682 | + boolean save = viewHistoryService.save(viewHistory); |
| 683 | + |
| 684 | + // 本地事务信息 |
| 685 | + MqTransaction mqTransaction = new MqTransaction(); |
| 686 | + mqTransaction.setTransactionId(transactionId); |
| 687 | + mqTransaction.setCreateTime(new Date()); |
| 688 | + mqTransaction.setStatus(MqTransaction.StatusEnum.VALID.getStatus()); |
| 689 | + |
| 690 | + // 1.可以把事务信息存数据库 |
| 691 | + mqTransactionService.save(mqTransaction); |
| 692 | + |
| 693 | + // 2.也可以选择存redis,4个小时有效期,'4个小时'是RocketMQ内置的最大回查超时时长,过期未确认将强制回滚 |
| 694 | + redisService.setCacheObject("mqTransaction:" + transactionId, mqTransaction, 4L, TimeUnit.HOURS); |
| 695 | + |
| 696 | + // 放开注释,模拟异常,事务回滚 |
| 697 | + // int i = 10 / 0; |
| 698 | + |
| 699 | + return save; |
| 700 | + } |
| 701 | +} |
| 702 | +``` |
| 703 | +5.消费消息,以及幂等处理 |
| 704 | +```java |
| 705 | +@Service |
| 706 | +@RocketMQMessageListener(topic = MQDestination.TOPIC, selectorExpression = MQDestination.TAG_ADD_VIEW_HISTORY, consumerGroup = MQDestination.TAG_ADD_VIEW_HISTORY) |
| 707 | +public class ConsumerAddViewHistory implements RocketMQListener<Message> { |
| 708 | + // 监听到消息就会执行此方法 |
| 709 | + @Override |
| 710 | + public void onMessage(Message message) { |
| 711 | + // 幂等校验 |
| 712 | + String transactionId = message.getTransactionId(); |
| 713 | + |
| 714 | + // 查redis |
| 715 | + MqTransaction mqTransaction = redisService.getCacheObject("mqTransaction:" + transactionId); |
| 716 | + |
| 717 | + // 不存在事务记录 |
| 718 | + if (Objects.isNull(mqTransaction)) { |
| 719 | + return; |
| 720 | + } |
| 721 | + |
| 722 | + // 已消费 |
| 723 | + if (Objects.equals(mqTransaction.getStatus(), MqTransaction.StatusEnum.CONSUMED.getStatus())) { |
| 724 | + return; |
| 725 | + } |
| 726 | + |
| 727 | + String msg = new String(message.getBody()); |
| 728 | + Map<String, Long> map = JSON.parseObject(msg, new TypeReference<HashMap<String, Long>>() { |
| 729 | + }); |
| 730 | + Long userId = map.get("userId"); |
| 731 | + Long forecastLogId = map.get("forecastLogId"); |
| 732 | + |
| 733 | + // 下游的业务处理 |
| 734 | + // TODO 记录用户喜好,更新用户画像 |
| 735 | + |
| 736 | + // TODO 更新'证券预测文章'的浏览量,重新计算文章的曝光排序 |
| 737 | + |
| 738 | + // 更新状态为已消费 |
| 739 | + mqTransaction.setUpdateTime(new Date()); |
| 740 | + mqTransaction.setStatus(MqTransaction.StatusEnum.CONSUMED.getStatus()); |
| 741 | + redisService.setCacheObject("mqTransaction:" + transactionId, mqTransaction, 4L, TimeUnit.HOURS); |
| 742 | + log.info("监听到消息:msg={}", JSON.toJSONString(map)); |
| 743 | + } |
| 744 | +} |
| 745 | +``` |
| 746 | + |
543 | 747 | ## 如何解决消息堆积问题?
|
544 | 748 |
|
545 | 749 | 在上面我们提到了消息队列一个很重要的功能——**削峰** 。那么如果这个峰值太大了导致消息堆积在队列中怎么办呢?
|
|
0 commit comments