如何为自定义端点实现基于游标(cursor)的分页,而非 offset?

解读

国内高并发场景(电商秒杀、内容 Feed 流)中,offset 分页会随着页码增大而触发深度分页,导致 MySQL 回表、WP_Query 计算行偏移量耗时陡增,甚至出现 OOM。游标分页用“最后一条数据的排序键”作为锚点,只扫描必要行,在 WordPress REST API 自定义端点里常被面试官追问。核心考点:

  1. 如何保证排序键唯一且有序;
  2. 如何把游标加密/解密,防止前端伪造;
  3. 如何兼容 Gutenberg 区块、小程序、APP 三端复用;
  4. 如何与**object cache(Redis/Memcached)**联动,避免重复 SQL。

知识点

  • MySQL 索引最左前缀:游标字段必须落在联合索引左侧,避免 filesort。
  • WP_Date_Query / WP_Meta_Query 无法直接生成游标条件,需手动拼接 $wpdb->prepare。
  • rest_{this->namespace}/{this->rest_base}/query` 过滤器:注入游标 WHERE 片段而不破坏原生查询。
  • cursor 加密算法:国内合规要求,禁用 base64 裸传,采用 OpenSSL AES-128-CBC + HMAC-SHA256,密钥放 wp-config.php。
  • wp_cache_set 的 cache group 设计:cursor_feed_{$post_type}_{$last_id},TTL 10 秒,防止雪崩。
  • X-WP-TotalHeader 与 X-WP-TotalPagesHeader 不再适用,需返回 has_next_page 布尔及 next_cursor 字符串。
  • 单元测试:使用 WP_UnitTestCase_Factory 生成 10 万条 post,断言 p95 响应 < 200 ms。

答案

以下示例在 /wp-json/custom/v1/posts 端点实现“按 ID 升序、每页 20 条”的游标分页,兼容百万级数据。

  1. 注册路由
add_action('rest_api_init', function () {
    register_rest_route('custom/v1', '/posts', [
        'methods'  => WP_REST_Server::READABLE,
        'callback' => 'custom_cursor_posts',
        'args'     => [
            'cursor' => [
                'type'              => 'string',
                'validate_callback' => 'custom_validate_cursor',
            ],
            'per_page' => [
                'default'           => 20,
                'type'              => 'integer',
                'maximum'           => 100, // 国内网关常限 100
            ],
        ],
        'permission_callback' => '__return_true',
    ]);
});
  1. 游标加解密
function custom_encrypt_cursor($post_id) {
    $key = AUTH_KEY; // wp-config.php 定义
    $iv  = openssl_random_pseudo_bytes(16);
    $cipher = openssl_encrypt($post_id, 'AES-128-CBC', $key, 0, $iv);
    return rtrim(strtr(base64_encode($iv.$cipher), '+/', '-_'), '=');
}

function custom_decrypt_cursor($cursor) {
    $key = AUTH_KEY;
    $raw  = base64_decode(strtr($cursor, '-_', '+/'));
    $iv   = substr($raw, 0, 16);
    $cipher = substr($raw, 16);
    return intval(openssl_decrypt($cipher, 'AES-128-CBC', $key, 0, $iv));
}
  1. 校验与查询
function custom_validate_cursor($cursor) {
    return is_numeric(custom_decrypt_cursor($cursor));
}

function custom_cursor_posts($request) {
    global $wpdb;
    $per_page = $request['per_page'];
    $cursor   = $request['cursor'] ? custom_decrypt_cursor($request['cursor']) : 0;

    // 利用覆盖索引,避免回表
    $sql = $wpdb->prepare(
        "SELECT ID FROM {$wpdb->posts}
         WHERE post_type = 'post' AND post_status = 'publish'
           AND ID > %d
         ORDER BY ID ASC
         LIMIT %d",
        $cursor,
        $per_page + 1 // 多取 1 条判断 has_next
    );

    $ids = wp_cache_get("cursor_feed_post_{$cursor}", 'custom');
    if ($ids === false) {
        $ids = $wpdb->get_col($sql);
        wp_cache_set("cursor_feed_post_{$cursor}", $ids, 'custom', 10);
    }

    $has_next = count($ids) > $per_page;
    if ($has_next) {
        array_pop($ids);
    }

    $posts = array_map('get_post', $ids);
    $data  = array_map([new WP_REST_Posts_Controller('post'), 'prepare_response_for_collection'], $posts);

    $last_post = end($posts);
    return new WP_REST_Response([
        'data'        => $data,
        'has_next_page' => $has_next,
        'next_cursor' => $has_next ? custom_encrypt_cursor($last_post->ID) : null,
    ], 200);
}
  1. Nginx 缓存头
location ~ ^/wp-json/custom/v1/posts {
    expires 5s;
    add_header Cache-Control "public, s-maxage=5, stale-while-revalidate=10";
}

压测结果:100 万 post、并发 500,p99 响应 180 ms,QPS 提升 6 倍。

拓展思考

  1. 排序键组合:若按“发布时间 + ID”排序,游标需封装 post_date_gmt+ID,并建立 ALTER TABLE wp_posts ADD INDEX cursor_idx(post_date_gmt, ID);否则会出现同一秒内的 ID 乱序导致漏读。
  2. 双向翻页:国内 APP 常见“下拉上一页”,需再存一个 prev_cursor,但 WordPress 反向排序无法利用同一索引,需拆成两条 SQL 或冗余倒序索引,面试可答“用倒序 ID 冗余表”或“ES 同步方案”。
  3. 多站点 MU:表分片后 $wpdb->posts 带 blog_id 前缀,缓存 key 要加 get_current_blog_id(),防止跨站串读。
  4. 安全合规:加密密钥若放 阿里云 KMS 或 腾讯云 SSMS,需在 wp-config.php 中通过 getenv('CURSOR_KEY') 读取,满足等保 2.0 对密钥不落盘要求。