本文详解如何使用Bun运行时替代传统PHP-FPM,加速WordPress响应速度。
什么是Bun
Bun 是新一代JavaScript运行时(2023年发布v1.0):
- 内置包管理器(替代npm/yarn)
- 内置测试框架(替代Jest)
- 内置打包器(替代Webpack)
- 内置TypeScript支持(无需编译)
- 性能:比Node.js快3-5倍
2026年新特性:
- Bun Shell(替代bash/PowerShell)
- Bun Edge(边缘运行时,兼容Cloudflare Workers)
- Bun SQL(内置SQLite/PostgreSQL客户端)
为什么Bun能加速WordPress
传统WordPress架构:
浏览器 → Nginx → PHP-FPM → MySQL
↓
PHP-FPM启动慢(~50ms冷启动)
Bun + WordPress架构:
浏览器 → Bun(直接运行TypeScript) → WordPress REST API
↓
Bun启动快(~1ms冷启动)
实战一:使用Bun作为WordPress反向代理
安装Bun
# Linux/macOS
curl -fsSL https://bun.sh/install | bash
Windows (PowerShell)
powershell -c "irm bun.sh/install.ps1 | iex"
验证
bun --version
创建Bun代理服务器
// server.ts
import { serve } from 'bun';
serve({
port: 3000,
async fetch(req) {
const url = new URL(req.url);
// 代理到WordPress REST API
if (url.pathname.startsWith('/wp-json')) {
const wpUrl = 'https://www.shenma98.com' + url.pathname + url.search;
const proxyReq = new Request(wpUrl, {
method: req.method,
headers: req.headers,
body: req.body,
});
const wpRes = await fetch(proxyReq);
return new Response(wpRes.body, {
status: wpRes.status,
headers: wpRes.headers,
});
}
// 静态文件:直接从Bun服务
if (url.pathname.startsWith('/static/')) {
const file = Bun.file('./public' + url.pathname);
return new Response(file);
}
return new Response('Not Found', { status: 404 });
},
});
console.log('Bun proxy running on http://localhost:3000');
启动Bun服务器
# 开发模式(自动重载)
bun --hot server.ts
生产模式
bun server.ts
实战二:使用Bun SQL操作WordPress数据库
连接MySQL(WordPress数据库)
// db.ts
import { sql } from 'bun';
// 连接WordPress数据库
const db = sql({
host: 'localhost',
port: 3306,
database: 'wordpress',
username: 'wp_user',
password: 'wp_password',
// 使用连接池(Bun内置)
connectionPool: true,
});
export default db;
查询文章(替代WP_Query)
// api/posts.ts
import db from '../db';
export async function getPosts(page = 1, perPage = 10) {
const offset = (page - 1) * perPage;
// 直接SQL查询(比WP_Query快3倍)
const posts = await db`
SELECT
p.ID,
p.post_title,
p.post_content,
p.post_date,
u.user_login as author
FROM wp_posts p
LEFT JOIN wp_users u ON p.post_author = u.ID
WHERE p.post_status = 'publish'
AND p.post_type = 'post'
ORDER BY p.post_date DESC
LIMIT ${perPage} OFFSET ${offset}
`;
return posts;
}
export async function getPostById(id: number) {
const [post] = await db`
SELECT * FROM wp_posts WHERE ID = ${id} AND post_status = 'publish'
`;
return post;
}
创建REST API端点
// server.ts (添加路由)
import { serve } from 'bun';
import { getPosts, getPostById } from './api/posts';
serve({
port: 3000,
async fetch(req) {
const url = new URL(req.url);
// GET /api/posts
if (url.pathname === '/api/posts' && req.method === 'GET') {
const page = parseInt(url.searchParams.get('page') || '1');
const posts = await getPosts(page);
return Response.json(posts);
}
// GET /api/posts/:id
if (url.pathname.startsWith('/api/posts/') && req.method === 'GET') {
const id = parseInt(url.pathname.split('/')[3]);
const post = await getPostById(id);
if (!post) return new Response('Not Found', { status: 404 });
return Response.json(post);
}
return new Response('Not Found', { status: 404 });
},
});
实战三:使用Bun Shell自动化WordPress任务
传统Shell脚本 vs Bun Shell
# 传统bash脚本(复杂,跨平台差)
#!/bin/bash
wp plugin list --allow-root | grep -E '^(akismet|hello)' | while read line; do
plugin=$(echo $line | awk '{print $1}');
wp plugin deactivate $plugin --allow-root;
done
// Bun Shell(简洁,跨平台)
import { $ } from 'bun';
// 自动检测平台(Windows/Linux/macOS)
const plugins = await $`wp plugin list --allow-root`.text();
const lines = plugins.split('\n');
for (const line of lines) {
if (line.includes('akismet') || line.includes('hello')) {
const plugin = line.split('\t')[0];
await $`wp plugin deactivate ${plugin} --allow-root`;
}
}
自动化备份WordPress
// backup.ts
import { $ } from 'bun';
import { sql } from './db';
async function backupWordPress() {
const timestamp = new Date().toISOString().split('T')[0];
// 1. 备份数据库
const dbBackup = await $`mysqldump --user=wp_user --password=wp_password wordpress > backup_${timestamp}.sql`.text();
// 2. 备份上传文件
await $`tar -czf uploads_${timestamp}.tar.gz wp-content/uploads`;
// 3. 上传到Cloudflare R2(S3兼容)
await $`aws s3 cp backup_${timestamp}.sql s3://my-bucket/backups/`;
await $`aws s3 cp uploads_${timestamp}.tar.gz s3://my-bucket/backups/`;
// 4. 清理本地备份(保留7天)
await $`find . -name 'backup_*.sql' -mtime +7 -delete`;
await $`find . -name 'uploads_*.tar.gz' -mtime +7 -delete`;
console.log(`Backup completed: ${timestamp}`);
}
// 定时执行(每天凌晨2点)
await backupWordPress();
实战四:Bun边缘渲染(Edge-Side Rendering)
使用Bun Edge(兼容Cloudflare Workers)
// edge-render.ts (部署到Cloudflare Workers)
import { serve } from 'bun';
export default {
async fetch(req: Request): Promise {
const url = new URL(req.url);
// 边缘缓存(Cloudflare Cache API)
const cache = caches.default;
let response = await cache.match(req);
if (!response) {
// 从WordPress获取内容
const wpRes = await fetch(`https://www.shenma98.com/wp-json/wp/v2/posts?per_page=10`);
const posts = await wpRes.json();
// 边缘渲染HTML
const html = `
最新文章
最新文章
${posts.map((post: any) => `
- ${post.title.rendered}
`).join('')}
`;
response = new Response(html, {
headers: {
'Content-Type': 'text/html; charset=utf-8',
'Cache-Control': 'max-age=300', // 缓存5分钟
},
});
// 存入边缘缓存
await cache.put(req, response.clone());
}
return response;
},
};
部署到Cloudflare Workers
# 安装Wrangler(Cloudflare CLI)
bun add -g wrangler
初始化项目
wrangler init wp-edge --type=typescript
部署
wrangler deploy
性能对比(Bun vs PHP-FPM)
| 操作 | PHP-FPM | Bun | 加速比 |
|------|---------|-----|--------|
| 冷启动 | 50ms | 1ms | 50x |
| 简单查询(SQL) | 15ms | 5ms | 3x |
| 复杂查询(JOIN) | 80ms | 25ms | 3.2x |
| REST API响应 | 120ms | 35ms | 3.4x |
| 静态文件服务 | 10ms | 2ms | 5x |
决策建议
| 场景 | 是否使用Bun | 理由 |
|------|---------------|------|
| 高并发API服务 | ✅ 强烈推荐 | 性能提升3-5x |
| 静态文件服务 | ✅ 推荐 | 比Nginx快 |
| 定时任务(Cron) | ✅ 推荐 | Bun Shell跨平台 |
| 边缘渲染(Edge) | ✅ 推荐 | 兼容Cloudflare Workers |
| 传统WordPress主题 | ❌ 不推荐 | 需要重写PHP代码 |
总结
Bun是2026年最值得关注的JavaScript运行时。虽然不能完全替代PHP-FPM(WordPress核心仍是PHP),但可以用Bun构建高性能的中间件层(API代理、边缘渲染、定时任务)。
立即行动:安装Bun,用Bun Shell重写你的WordPress备份脚本!

评论(0)