使用Golang简单实现七牛图片处理API

2020-01-28 12:05:40丽君

从 job payload 中解析出需要做的任务,解析出每个cmd, 最好能并行执行每一个 cmd, 记录每一个cmd的结果

每个cmd中有多个 operation, 并且用 pipe 连接,前一个operaion的输出是后一个operation的输入

可以把 1 和 2,3 分开来看,1 比较独立,之前写过一个worker的模型,参考的是这篇文章 Handling 1 Million Requests per Minute with Go,比较详细,是用 go channel 作为queue的,我加了一个 beanstalk 作为 queue的 providor。还有一点改进是,文章中只提供了worker数量的设置,我再加了一个参数,设定每个worker可以并行执行的协程数。所以下面主要讲讲3, 2的解决办法

Pipe

可以参考这个库 pipe, 用法如下:


p := pipe.Line(
    pipe.ReadFile("test.png"),
    resize(300, 300),
    blur(0.5),
)

output, err := pipe.CombinedOutput(p)
if err != nil {
    fmt.Printf("%vn", err)
}

buf := bytes.NewBuffer(output)
img, _ := imaging.Decode(buf)

imaging.Save(img, "test_a.png")

还是比较方便的,建一个 Cmd struct, 利用正则匹配一下每个 Operation 的参数,放入一个 []Op slice, 最后执行,struct和方法如下:


type Cmd struct {
    cmd    string
    saveas string
    ops    []Op
    err    error
}

type Op interface {
    getPipe() pipe.Pipe
}

type ResizeOp struct {
    width, height int
}

func (c ResizeOp) getPipe() pipe.Pipe {
    return resize(c.width, c.height)
}

//使用方法
cmdStr := `file/test.png|thumbnail/x300|blur/20x8`
cmd := Cmd{cmdStr, "test_b.png", nil, nil}

cmd.parse()
cmd.doOps()
sync.WaitGroup

单个cmd处理解决后,就是多个cmd的并行问题,没啥好想的,直接用 sync.WaitGroup 就可以完美解决。一步一步来,我们先看看这个struct的使用方法:


func main() {
    cmds := []string{}
    for i := 0; i < 10000; i++ {
        cmds = append(cmds, fmt.Sprintf("cmd-%d", i))
    }

    results := handleCmds(cmds)

    fmt.Println(len(results)) // 10000
}

func doCmd(cmd string) string {
    return fmt.Sprintf("cmd=%s", cmd)
}

func handleCmds(cmds []string) (results []string) {
    fmt.Println(len(cmds)) //10000
    var count uint64

    group := sync.WaitGroup{}
    lock := sync.Mutex{}
    for _, item := range cmds {