面试题集锦:新闻推送场景对照

面试题集锦:新闻推送场景对照

Hello,我是小兔大白糖。 这篇整理面试口述与高频追问要点,方便对照站内同主题通识文。


1. 概念定义

一句话描述

本场景聚焦于新闻推送系统的高并发架构设计,对比 Go 和 Java 两大生态在处理千万级在线用户、实时推送延迟 <100ms、峰值 QPS 100万+ 的技术方案选型。

场景指标

指标目标值
在线用户数1000 万
消息推送延迟P99 < 100ms
消息下发峰值 QPS100 万+
可用性99.99%
错误率< 0.01%

2. 场景需求分析

2.1 业务场景描述

┌─────────────────────────────────────────────────────────────────┐
│                      用户层 (1亿注册用户)                         │
│   ┌─────┐ ┌─────┐ ┌─────┐ ┌─────┐ ┌─────┐ ┌─────┐              │
│   │手机 │ │平板 │ │Web  │ │APP  │ │ 小程序│ │IoT  │              │
│   └─────┘ └─────┘ └─────┘ └─────┘ └─────┘ └─────┘              │
└─────────────────────────────────────────────────────────────────┘
                              │
                              │ 长连接 (WebSocket/SSE)
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                    推送网关层 (接入层)                            │
│   ┌─────────────────────────────────────────────────────────┐   │
│   │              连接管理 (goroutine per connection)        │   │
│   │   连接1 │ 连接2 │ 连接3 │ ... │ 连接1000万              │   │
│   └─────────────────────────────────────────────────────────┘   │
└─────────────────────────────────────────────────────────────────┘
                              │
                              │ 消息分发
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                     消息路由层                                    │
│   ┌───────────────┐  ┌───────────────┐  ┌───────────────┐     │
│   │  用户分组路由  │  │  标签路由      │  │  全量广播      │     │
│   └───────────────┘  └───────────────┘  └───────────────┘     │
└─────────────────────────────────────────────────────────────────┘
                              │
                              │ Kafka 消息队列
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                     消息队列层                                   │
│   ┌─────────┐  ┌─────────┐  ┌─────────┐                       │
│   │Kafka   │  │Kafka   │  │Kafka   │  ... 32 分区              │
│   │Partition│  │Partition│  │Partition│                       │
│   └─────────┘  └─────────┘  └─────────┘                       │
└─────────────────────────────────────────────────────────────────┘
                              │
                              │ 消费
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                     业务处理层                                   │
│   ┌─────────────────────────────────────────────────────────┐   │
│   │  消息过滤 → 内容处理 → 用户画像匹配 → 下发决策           │   │
│   └─────────────────────────────────────────────────────────┘   │
└─────────────────────────────────────────────────────────────────┘

2.2 核心挑战

挑战描述影响
海量长连接1000 万 WebSocket 连接内存占用、连接管理
低延迟推送P99 < 100ms调度优化、网络优化
突发流量峰值 100 万 QPS队列缓冲、限流
消息可靠性不丢消息、 Exactly-Once消费确认、幂等
用户离线离线消息存储消息持久化

3. Go 架构设计

3.1 整体架构图

                    ┌─────────────────────────────────────────────────────────┐
                    │                    Go 推送服务                           │
                    │                                                          │
                    │  ┌─────────────────────────────────────────────────────┐ │
                    │  │              WebSocket Gateway (Hertz)              │ │
                    │  │  • goroutine per connection (2KB 初始栈)            │ │
                    │  │  • 连接元数据存储 (用户ID → conn)                    │ │
                    │  │  • 心跳检测 (goroutine 独立 timer)                   │ │
                    │  └─────────────────────────────────────────────────────┘ │
                    │                              │                            │
                    │                              │ channel                    │
                    │                              ▼                            │
                    │  ┌─────────────────────────────────────────────────────┐ │
                    │  │              Message Router                          │ │
                    │  │  • fan-out 消息分发                                   │ │
                    │  │  • 用户分组 (channel 分片)                           │ │
                    │  │  • 广播 (multi-cast)                                 │ │
                    │  └─────────────────────────────────────────────────────┘ │
                    │                              │                            │
                    └──────────────────────────────┼────────────────────────────┘
                                                   │
                                                   ▼
