Easy-Go-Web3
知识图谱Go 教程React Web3智能合约
需求分析系统设计设计模式Go 微服务
项目实战DevOps
Go 生态React 生态智能合约生态Web3 生态AI × Web3工具箱Web3 公司远程Web3求职
🎯 AA 工程师面试手册博客
GitHub
返回设计模式
并发型

Pipeline 模式

将处理过程分解为多个阶段,每个阶段通过 channel 连接。

问题场景

数据需要经过多个处理步骤,每个步骤可以并行执行。

解决方案

每个阶段是一个 goroutine,通过 channel 传递数据。

Go 实现

pipeline.go
go
1// 区块处理 Pipeline
2func BlockPipeline(ctx context.Context, blocks <-chan *types.Block) <-chan *ProcessedBlock {
3 // Stage 1: 解析交易
4 txs := parseTxStage(ctx, blocks)
5
6 // Stage 2: 解码日志
7 logs := decodeLogsStage(ctx, txs)
8
9 // Stage 3: 存储数据
10 results := storeStage(ctx, logs)
11
12 return results
13}
14
15func parseTxStage(ctx context.Context, in <-chan *types.Block) <-chan *ParsedTx {
16 out := make(chan *ParsedTx)
17 go func() {
18 defer close(out)
19 for block := range in {
20 for _, tx := range block.Transactions() {
21 parsed := parseTx(tx)
22 select {
23 case out <- parsed:
24 case <-ctx.Done():
25 return
26 }
27 }
28 }
29 }()
30 return out
31}
32
33func decodeLogsStage(ctx context.Context, in <-chan *ParsedTx) <-chan *DecodedLog {
34 out := make(chan *DecodedLog)
35 go func() {
36 defer close(out)
37 for tx := range in {
38 for _, log := range tx.Logs {
39 decoded := decodeLog(log)
40 select {
41 case out <- decoded:
42 case <-ctx.Done():
43 return
44 }
45 }
46 }
47 }()
48 return out
49}

Web3 应用场景

区块链数据索引器,流式处理区块、交易、事件。

优点

  • +阶段独立
  • +易于扩展
  • +自然流控

缺点

  • -调试复杂
  • -错误处理需要设计
Worker PoolFan-out/Fan-in
Easy-Go-Web3

构建 Go 后端与 Web3 的学习之路。从基础到进阶,从理论到实践,助你成为全栈区块链开发者。

学习路径

  • 知识图谱
  • Go 教程
  • Go 微服务
  • 面试手册

资源中心

  • 工具箱
  • DevOps 工具
  • Web3 生态
  • 博客

© 2025 Easy-Go-Web3. All rights reserved.

Created withbyhardybao