前言
提到 n8n,大多数人的印象还停留在「一个可以连接各种 App 的自动化工具」——能发Webhook、做个钉钉通知、填个表格。但你知道吗?这个开源工作流引擎已经悄悄成长为 AI 原生的自动化平台,GitHub 收获了 18.4 万颗星,拥有 400+ 集成、完整的 MCP 支持,甚至可以本地运行 LLM 来做隐私优先的 AI 管道。今天这篇文章,我来分享 8 个连很多 n8n 老手都不知道的高阶玩法。
一、用 Sub-Node 实现多 Agent 循环协作
大多数人用 n8n 的 Agent 节点做单次问答。但真正的隐藏技能是:创建递归 Agent 循环,让多个 Agent 轮流处理任务,每个 Agent 输出自动注入下一个 Agent 的上下文。
实现思路:用 Split In Batches 节点控制循环次数,用不同 LLM(Claude 负责推理、GPT-4o 负责速度、DeepSeek 负责省钱)处理不同阶段。
// n8n Code 节点:路由到不同的 Agent
const taskType = $input.first().json.taskType;
// 任务类型映射到不同模型
const agentMap = {
'reasoning': 'claude', // 需要深度推理
'coding': 'gpt-4o', // 需要代码生成
'budget': 'deepseek' // 预算敏感任务
};
const selected = agentMap[taskType] || 'claude';
return [{
json: {
selectedAgent: selected,
routed: true,
// 记录路由时间,用于分析性能
routedAt: new Date().toISOString()
}
}];
数据来源: n8n GitHub 仓库 184,833 Stars,官方 MCP 集成文档 (GitHub)
二、PostgreSQL 持久化:让 Workflow 状态跨越重启
n8n 的 Workflow 通常是无状态的 JSON 流转。隐藏玩法:用 PostgreSQL 存储 Workflow 状态和二进制文件(图片、PDF、音频),实现断点续传级别的文档处理管道。
-- PostgreSQL:n8n Workflow 状态持久化表
CREATE TABLE workflow_runs (
id SERIAL PRIMARY KEY,
workflow_id VARCHAR(255) NOT NULL,
state JSONB NOT NULL, -- Workflow 执行状态
binary_data BYTEA, -- 二进制附件(图片/PDF)
status VARCHAR(50) DEFAULT 'running',
created_at TIMESTAMP DEFAULT NOW()
);
-- 复合索引:按 Workflow ID 和状态快速查询
CREATE INDEX idx_workflow_runs_status
ON workflow_runs(workflow_id, status);
// n8n Code 节点:写入状态到 PostgreSQL
const state = $input.first().json;
const binary = $input.first().binary; // 附件数据
const { Client } = require('pg');
const client = new Client({ connectionString: process.env.DATABASE_URL });
await client.connect();
// 持久化状态和二进制文件
await client.query(
'INSERT INTO workflow_runs'
+ ' (workflow_id, state, binary_data, status)'
+ ' VALUES ($1, $2, $3, $4)',
[state.workflowId, JSON.stringify(state), binary ? binary.data : null, 'running']
);
await client.end();
return [{ json: { saved: true, workflowId: state.workflowId } }];
💡 这个模式特别适合做 AI 文档分析管道——大文件上传后拆分成多步处理,每步状态持久化到数据库,重启后自动从断点恢复。
三、Webhook + 轮询:处理 30 秒以上的长任务
n8n Webhook 默认是「发完就走」的模式。但当你需要调用 AI 做代码分析、代码库重构等耗时操作时,结果往往需要 30 秒以上才能返回。隐藏解法:用 Webhook 入队,用状态接口轮询结果。
import requests
import time
import uuid
# Step 1: 通过 Webhook 入队一个 AI 长任务
job_id = str(uuid.uuid4())
payload = {
"jobId": job_id,
"prompt": "分析这个代码库并生成架构文档",
"repoUrl": "https://github.com/n8n-io/n8n",
"callbackUrl": "https://myapp.com/results/" + job_id
}
r = requests.post(
"https://your-n8n/webhook/ai-analysis-queue",
json=payload, timeout=10
)
print(f"任务 {job_id} 已入队,开始轮询...")
# Step 2: 轮询状态,最长等待 60 秒
for attempt in range(60):
time.sleep(1)
status = requests.get(
f"https://your-n8n/webhook/job-status/{job_id}",
timeout=5
)
data = status.json()
if data.get("status") == "done":
print(f"分析完成: {data['result']}")
break
elif data.get("status") == "failed":
print(f"任务失败: {data['error']}")
break
HN 热议: GitHub 假星经济 (HN 讨论) 引发了关于自动化工具可信度的辩论,n8n 的开源模式(56,975 Fork)被开发者社区视为健康替代方案。
四、MCP(Model Context Protocol)服务端:让 Claude Code 直接调用 n8n
这是 2026 年最被低估的集成——n8n 可以作为 MCP 服务器运行,把任意 Workflow 暴露为 AI IDE(Claude Code、Cursor 等)可直接调用的工具。想象一下:在 Claude Code 里输入 /analyze-repo 直接触发 n8n 里构建的分析管道。
# 一行命令让 n8n 变成 MCP 服务器
n8n start --mcp-server --mcp-port 3100
# 在 Claude Code 的 claude_desktop_config.json 中添加:
# {
# "mcpServers": {
# "n8n": {
# "command": "npx",
# "args": ["-y", "@n8n/mcp-client",
# "--server", "http://localhost:3100"]
# }
# }
# }
// n8n Workflow 中暴露为 MCP 工具(Code 节点)
const mcpTool = {
toolName: "github_repo_analysis",
description: "分析任意 GitHub 仓库并返回统计信息",
inputSchema: {
type: "object",
properties: {
repoUrl: { type: "string", description: "仓库 URL" }
}
}
};
return [{ json: mcpTool }];
数据来源: everything-claude-code 仓库(161,843 Stars)详细记录了 MCP 集成模式,n8n 作为 Workflow 后端被重点推荐 (GitHub)。
五、本地 LLM 网关:Ollama + n8n 实现隐私优先 AI 管道
将 n8n 与 Ollama 配对,所有 LLM 调用都在本地运行,数据永远不会离开你的网络。这对企业合规和个人隐私保护来说是刚需。
# 启动 Ollama 服务
ollama serve &
# 下载中文友好的模型
ollama pull llama3.2
// n8n Code 节点:构造 Ollama 请求体
const userPrompt = $input.first().json.userPrompt;
return [{
json: {
model: "llama3.2", // 本地运行的模型
prompt: userPrompt,
stream: false, // 非流式响应
options: {
temperature: 0.7, // 控制创造性
num_predict: 512 // 最大 token 数
}
}
}];
// 连接器指向:http://localhost:11434/api/generate
// 结果:完全本地化的 LLM 响应,零外部 API 调用
数据来源: Ollama GitHub 仓库 169,510 Stars,专为本地 LLM 运行设计 (GitHub)
六、GitHub Webhook 驱动的自动代码审查管道
n8n 可以监听 GitHub Webhook,触发 LLM 代码审查,自动将审查结果以 PR Comment 形式发回。完全自动化,不需要人工介入。
import hmac
import hashlib
import requests
GITHUB_SECRET = "your-webhook-secret"
GITHUB_TOKEN = "ghp_your_personal_access_token"
def post_pr_comment(owner, repo, pr_number, comment_body):
# 将 AI 审查结果写入 PR 评论
api_url = f"https://api.github.com/repos/{owner}/{repo}/issues/{pr_number}/comments"
headers = {
"Authorization": f"token {GITHUB_TOKEN}",
"Accept": "application/vnd.github.v3+json"
}
resp = requests.post(api_url, json={"body": comment_body}, headers=headers)
return resp.status_code == 201
# 在 n8n 的 GitHub Webhook 节点中验证签名
# 然后触发 LLM 审查流程
七、动态定时:队列深度驱动的智能调度
大多数 n8n 用户设置固定的 Cron 表达式。但隐藏玩法是事件驱动的动态调度——根据消息队列深度自动调整执行频率,队列积压多就高频执行,空闲时就降低频率。
// n8n Code 节点:根据队列深度计算下次执行间隔
async function getQueueDepth() {
const resp = await fetch('https://your-queue-metrics-api/depth');
return (await resp.json()).pending;
}
const depth = await getQueueDepth();
let nextCron;
// 队列深度分级调度
if (depth > 1000) {
nextCron = '*/5 * * * *'; // 每 5 分钟(高负载)
} else if (depth > 100) {
nextCron = '*/30 * * * *'; // 每 30 分钟(正常)
} else {
nextCron = '0 */2 * * *'; // 每 2 小时(低负载)
}
return [{
json: {
queueDepth: depth,
suggestedCron: nextCron,
autoTuned: true
}
}];
八、Dead Letter Queue:优雅的失败恢复机制
n8n 自带的重试机制比较基础。真正的生产级玩法是实现 DLQ(死信队列)——失败的执行进入一个独立 Workflow,自动重试 + 指数退避,超过重试次数后触发人工介入或 Slack 通知。
// n8n Code 节点:DLQ 处理器
const MAX_RETRIES = 3;
const item = $input.first().json;
const retryCount = item._retryCount || 0;
const errorMsg = item.error || 'Unknown error';
if (retryCount < MAX_RETRIES) {
// 指数退避重试:2^retryCount 秒后再次执行
return [{
json: {
...item,
_retryCount: retryCount + 1,
_nextRetryDelayMs: Math.pow(2, retryCount) * 1000,
_willRetry: true
}
}];
} else {
// 进入 DLQ,通知人工处理
return [{
json: {
dlq: true,
originalError: errorMsg,
failedAt: new Date().toISOString(),
notifySlack: true,
slackMessage: 'n8n Workflow 失败: ' + item.workflowName + ' 错误: ' + errorMsg
}
}];
}
总结
n8n 已经远不只是一个「连接 App 的自动化工具」。凭借原生 AI Agent 支持、MCP 集成、本地 LLM 编排和强大的企业级特性,它已经成长为真正的 AI 原生自动化平台,GitHub 18.4 万星就是最好的证明。上述 8 个高阶玩法——多 Agent 循环、PostgreSQL 持久化、DLQ 模式——才是区分生产级 n8n 部署和玩具项目的关键。
你打算先尝试哪个玩法?欢迎在评论区分享你的 n8n 奇技淫巧!
相关文章
数据来源:GitHub Stars and Fork 数来自 n8n-io/n8n、ollama/ollama、everything-claude-code。Hacker News 讨论来自 HN Frontpage。
Top comments (0)