┌──────────────────────────────────────────────────────────────────────────────┐
│                            Redis Cluster                                      │
│   ┌─────────────────┐  ┌─────────────────┐  ┌─────────────────┐              │
│   │  Connection Hub  │  │  Pub/Sub        │  │  Session Cache  │              │
│   │  (用户→节点映射)  │  │  (发布订阅)      │  │  (在线状态)      │              │
│   └─────────────────┘  └─────────────────┘  └─────────────────┘              │
└──────────────────────────────────────────────────────────────────────────────┘
                                                   │
                                                   ▼
┌──────────────────────────────────────────────────────────────────────────────┐
│                            Kafka Cluster                                      │
│   ┌─────────┐  ┌─────────┐  ┌─────────┐  ┌─────────┐  ┌─────────┐           │
│   │ Partition│  │ Partition│  │ Partition│  │ Partition│  │ Partition│  ... 64 │
│   │    0     │  │    1     │  │    2     │  │    3     │  │    4     │         │
│   └─────────┘  └─────────┘  └─────────┘  └─────────┘  └─────────┘           │
└──────────────────────────────────────────────────────────────────────────────┘

3.2 连接管理实现

文件位置: internal/api/handler/websocket/websocket_handler.go

type WebSocketHandler struct {
    // 用户连接映射 (注意:生产环境应分片管理)
    conns      sync.Map  // map[string]*UserConnection
 
    // 消息通道
    msgChan    chan *Message
    broadcast  chan *BroadcastMessage
 
    // 配置
    maxConns   int64
    heartbeatInterval time.Duration
}
 
type UserConnection struct {
    UserID   string
    Conn     *websocket.Conn
    NodeID   string
    SubTag   []string  // 用户订阅标签
    LastPing time.Time
 
    // 该用户的离线消息缓冲
    offlineMsgs [] *Message
    mu          sync.Mutex
}
 
// goroutine per connection 模式
func (h *WebSocketHandler) HandleConnection(c *websocket.Conn, userID string) {
    // 1. 注册连接
    conn := &UserConnection{
        UserID:   userID,
        Conn:     c,
        NodeID:   nodeID,
        LastPing: time.Now(),
    }
    h.conns.Store(userID, conn)
 
    // 2. 启动读 goroutine (阻塞读取,不消耗 CPU)
    go h.readLoop(conn)
 
    // 3. 启动写 goroutine (消息下发)
    go h.writeLoop(conn)
 
    // 4. 启动心跳检测 goroutine
    go h.heartbeatLoop(conn)
 
    // 5. 连接关闭时清理
    defer func() {
        h.conns.Delete(userID)
        h.clearOfflineMessages(userID)
    }()
}
 
func (h *WebSocketHandler) readLoop(conn *UserConnection) {
    for {
        _, msg, err := conn.Conn.ReadMessage()
        if err != nil {
            // 客户端关闭或网络错误
            return
        }
        // 处理客户端消息 (ACK、订阅变更等)
        h.handleClientMessage(conn, msg)
    }
}
 
func (h *WebSocketHandler) writeLoop(conn *UserConnection) {
    // 使用独立的 write channel 实现有序下发
    writeChan := make(chan []byte, 256)
 
    go func() {
        for msg := range writeChan {
            if err := conn.Conn.WriteMessage(websocket.TextMessage, msg); err != nil {
                return
            }
        }
    }()
 
    // 将 writeChan 关联到 conn
    conn.writeChan = writeChan
}

3.3 Channel Fan-Out 消息分发

// 消息分发器
type MessageDispatcher struct {
    // 用户连接分片 (减少锁竞争)
    shards []*ConnectionShard
 
    // Kafka 消费者组
    kafkaConsumer *kafka.Consumer
 
    // 广播 channel
    broadcastCh chan *BroadcastMessage
}
 
type ConnectionShard struct {
    conns sync.Map  // 分片内的连接
    mu    sync.RWMutex
}
 
// 启动 N 个 worker 处理消息
func (d *MessageDispatcher) StartWorkers(ctx context.Context, workerCount int) {
    for i := 0; i < workerCount; i++ {
        go d.worker(ctx, i)
    }
}
 
