一、需求背景
题库服务,自动判题逻辑处理耗时较长,每张试卷也会包含多道题目,若采用同步处理,耗时时间会成倍增加,需要改为并行异步处理。
二、实现功能
同时最高并发1000个请求做异步处理
三、基于go实现
// +build ignore
package main
import (
"fmt"
"time"
)
type Req struct {
ID int `json:id`
}
type Resp struct {
ID int `json:id`
Res int `json:res`
}
type Data struct {
ReqChan chan *Req `json:req_chan`
RespChan chan *Resp `json:resp_chan`
}
func deal(data Data) {
for i := 0; i < 10; i++ {
go dealSingle(data.ReqChan, data.RespChan)
}
}
func dealSingle(reqChan chan *Req, respChan chan *Resp) {
for {
if v, ok := <-reqChan; ok {
respChan <- &Resp{ID: v.ID, Res: v.ID * v.ID}
}
time.Sleep(time.S