使用Deno Deploy快速部署边缘函数

本文详解使用Deno Deploy部署边缘函数的完整流程。

为什么选择Deno Deploy

平台 运行时 启动延迟 免费额度
Cloudflare Workers V8 Isolate ~1ms 10万请求/天
Vercel Edge V8 Isolate ~2ms 100GB带宽/月
Deno Deploy Deno (V8) ~1ms 100万请求/月

第一个Deno Deploy函数

本地创建项目

# 安装Deno
curl -fsSL https://deno.land/x/install/install.sh | sh

# 创建项目
mkdir my-edge-app
cd my-edge-app
deno init

编写边缘函数

// main.ts - Deno Deploy入口
export default {
  async fetch(request: Request): Promise<Response> {
    const url = new URL(request.url);

    if (url.pathname === '/api/hello') {
      return new Response(
        JSON.stringify({ message: 'Hello from Deno Deploy!' }),
        {
          headers: { 'Content-Type': 'application/json' },
        }
      );
    }

    if (url.pathname === '/api/time') {
      const now = new Date().toISOString();
      return new Response(
        JSON.stringify({ time: now }),
        {
          headers: { 'Content-Type': 'application/json' },
        }
      );
    }

    return new Response('Not Found', { status: 404 });
  }
};

部署到Deno Deploy

方式一:GitHub集成(推荐)

1. 将代码推送到GitHub仓库
2. 访问 https://deno.com/deploy
3. 点击 "New Project"
4. 选择GitHub仓库
5. 配置
   - Entry point: main.ts
   - Branch: main
6. 点击 "Deploy"
7. 获得 *.deno.dev 域名

方式二:CLI部署

# 安装deployctl
deno install --allow-read --allow-write --allow-env --allow-net --allow-run --name deployctl https://deno.land/x/deploy/deployctl.ts

# 部署
deployctl deploy main.ts --project=my-edge-app

实战:边缘API代理

防止API密钥泄露

// proxy.ts - 隐藏API密钥
const API_KEY = Deno.env.get('API_KEY')!;

export default {
  async fetch(request: Request): Promise<Response> {
    const url = new URL(request.url);
    const targetUrl = 'https://api.openweathermap.org/data/2.5/weather';

    const params = new URLSearchParams({
      q: url.searchParams.get('city') || 'Beijing',
      appid: API_KEY,
      units: 'metric',
    });

    const response = await fetch(`${targetUrl}?${params}`);
    const data = await response.json();

    return new Response(JSON.stringify(data), {
      headers: {
        'Content-Type': 'application/json',
        'Cache-Control': 's-maxage=300', // 边缘缓存5分钟
      },
    });
  }
};

设置环境变量

# 在Deno Deploy Dashboard中设置
# Settings → Environment Variables → Add
API_KEY=your_secret_api_key

实战:边缘A/B测试

使用Deno KV(内置KV存储)

// ab-test.ts
export default {
  async fetch(request: Request): Promise<Response> {
    const url = new URL(request.url);

    // 读取用户Cookie
    const cookie = request.headers.get('Cookie') || '';
    let variant = getCookie(cookie, 'ab_variant');

    // 新用户随机分配
    if (!variant) {
      variant = Math.random() < 0.5 ? 'A' : 'B';
    }

    // 从源站获取页面
    let response = await fetch('https://example.com', request);
    let html = await response.text();

    // 修改HTML
    if (variant === 'A') {
      html = html.replace('Buy Now', 'Buy Now (20% OFF)');
    } else {
      html = html.replace('Buy Now', 'Buy Now (Free Shipping)');
    }

    // 设置Cookie
    return new Response(html, {
      headers: {
        'Content-Type': 'text/html',
        'Set-Cookie': `ab_variant=${variant}; Max-Age=604800; Path=/`,
      },
    });
  }
};

function getCookie(cookie: string, name: string): string | null {
  const match = cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
  return match ? match[2] : null;
}

Deno Deploy的高级功能

1. Subhosting(多租户)

// 根据域名加载不同配置
export default {
  async fetch(request: Request): Promise<Response> {
    const hostname = new URL(request.url).hostname;

    // 租户A的配置
    if (hostname === 'tenant-a.deno.dev') {
      return new Response('Tenant A', { headers: { 'X-Tenant': 'A' } });
    }

    // 租户B的配置
    if (hostname === 'tenant-b.deno.dev') {
      return new Response('Tenant B', { headers: { 'X-Tenant': 'B' } });
    }

    return new Response('Unknown Tenant', { status: 404 });
  }
};