func (d *MessageDispatcher) worker(ctx context.Context, id int) {
    for {
        select {
        case msg := <-d.broadcastCh:
            d.fanoutMessage(msg)
        case <-ctx.Done():
            return
        }
    }
}
 
// fan-out 消息分发
func (d *MessageDispatcher) fanoutMessage(msg *BroadcastMessage) {
    // 1. 找到目标分片
    targetShards := d.getTargetShards(msg.RecipientFilter)
 
    // 2. 并行发送到各分片
    var wg sync.WaitGroup
    for _, shard := range targetShards {
        wg.Add(1)
        go func(s *ConnectionShard) {
            defer wg.Done()
            s.forEachConn(func(conn *UserConnection) bool {
                // 检查用户是否匹配标签/条件
                if msg.Match(conn) {
                    conn.Write(msg.Data)
                }
                return true
            })
        }(shard)
    }
    wg.Wait()
}

3.4 内存优化:对象池

// 使用 sync.Pool 减少 GC 压力
var messagePool = sync.Pool{
    New: func() interface{} {
        return &Message{
            Data: make([]byte, 0, 4096),
            Headers: make(map[string]string),
        }
    },
}
 
// 获取消息对象
func GetMessage() *Message {
    return messagePool.Get().(*Message)
}
 
// 归还消息对象
func PutMessage(m *Message) {
    m.Reset()
    messagePool.Put(m)
}
 
// 在 handler 中使用
func (h *WebSocketHandler) handleMessage() {
    msg := GetMessage()
    defer PutMessage(msg)
 
    // 处理消息...
}

3.5 Redis 缓存层

// Redis 连接管理
type RedisManager struct {
    client *redis.ClusterClient
 
    // 连接池配置
    poolSize       int
    minIdleConns   int
    maxRetries     int
}
 
// 用户节点映射
func (m *RedisManager) GetUserNode(ctx context.Context, userID string) (string, error) {
    // 使用 Redis Hash 存储用户→节点映射
    return m.client.HGet(ctx, "user:node", userID).Result()
}
 
func (m *RedisManager) SetUserNode(ctx context.Context, userID, nodeID string) error {
    return m.client.HSet(ctx, "user:node", userID, nodeID).Err()
}
 
// 在线状态 (使用 Redis Set)
func (m *RedisManager) GetOnlineUsers(ctx context.Context) ([]string, error) {
    return m.client.SMembers(ctx, "online:users").Result()
}
 
// Pub/Sub 发布
func (m *RedisManager) PublishMessage(ctx context.Context, channel string, msg []byte) error {
    return m.client.Publish(ctx, channel, msg).Err()
}

3.6 Kafka 生产者

// 消息写入 Kafka
func (s *MessageService) SendToKafka(ctx context.Context, msg *PushMessage) error {
    // 按用户ID hash 到不同分区
    partition := int(crc32.ChecksumIEEE([]byte(msg.UserID))) % s.kafkaPartitions
 
    _, err := s.producer.Send(ctx, &kafka.Message{
        Topic: "push_messages",
        Key:   []byte(msg.UserID),
        Value: msg.Data,
        Headers: []kafka.Header{
            {Key: "msg_type", Value: []byte(msg.Type)},
            {Key: "priority", Value: []byte(msg.Priority)},
        },
    })
    return err
}

4. Java 架构设计

4.1 整体架构图

                    ┌─────────────────────────────────────────────────────────┐
                    │                 Java 推送服务 (Spring Boot)              │
                    │                                                          │
                    │  ┌─────────────────────────────────────────────────────┐ │
                    │  │              Netty WebSocket Server                 │ │
                    │  │  • Virtual Threads (Project Loom)                   │ │
                    │  │  • ChannelHandlerPipeline                           │ │
                    │  │  • IdleStateHandler (心跳)                          │ │
                    │  └─────────────────────────────────────────────────────┘ │
                    │                              │                          │
                    │                              │ Dispatcher               │
                    │                              ▼                          │
                    │  ┌─────────────────────────────────────────────────────┐ │
                    │  │              Message Router (R2DBC/Project Reactor) │ │
                    │  │  • Flux/Mono 反应式流                                │ │
                    │  │  • 分区路由                                          │ │
                    │  └─────────────────────────────────────────────────────┘ │
                    └──────────────────────────────┼────────────────────────────┘
                                                   │
                                                   ▼
