golang 使用chan(select)、和goroutine实现:耗时代码块的执行不影响http服务及时响应

简单示例:

package main

import (
	"fmt"
	"math/rand"
	"net/http"
	"time"
)

var myServer = MyServer{}

func main() {	
	_ = http.ListenAndServe(":8080", myServer)
}

type MyServer struct{}

//所有的请求的
func (recv MyServer) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
	c1 := make(chan int, 1)
	go goRequest(c1)
	//读取chan数据等待1s,超过1s会打印出timeout 1
	select {
	case res := <-c1:
		fmt.Println(res)
	case <-time.After(time.Second * 1):
		fmt.Println("timeout 1")
	}
	endTag := "http Connect done !  " + time.Now().Format("2006-01-02 15:04:05")
	fmt.Println(endTag)
	resp.Write([]byte(endTag))
}

func goRequest(ch chan int) {
	staReqTime := time.Now().UnixNano() / 1e6
	rand.Seed(time.Now().UnixNano())
	proX := rand.Intn(10)
	fmt.Println("proX:", proX)
	if proX < 5 {
		//模拟耗时3秒
		time.Sleep(time.Second * 3)
	}
	endReqTime := time.Now().UnixNano() / 1e6
	costTime := endReqTime - staReqTime
	if costTime > 60 {
		//耗用超过60ms,视为超时
		ch <- 0
	} else {
		ch <- 1
	}
	fmt.Println("goRequest end !costTime:", costTime, time.Now().Format("2006-01-02 15:04:05"))
}

测试结果:

猜你喜欢

转载自blog.csdn.net/lctmei/article/details/117993685