2. 边缘缓存策略

export default {
  async fetch(request: Request): Promise<Response> {
    // 尝试从缓存读取
    const cache = caches.default;
    let response = await cache.match(request);

    if (!response) {
      // 回源
      response = await fetch('https://api.example.com/data');

      // 克隆响应(可以多次使用)
      const clone = response.clone();

      // 缓存响应
      await cache.put(request, clone);
    }

    return response;
  }
};

3. 流式响应(Streaming)

export default {
  async fetch(request: Request): Promise<Response> {
    const body = new ReadableStream({
      async start(controller) {
        for (let i = 0; i < 10; i++) {
          controller.enqueue(new TextEncoder().encode(`Chunk ${i}\n`));
          await new Promise(resolve => setTimeout(resolve, 100));
        }
        controller.close();
      }
    });

    return new Response(body, {
      headers: { 'Content-Type': 'text/plain' },
    });
  }
};

性能优化

1. 减少冷启动时间

// ❌ 错误:每次请求都导入大模块
export default {
  async fetch(request: Request): Promise<Response> {
    const { bigLibrary } = await import('./big-library.ts');
    return new Response(bigLibrary.process());
  }
}

// ✅ 正确:顶层导入(只加载一次)
import { process } from './big-library.ts';

export default {
  async fetch(request: Request): Promise<Response> {
    return new Response(process());
  }
}

2. 使用HTTP缓存

export default {
  async fetch(request: Request): Promise<Response> {
    const response = await fetch('https://api.example.com/data');

    // 添加缓存头
    const headers = new Headers(response.headers);
    headers.set('Cache-Control', 'public, max-age=60, s-maxage=300');

    return new Response(response.body, { headers });
  }
}

与WordPress集成

使用Deno Deploy作为WordPress API网关

// wordpress-proxy.ts
const WP_URL = 'https://www.shenma98.com';

export default {
  async fetch(request: Request): Promise<Response> {
    const url = new URL(request.url);

    // 代理WordPress REST API
    if (url.pathname.startsWith('/wp-json/')) {
      const wpUrl = WP_URL + url.pathname + url.search;
      return fetch(wpUrl, {
        headers: {
          'X-Forwarded-For': request.headers.get('CF-Connecting-IP') || '',
        },
      });
    }

    // 其他请求回源
    return fetch(WP_URL + url.pathname, request);
  }
};

成本分析

方案 免费额度 超出后费用
Deno Deploy 100万请求/月,100GB带宽 $2/百万请求,$0.05/GB
Cloudflare Workers 10万请求/天 $0.50/百万请求
Vercel Edge 100GB带宽/月 $40/100GB(超出后)

2026年Deno Deploy趋势

趋势一:Deno 2.0稳定性

Deno 2.0(2025年底发布):
- 完全兼容Node.js/npm包
- 性能提升30%(相比Deno 1.x)
- 内置SQLite(边缘数据库)

趋势二:Deno KV正式版

Deno KV(类似于Cloudflare KV):
- 强一致性(Compare-and-Set)
- 自动全球复制
- 免费额度:1GB存储,10万读取/天

趋势三:边缘AI推理

// 在Deno Deploy中运行ONNX模型
import { InferenceSession } from 'onnxruntime-node';

export default {
  async fetch(request: Request): Promise<Response> {
    const session = await InferenceSession.create('model.onnx');
    const input = new Float32Array([1, 2, 3]);
    const output = await session.run({ input });
    return new Response(JSON.stringify(output));
  }
};

部署检查清单

  • [ ] 代码推送到GitHub(或使用deployctl)
  • [ ] 配置环境变量(API密钥等)
  • [ ] 设置自定义域名(可选)
  • [ ] 配置Deno KV(如果需要)
  • [ ] 测试边缘函数(本地 deno run --allow-net main.ts
  • [ ] 查看Deno Deploy Dashboard(监控请求/错误)

总结

Deno Deploy是2026年边缘函数领域的有力竞争者,特别适合:
1. TypeScript原生支持(无需编译)
2. 免费额度慷慨(100万请求/月)
3. 与Deno KV深度集成(边缘存储)

立即行动:访问 https://deno.com/deploy 开始你的第一个边缘函数。

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。