┌──────────────────────────────────────────────────────────────────────────────┐
│                            Redis Cluster (Lettuce)                          │
│   ┌─────────────────┐  ┌─────────────────┐  ┌─────────────────┐              │
│   │  Connection Pool│  │  Pub/Sub        │  │  Session Cache  │              │
│   │  (异步IO)        │  │  (Lettuce)      │  │  (Spring Cache) │              │
│   └─────────────────┘  └─────────────────┘  └─────────────────┘              │
└──────────────────────────────────────────────────────────────────────────────┘
                                                   │
                                                   ▼
┌──────────────────────────────────────────────────────────────────────────────┐
│                            Apache Kafka (Confluent)                           │
│   ┌─────────┐  ┌─────────┐  ┌─────────┐  ┌─────────┐  ┌─────────┐              │
│   │ Partition│  │ Partition│  │ Partition│  │ Partition│  │ Partition│  ... 64 │
│   │    0     │  │    1     │  │    2     │  │    3     │  │    4     │         │
│   └─────────┘  └─────────┘  └─────────┘  └─────────┘  └─────────┘              │
└──────────────────────────────────────────────────────────────────────────────┘

4.2 虚拟线程实现

// Java 21 Virtual Threads
@Sharable
public class PushWebSocketHandler extends TextWebSocketHandler {
 
    // 用户连接映射
    private final ConcurrentHashMap<String, WebSocketSession> connections =
        new ConcurrentHashMap<>();
 
    // 用户订阅映射
    private final ConcurrentHashMap<String, Set<String>> userSubscriptions =
        new ConcurrentHashMap<>();
 
    @Override
    protected void handleTextMessage(WebSocketSession session,
                                     TextMessage message) {
        // 每个消息在虚拟线程中处理
        try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
            executor.submit(() -> processMessage(session, message));
        }
    }
 
    // 虚拟线程:每连接一个虚拟线程
    public void handleConnection(WebSocketSession session) {
        String userId = extractUserId(session);
 
        // 虚拟线程不占用 OS 线程
        Thread.startVirtualThread(() -> {
            try {
                // 读取循环
                while (session.isOpen()) {
                    TextMessage msg = (TextMessage) session.receiveMessage();
                    handleClientMessage(session, msg);
                }
            } catch (Exception e) {
                // 连接关闭
            } finally {
                connections.remove(userId);
            }
        });
    }
}

4.3 Netty + 反应式编程

// Netty + Project Reactor 实现
@Service
public class ReactivePushService {
 
    private final KafkaTemplate<String, byte[]> kafkaTemplate;
    private final RedisTemplate<String, Object> redisTemplate;
 
    // 反应式消息发送
    public Mono<Void> pushMessage(String userId, PushMessage message) {
        return Mono.fromFuture(() -> redisTemplate.opsForValue()
                .getAsync("user:session:" + userId))
            .flatMap(session -> {
                // 通过 Netty channel 发送
                NettyChannel channel = session.getChannel();
                return channel.writeAndFlush(message)
                    .toFuture()
                    .then();
            })
            .onErrorResume(e -> {
                // 失败时写入离线队列
                return writeToOfflineQueue(userId, message);
            });
    }
 
    // 广播消息 - 使用反应式流
    public Flux<Integer> broadcastMessage(BroadcastMessage message) {
        return Flux.range(0, partitionCount)
            .flatMap(partition ->
                kafkaTemplate.send("push_topic", partition, message)
                    .toMono()
                    .map(result -> result.getRecordMetadata().partition())
            );
    }
 
    // 使用 Disruptor 高性能队列作为内部缓冲
    private final RingBuffer<PushEvent> ringBuffer =
        RingBuffer.createSingleProducer(
            new PushEventFactory(),
            1024 * 1024,  // 1M buffer
            new BusySpinWaitStrategy()
        );
 
    public void publishEvent(PushEvent event) {
        long sequence = ringBuffer.next();
        try {
            PushEvent e = ringBuffer.get(sequence);
            e.copyFrom(event);
        } finally {
            ringBuffer.publish(sequence);
        }
    }
}

