Files
n8n-guide/docs/learning/basic-workflows.md
2025-09-09 09:29:17 +08:00

367 lines
11 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 基本工作流创建
## 📚 学习资源
- **图文教程**[n8n工作流创建完整指南](https://mp.weixin.qq.com/s/oIcmTW0Gg2r63C0Tn91r2Q)
- **视频教程**[从零开始的n8n实战](https://www.bilibili.com/video/BV1nejbz6Eip)
- **官方文档**[n8n Workflow Examples](https://docs.n8n.io/workflows/)
通过本章节您将学会如何从零开始设计和构建实用的n8n工作流。
## 🎯 工作流设计原则
### SOLID原则在工作流中的应用
| 原则 | 工作流应用 | 实践建议 |
|------|------------|----------|
| **单一职责** | 每个工作流专注一个业务目标 | 避免在一个工作流中处理多个不相关的任务 |
| **开放封闭** | 易于扩展,难以修改核心逻辑 | 使用子工作流和模板化设计 |
| **里氏替换** | 相似节点可以互相替换 | 标准化节点接口和数据格式 |
| **接口隔离** | 最小化节点间依赖 | 只传递必要的数据字段 |
| **依赖倒置** | 依赖抽象而非具体实现 | 使用凭证管理而非硬编码 |
### 工作流生命周期
**需求分析****流程设计****节点配置****测试调试****部署运行****监控维护****优化迭代** → 回到流程设计
## 📝 第一个工作流:每日天气邮件
让我们从一个简单但实用的例子开始学习。
### 需求分析
**目标**: 每天早上8点自动获取天气信息并发送邮件提醒
**数据源**: OpenWeatherMap API
**输出**: HTML格式的天气邮件
**频率**: 每日执行
### 工作流设计
**Schedule Trigger每天8:00****HTTP Request获取天气API****Set Node处理天气数据****Code Node生成邮件HTML****Email Send发送天气邮件**
### 详细配置步骤
=== "1. 定时触发器配置"
```yaml
节点类型: Schedule Trigger
触发规则: Cron
Cron表达式: 0 8 * * *
时区: Asia/Shanghai
```
=== "2. 天气API请求"
```javascript
// HTTP Request 节点配置
{
"method": "GET",
"url": "https://api.openweathermap.org/data/2.5/weather",
"qs": {
"q": "Beijing,CN",
"appid": "{{$credentials.openweather.api_key}}",
"units": "metric",
"lang": "zh_cn"
}
}
```
=== "3. 数据处理"
```javascript
// Set 节点 - 提取有用信息
{
"city": "={{$json.name}}",
"temperature": "={{Math.round($json.main.temp)}}",
"feels_like": "={{Math.round($json.main.feels_like)}}",
"humidity": "={{$json.main.humidity}}",
"description": "={{$json.weather[0].description}}",
"icon": "={{$json.weather[0].icon}}",
"wind_speed": "={{$json.wind.speed}}",
"current_time": "={{new Date().toLocaleString('zh-CN', {timeZone: 'Asia/Shanghai'})}}"
}
```
=== "4. HTML邮件生成"
```javascript
// Code 节点 - 生成邮件HTML
const weatherData = $input.first().json;
const htmlContent = `
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
.weather-card {
font-family: 'Arial', sans-serif;
max-width: 600px;
margin: 0 auto;
background: linear-gradient(135deg, #74b9ff, #0984e3);
color: white;
padding: 30px;
border-radius: 15px;
text-align: center;
}
.temperature {
font-size: 48px;
font-weight: bold;
margin: 20px 0;
}
.details {
display: flex;
justify-content: space-around;
margin-top: 30px;
}
.detail-item {
text-align: center;
}
.detail-value {
font-size: 24px;
font-weight: bold;
}
.detail-label {
font-size: 14px;
opacity: 0.8;
}
</style>
</head>
<body>
<div class="weather-card">
<h2>🌤️ ${weatherData.city} 今日天气</h2>
<div class="temperature">${weatherData.temperature}°C</div>
<p>${weatherData.description}</p>
<p>体感温度:${weatherData.feels_like}°C</p>
<div class="details">
<div class="detail-item">
<div class="detail-value">💧${weatherData.humidity}%</div>
<div class="detail-label">湿度</div>
</div>
<div class="detail-item">
<div class="detail-value">🌬️${weatherData.wind_speed}m/s</div>
<div class="detail-label">风速</div>
</div>
</div>
<hr style="margin: 30px 0; border: 1px solid rgba(255,255,255,0.3);">
<p style="font-size: 12px; opacity: 0.8;">
更新时间:${weatherData.current_time}<br>
由 n8n 自动发送 ❤️
</p>
</div>
</body>
</html>`;
return [{
json: {
html_content: htmlContent,
subject: `${weatherData.city} ${weatherData.temperature}°C - ${weatherData.description}`,
weather_summary: `今日${weatherData.city}气温${weatherData.temperature}°C${weatherData.description}`
}
}];
```
=== "5. 邮件发送"
```yaml
节点类型: Email Send
收件人: your-email@example.com
主题: "={{$json.subject}}"
邮件类型: HTML
邮件内容: "={{$json.html_content}}"
```
## 🔄 进阶工作流:客户反馈处理系统
现在我们来构建一个更复杂的业务工作流。
### 业务场景
**目标**: 自动化处理客户反馈表单提交
**触发**: 网站表单Webhook
**处理**: 分类、存储、分配、通知
**输出**: 多渠道通知和工单创建
### 工作流架构
**Webhook接收** → **判断反馈类型**
- **投诉** → 高优先级处理 → 发送紧急通知 + 创建高优先级工单 → 发送客户确认
- **建议** → 普通优先级处理 → 存储到数据库 + 分配给客服 → 发送客户确认
- **咨询** → 自动回复处理 → AI自动回复 + 发送确认邮件 → 发送客户确认
### 核心节点配置
=== "Webhook接收"
```javascript
// Webhook 节点配置
{
"httpMethod": "POST",
"path": "customer-feedback",
"authentication": "headerAuth",
"options": {
"rawBody": false
}
}
```
=== "反馈分类逻辑"
```javascript
// Switch 节点 - 根据反馈类型分发
const feedbackType = $json.body.feedback_type || 'unknown';
const urgentKeywords = ['投诉', '不满', '退款', '问题', '错误'];
const content = $json.body.message || '';
// 检查是否包含紧急关键词
const isUrgent = urgentKeywords.some(keyword =>
content.includes(keyword)
);
if (feedbackType === 'complaint' || isUrgent) {
return [0]; // 投诉流程
} else if (feedbackType === 'suggestion') {
return [1]; // 建议流程
} else {
return [2]; // 咨询流程
}
```
=== "数据库存储"
```sql
-- PostgreSQL 插入语句
INSERT INTO customer_feedback (
customer_name,
customer_email,
feedback_type,
message,
priority,
status,
created_at,
assigned_to
) VALUES (
'{{$json.body.name}}',
'{{$json.body.email}}',
'{{$json.body.feedback_type}}',
'{{$json.body.message}}',
'{{$json.priority || "normal"}}',
'new',
NOW(),
'{{$json.assigned_agent || null}}'
);
```
=== "AI自动回复"
```javascript
// AI Agent 节点配置
{
"model": "gpt-3.5-turbo",
"prompt": `你是一个专业的客服助手。客户发来了以下咨询:
客户姓名:{{$json.body.name}}
咨询内容:{{$json.body.message}}
请生成一个专业、友好的自动回复邮件,内容应该:
1. 感谢客户的咨询
2. 确认已收到并会尽快处理
3. 提供预计回复时间
4. 如果是常见问题,提供初步解答
5. 保持礼貌和专业的语调
请以中文回复,格式为邮件正文。`,
"temperature": 0.7,
"max_tokens": 500
}
```
## 🔧 工作流最佳实践
### 错误处理和重试机制
**主流程** → **判断执行成功?**
- **是** → 正常完成
- **否** → Error Trigger → **判断重试次数 < 3**
- **是** → 等待延迟 → 重新执行 → 回到主流程
- **否** → 发送失败通知 → 记录错误日志
### 性能优化建议
!!! tip "性能优化技巧"
**1. 批量处理**
```javascript
// 避免在循环中频繁API调用
// 好的做法:批量收集数据,一次性处理
const batchData = [];
for (const item of $input.all()) {
batchData.push(item.json);
}
// 批量API调用
const result = await callBatchAPI(batchData);
```
**2. 缓存机制**
```javascript
// 使用Set节点缓存常用数据
const cacheKey = `cache_${$json.query_key}`;
const cachedData = $workflow.cache[cacheKey];
if (cachedData && cachedData.timestamp > Date.now() - 3600000) {
return cachedData.data; // 使用1小时内的缓存
}
```
**3. 并行执行**:数据输入 → 拆分数据 → 并行处理1/2/3 → 合并结果
### 测试和调试策略
**1. 单元测试**
- 单独测试每个节点
- 使用测试数据验证逻辑
- 检查数据转换正确性
**2. 集成测试**
- 端到端流程测试
- 异常情况模拟
- 性能压力测试
**3. 调试技巧**
```javascript
// 在Code节点中添加调试信息
console.log('调试信息:', {
input_data: $input.all(),
processed_count: processedItems.length,
timestamp: new Date().toISOString()
});
// 使用Set节点添加调试字段
{
"debug_info": {
"node_name": "数据处理节点",
"execution_time": "={{Date.now()}}",
"input_size": "={{$input.all().length}}"
},
"original_data": "={{$json}}"
}
```
## 📚 工作流模板库
### 常用业务模板
| 模板类型 | 适用场景 | 核心节点 |
|---------|---------|----------|
| **数据同步** | CRM、ERP系统集成 | Schedule + HTTP + Database |
| **内容管理** | 社交媒体自动发布 | RSS + AI + Social Media APIs |
| **监控告警** | 系统监控、业务监控 | HTTP + IF + Email/Slack |
| **报告生成** | 定期业务报告 | Database + AI + Email |
| **客户服务** | 工单管理、自动回复 | Webhook + AI + Database |
### 学习资源
- **图文教程**: [n8n工作流创建完整指南](https://mp.weixin.qq.com/s/oIcmTW0Gg2r63C0Tn91r2Q)
- **视频教程**: [从零开始的n8n实战](https://www.bilibili.com/video/BV1nejbz6Eip)
- **官方文档**: [n8n Workflow Examples](https://docs.n8n.io/workflows/)
---
掌握了基本工作流创建后,您就可以开始构建更复杂的自动化解决方案了!
[上一章:常用节点](common-nodes/){ .md-button } [下一章:避坑指南](pitfalls/){ .md-button .md-button--primary }