如何发送通知?

解读

在国内一线互联网或金融企业的 Spring 岗位面试中,“发送通知”并不是让候选人写一段简单的 JavaMail 代码,而是考察对 Spring 生态内事件驱动模型、异步处理、可靠性投递以及高并发场景下削峰填谷能力的综合理解。面试官往往以“如何发送通知”为引子,层层追问:事务边界怎么定?消息丢失怎么办?如何防止重复消费?是否支持动态渠道切换?因此,回答必须体现领域建模、Spring 事件、消息队列、分布式事务、幂等设计等多维度能力,并给出可直接落地的 Spring Boot 代码骨架。

知识点

  1. Spring 事件发布器(ApplicationEventPublisher)与@EventListener注解的同步/异步机制
  2. @TransactionalEventListener在事务提交后发送通知,避免消息早于业务落库
  3. Spring for Apache Kafka/RabbitMQ 的可靠投递:confirm、return、事务消息、批量发送
  4. 消息幂等:业务键 + 数据库唯一索引 / Redis setNX / 雪花 ID 去重表
  5. 削峰填谷:线程池隔离、MQ 堆积、流控(Sentinel、Resilience4j)
  6. 多通道动态路由:Spring 策略模式 + 配置中心(Nacos、Apollo)实时切换短信、邮件、企微、Push
  7. 分布式事务:本地消息表、RocketMQ 事务消息、Seata AT 模式
  8. 监控与告警:Micrometer + Prometheus 记录发送 QPS、耗时、失败率;钉钉/飞书告警
  9. 灰度与回滚:Spring Cloud Gateway 权重路由 + 配置版本号快速回退模板

答案

发送通知的完整方案分四层:领域事件封装、可靠投递、消费端幂等、监控运维。以下给出可直接落地的 Spring Boot 骨架,全部基于国内主流组件(RocketMQ、MySQL、Redis),并兼顾金融级可靠性要求。

  1. 领域事件封装
public class OrderPaidEvent extends ApplicationEvent {
    private final String bizId;          // 业务唯一键
    private final String mobile;
    private final String content;
    public OrderPaidEvent(Object source, String bizId, String mobile, String content) {
        super(source);
        this.bizId = bizId;
        this.mobile = mobile;
        this.content = content;
    }
    // getter 省略
}
  1. 事务内发布事件,确保业务落库后再发消息
@Service
public class OrderService {
    @Autowired private ApplicationEventPublisher publisher;
    @Autowired private OrderMapper orderMapper;

    @Transactional(rollbackFor = Exception.class)
    public void pay(Long orderId) {
        // 1. 业务落库
        Order order = orderMapper.find(orderId);
        order.setStatus("PAID");
        orderMapper.update(order);

        // 2. 注册事务后置事件
        OrderPaidEvent event = new OrderPaidEvent(this, order.getBizId(), order.getMobile(), "订单已支付");
        publisher.publishEvent(event);
    }
}
  1. 事务提交后异步转 RocketMQ,零消息丢失
@Component
public class OrderPaidListener {
    @Autowired private RocketMQTemplate rocketTemplate;

    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT, fallbackExecution = true)
    @Async("notifyExecutor")   // 自定义线程池,与主业务线程隔离
    public void handle(OrderPaidEvent event) {
        Message<OrderPaidEvent> msg = MessageBuilder
                .withPayload(event)
                .setHeader(RocketMQHeaders.KEYS, event.getBizId())  // 业务键,用于幂等
                .build();
        rocketTemplate.send("topic_notify", msg);
    }
}
  1. 消费端幂等(防止 MQ 重试或人工补偿导致重复)
@RocketMQMessageListener(topic = "topic_notify", consumerGroup = "notify_consumer")
@Component
public class NotifyConsumer {
    @Autowired private NotifyRecordMapper recordMapper;

    @Override
    public void onMessage(MessageExt ext) {
        String bizId = ext.getKeys();
        // 1. 幂等判断
        if (recordMapper.exists(bizId)) {
            return;
        }
        // 2. 短信渠道发送(此处可动态切换)
        SmsChannel.send(ext.getUserProperty("mobile"), ext.getUserProperty("content"));
        // 3. 落去重表
        recordMapper.insert(bizId, ext.getMsgId(), "SUCCESS");
    }
}
  1. 线程池与流控
@Configuration
public class ExecutorConfig {
    @Bean("notifyExecutor")
    public Executor notifyExecutor() {
        ThreadPoolTaskExecutor exec = new ThreadPoolTaskExecutor();
        exec.setCorePoolSize(8);
        exec.setMaxPoolSize(32);
        exec.setQueueCapacity(2000);
        exec.setThreadNamePrefix("notify-");
        exec.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        exec.initialize();
        return exec;
    }
}
  1. 动态渠道切换(配置中心实时刷新)
@Component
@ConfigurationProperties(prefix = "notify.channel")
@Data
public class ChannelProperties {
    private String sms = "ALIYUN";   // 默认阿里云
}

@Service
public class SmsChannel {
    @Autowired private ChannelProperties props;
    private final Map<String, SmsStrategy> strategyMap = Map.of(
            "ALIYUN", new AliyunSmsStrategy(),
            "TENCENT", new TencentSmsStrategy()
    );
    public static void send(String mobile, String content) {
        SmsStrategy strategy = strategyMap.get(props.getSms());
        strategy.send(mobile, content);
    }
}
  1. 监控告警
@RestControllerEndpoint(id = "notify-metrics")
@Component
public class NotifyMetricsEndpoint {
    @GetMapping
    public Map<String, Object> metrics() {
        return Map.of(
                "qps", Metrics.counter("notify_sent_total").count(),
                "fail", Metrics.counter("notify_fail_total").count(),
                "tps", Metrics.timer("notify_duration").mean(TimeUnit.MILLISECONDS)
        );
    }
}

通过以上七步,可在国内高并发、高可靠场景下完成事务级可靠通知,并支持灰度、回滚、动态渠道、可观测等企业级需求。

拓展思考

  1. 如果企业已全面上云,可替换 RocketMQ 为阿里云 MNS 或腾讯云 CMQ,利用云厂商的死信队列+消息轨迹能力,进一步降低自建成本。
  2. 对于营销类批量通知,可引入Spring Batch + 分片线程池,将 500 万条短信任务拆成 100 片,每片 5 万条,逐片提交,失败片单独重试,避免一次性加载内存溢出。
  3. 若要求秒级实时触达,可在消费端再套一层Spring WebFlux + Netty,调用运营商 HTTP2 网关,实现单线程 10 万 QPS 的长连接推送。
  4. 当业务需要跨境合规(如 GDPR、PIPL),通知内容需先经过Spring Cloud Gateway + 自研脱敏过滤器做数据屏蔽,再调用海外 SMS 供应商,避免敏感数据出境。