4.4 线程池配置

// Spring 配置
@Configuration
public class ThreadPoolConfig {
 
    // 虚拟线程适合 IO 密集型任务
    @Bean
    public ExecutorService virtualThreadExecutor() {
        return Executors.newVirtualThreadPerTaskExecutor();
    }
 
    // Netty Boss 线程组 (OS 线程)
    @Bean
    public NioEventLoopGroup bossGroup() {
        return new NioEventLoopGroup(1, // 1 个 boss 线程
            new DefaultThreadFactory("boss"));
    }
 
    // Netty Worker 线程组 (OS 线程)
    @Bean
    public NioEventLoopGroup workerGroup() {
        // Worker 处理 channel 事件
        return new NioEventLoopGroup(
            Runtime.getRuntime().availableProcessors() * 2,
            new DefaultThreadFactory("worker"));
    }
 
    // Kafka 消费者线程池
    @Bean
    public KafkaListenerContainerFactory<ConcurrentMessageListenerContainer<Integer, byte[]>>
            kafkaListenerContainerFactory() {
        var factory = new ConcurrentKafkaListenerContainerFactory<>();
        factory.setConsumerFactory(consumerFactory());
        // 每个分区一个并发
        factory.setConcurrency(64);
        return factory;
    }
}

5. 关键设计对比

5.1 并发模型对比

维度GoJava
连接模型goroutine per connectionvirtual thread per connection
初始栈大小2KB~1MB (虚拟线程)
调度方式GMP work-stealingForkJoinPool + OS 调度
阻塞处理goroutine 阻塞,M调度其他虚拟线程阻塞,carrier 线程调度其他
内存开销~2KB/连接~200-400KB/虚拟线程
1000万连接内存~20GB~2-4TB (不可行)

Go 优势:轻量 goroutine 使 1000 万连接成为可能 Java 痛点:虚拟线程虽轻量,但仍有数百 KB 开销

5.2 网络层对比

维度GoJava
WebSocket 库gorilla/websocket, nhooyr.io/websocketJava-WebSocket, Netty
epoll/kqueue运行时自动使用Netty 自动使用
连接内存~4-8KB/连接~8-16KB/连接
Zero-copysyscall + channelNetty ByteBuf 池化

5.3 消息队列对比

维度GoJava
Kafka 客户端segmentio/kafka-go (原生)Confluent Kafka (官方)
生产者吞吐~50-100MB/s~100-200MB/s
消费者吞吐~100-200MB/s~200-400MB/s
分区策略用户ID hash用户ID hash

6. 共同优化策略

6.1 Redis 缓存分层

┌─────────────────────────────────────────────────────────────────┐
│                     本地缓存 (进程内)                             │
│   ┌─────────────────────────────────────────────────────────┐    │
│   │  用户信息 │ 推送规则 │ 热点内容                           │    │
│   │  LRU: 1万条目, TTL: 30s                                 │    │
│   └─────────────────────────────────────────────────────────┘    │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                     Redis 集群                                   │
│   ┌──────────────┐  ┌──────────────┐  ┌──────────────┐          │
│   │ 连接元数据    │  │ 在线状态     │  │ 消息缓存     │          │
│   │ (Hash)       │  │ (Sorted Set) │  │ (List)       │          │
│   └──────────────┘  └──────────────┘  └──────────────┘          │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                     MongoDB                                     │
│   ┌──────────────┐  ┌──────────────┐                            │
│   │ 离线消息存储  │  │ 用户画像     │                            │
│   └──────────────┘  └──────────────┘                            │
└─────────────────────────────────────────────────────────────────┘

Go 实现:

type MultiLevelCache struct {
    local *LocalCache    // 进程内 LRU
    redis *RedisManager  // Redis
    mongodb *MongoDB      // 兜底
}
 
func (c *MultiLevelCache) GetUserInfo(ctx context.Context, userID string) (*UserInfo, error) {
    // 1. 先查本地缓存
    if info := c.local.Get(userID); info != nil {
        return info, nil
    }
 
    // 2. 查 Redis
    if info, err := c.redis.GetUserInfo(ctx, userID); err == nil {
        c.local.Set(userID, info) // 回填本地缓存
        return info, nil
    }
 
    // 3. 查 MongoDB
    return c.mongodb.GetUserInfo(ctx, userID)
}

6.2 Kafka 削峰

// Kafka 分区策略
func partitionKey(userID string) int {
    // 一致性 hash 保证用户消息有序
    return int(crc32.ChecksumIEEE([]byte(userID))) % PartitionCount
}
 
// 消息缓冲写入
func (s *PushService) EnqueueMessage(ctx context.Context, msg *PushMessage) error {
    // 先写入本地 buffer (如果配置了)
    if s.localBuffer != nil {
        s.localBuffer.Add(msg)
    }
 
    // 异步写入 Kafka (不阻塞主流程)
    return s.kafkaProducer.SendAsync(ctx, msg)
}

Java 实现:

@Service
public class KafkaBatchingService {
 
    private final KafkaTemplate<String, byte[]> kafkaTemplate;
 
    // 批量发送优化
    public Mono<Void> sendBatch(List<PushMessage> messages) {
        return Flux.fromIterable(messages)
            .buffer(100) // 批量大小
            .flatMap(batch ->
                kafkaTemplate.send(batch.stream()
                    .collect(Collectors.toMap(
                        m -> m.getUserId(),
                        m -> m.getData()
                    )))
                .toMono()
            )
            .then();
    }
}

6.3 连接池复用

Go Redis 连接池:

// 默认配置
redisOpts := &redis.Options{
    Addr:     "localhost:6379",
    PoolSize: 100,        // 每个节点 100 连接
    MinIdleConns: 10,      // 最小空闲
    MaxRetries:   3,
    PoolTimeout:   30 * time.Second,
}

Java Lettuce 连接池:

// Lettuce 连接池配置
LettuceConnectionFactory factory = new LettuceConnectionFactory();
factory.setHost("localhost");
factory.setPort(6379);
factory.setPoolConfig(PoolConfig.builder()
    .maxTotal(100)
    .maxIdle(50)
    .minIdle(10)
    .build());

7. 压测与监控

7.1 Go 压测

// Benchmark 测试
func BenchmarkWebSocketBroadcast(b *testing.B) {
    // 模拟 10万连接的广播
    conns := make([]*MockConn, 100000)
 
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        msg := make([]byte, 1024)
        for _, conn := range conns {
            conn.Write(msg)
        }
    }
}
 
// 压测脚本使用 k6
// k6_publish.js
// import ws from 'k6/ws';
//
// export const options = {
//   scenarios: {
//     high_load: {
//       executor: 'constant-vus',
//       vus: 10000,
//       duration: '60s',
//     },
//   },
// };
//
// export default function() {
//   ws.connect('wss://push.example.com/ws', {}, function(socket) {
//     socket.on('message', (data) => {
//       // 确认收到
//     });
//   });
// }

7.2 Java 压测

// JMH 基准测试
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.SECONDS)
public class WebSocketBenchmark {
 
    @Benchmark
    public void testBroadcast(Blackhole bh) {
        // 模拟广播
        for (int i = 0; i < 10000; i++) {
            bh.consume(broadcast(message));
        }
    }
}
 
// 使用 Gatling 进行负载测试
// PushSimulation.scala
// class PushSimulation extends Simulation {
//   val httpConf = http.baseUrl("https://push.example.com")
//
//   val scenario = scenario("Push Load Test")
//     .exec(ws("WS Connect").connect("/ws")
//     .onMessage(ws.checkTextMessage("check").print()))
//     .pause(1)
//     .exec(ws("WS Send").sendTextMessage("ping"))
// }

7.3 监控指标

Prometheus 指标定义:

var (
    // 连接指标
    wsConnections = promauto.NewGauge(prometheus.GaugeOpts{
        Name: "ws_connections_total",
        Help: "Total WebSocket connections",
    })
 
    // 消息指标
    messagesPublished = promauto.NewCounterVec(prometheus.CounterOpts{
        Name: "messages_published_total",
        Help: "Total messages published",
    }, []string{"type", "status"})
 
    // 延迟指标
    messageLatency = promauto.NewHistogram(prometheus.HistogramOpts{
        Name:    "message_push_latency_seconds",
        Help:    "Message push latency",
        Buckets: []float64{.001, .005, .01, .025, .05, .1, .25, .5, 1},
    })
)

Grafana 看板面板:

面板指标
连接数ws_connections_total
消息吞吐量rate(messages_published_total[5m])
P99 延迟histogram_quantile(0.99, message_push_latency_seconds)
CPU 使用率rate(process_cpu_seconds_total[1m])
内存使用process_resident_memory_bytes
GC 频率go_gc_duration_seconds_count

7.4 延迟指标对比

指标GoJava G1Java ZGC
P505ms10ms5ms
P9020ms50ms15ms
P9950ms200ms30ms
P999100ms500ms50ms

8. 架构选型建议

8.1 选择 Go 的场景

场景推荐原因
超大规模长连接goroutine 轻量,1000万+连接可行
低内存环境2KB 栈 vs 1MB 固定栈
简单业务逻辑CSP 模型易于理解和维护
快速迭代编译快速,部署简单
云原生镜像小,启动快,适合 K8s

8.2 选择 Java 的场景

场景推荐原因
复杂企业集成Spring 全家桶生态完善
团队 Go 经验不足Java 人才更多
现有微服务兼容已有 Java 技术栈
高级 GC 调优G1/ZGC 工具成熟
混合微服务GraalVM native-image

8.3 混合架构建议

┌─────────────────────────────────────────────────────────────────┐
│                    接入层 (Go)                                   │
│   • WebSocket 网关 (goroutine per connection)                   │
│   • 高并发、低延迟                                               │
└─────────────────────────────────────────────────────────────────┘
                              │
                              │ gRPC
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                    业务层 (Java)                                 │
│   • 复杂业务逻辑                                                 │
│   • Spring Boot 微服务                                          │
│   • 丰富的企业级特性                                             │
└─────────────────────────────────────────────────────────────────┘

9. 常见问题与解答

Q1: 1000万 WebSocket 连接可行吗?

Go 可行方案:

  • 单机 ~50-100万连接(取决于内存)
  • 需要 10-20 台网关 + 负载均衡
  • 使用 ulimit -n 调整文件描述符限制
  • 内存估算:50万连接 × ~4KB = ~2GB

Java 不可行原因:

  • 虚拟线程 ~200KB/连接 × 50万 = ~100GB(单机不可能)

Q2: 消息推送如何保证不丢?

  1. Kafka 持久化:消息写入 Kafka,分区副本 ≥ 2
  2. 消费确认:手动提交 offset,处理成功后才提交
  3. 幂等处理:消息 ID 去重
  4. 离线补偿:用户上线时查询离线消息

Q3: 如何处理用户离线?

策略Go 实现Java 实现
Redis 缓冲List 存储离线消息RedisTemplate.opsForList()
MongoDB 持久化写入 offline_messages 集合@Document JPA
设备同步APNs/FCM 推送Java-APNs

Q4: 热点新闻如何避免惊群效应?

// 使用 singleflight 合并重复请求
type Deduplicator struct {
    sfGroup singleflight.Group
}
 
func (d *Deduplicator) PublishNews(newsID string, msg *Message) {
    // 相同的 newsID 只会执行一次
    d.sfGroup.Do(newsID, func() (interface{}, error) {
        return nil, d.doPublish(newsID, msg)
    })
}

Java 等价:使用 ConcurrentHashMap + computeIfAbsent 实现类似效果。

Q5: 如何实现优雅关闭?

// Go 优雅关闭
func (s *Server) Shutdown(ctx context.Context) error {
    // 1. 停止接收新连接
    s.ln.Close()
 
    // 2. 通知现有连接关闭
    close(s.closeChan)
 
    // 3. 等待连接处理完成 (带超时)
    return s.waitForConnections(ctx, 30*time.Second)
}

10. 参考资料

  1. Go WebSocket: https://github.com/gorilla/websocket
  2. Java Virtual Threads: https://openjdk.org/jeps/444
  3. Netty in Action
  4. Kafka Documentation: https://kafka.apache.org/documentation/
  5. Redis Clustering: https://redis.io/docs/management/scaling/
  6. Prometheus Go Client: https://prometheus.io/docs/instrumenting/clients/