>  기사  >  백엔드 개발  >  Golang 컨텍스트에 대한 자세한 설명

Golang 컨텍스트에 대한 자세한 설명

藏色散人
藏色散人앞으로
2020-09-10 09:30:293825검색

다음 칼럼에서는 golang tutorial 칼럼에서 Golang 컨텍스트에 대해 자세히 설명하겠습니다. 필요한 친구들에게 도움이 되길 바랍니다!

Golang 컨텍스트에 대한 자세한 설명

머리말

네, 오늘은 나가서 놀고 싶었어요. 기차표를 사서 또 늦잠을 잤어요. . 방법은 없고, 어쩌면 신의 뜻일지도 모르니, 그 맥락과의 단절을 바라며 골랑의 맥락을 요약해야 한다.

회사에서 다양한 서비스를 작성할 때 Context를 첫 번째 매개변수로 사용해야 합니다. 처음에는 주로 풀링크 문제 해결 및 추적에 사용되는 것으로 생각했습니다. 하지만 더 많이 접촉할수록 그 이상이라는 것이 드러납니다.

Text

1.컨텍스트 상세 설명

1.1 세대 배경

go 1.7 이전에는 컨텍스트가 아직 컴파일되지 않았습니다(golang.org/x/net/context에 포함됨). 는 여러 곳에서 사용되므로 1.7 버전에 통합되어 공식적으로 표준 라이브러리에 들어갔습니다.

컨텍스트의 일반적인 사용 자세:
1. 웹 프로그래밍에서 하나의 요청은 여러 고루틴 간의 데이터 상호 작용에 해당합니다.
2. 시간 초과 제어
3. 컨텍스트 제어

1.2 컨텍스트의 기본 구조

type Context interface {
    Deadline() (deadline time.Time, ok bool)
    Done() <-chan struct{}
    Err() error
    Value(key interface{}) interface{}
}

이것이 바로 Context입니다. 기본 데이터 구조:

field 의미
Deadline 은 현재 컨텍스트가 종료되어야 하는 시간을 나타내는 time.Time을 반환하고 ok는 종료 시간이 있음을 의미합니다
Done 컨텍스트가 취소되거나 시간 초과되면 반환되는 닫기 채널로, 컨텍스트 관련 기능에 현재 작업을 중지하고 반환하도록 지시합니다. (이건 글로벌 브로드캐스트와 약간 비슷함)
Err 컨텍스트가 취소된 이유
Value context는 코루틴에 안전한 공유 데이터 저장소를 구현합니다. (이전에는 지도가 안전하지 않다고 했던 것을 기억하세요) ? 그래서 맵 구조를 만났을 때 sync.Map이 아니면 작동을 위해 잠가야 합니다.)

동시에 패키지는 취소 기능을 제공하기 위해 구현해야 하는 인터페이스도 정의합니다. 기능. 이는 주로 후술할 '취소 신호 및 타임아웃 신호'를 구현해야 하기 때문이다.

// A canceler is a context type that can be canceled directly. The
// implementations are *cancelCtx and *timerCtx.
type canceler interface {
	cancel(removeFromParent bool, err error)
	Done() <-chan struct{}
}

그런 다음 라이브러리는 모든 사람이 놀 수 있는 4가지 컨텍스트 구현을 제공합니다. 비어 있음 컨텍스트, 구현 함수는 또한 반환합니다. 전혀, 그들은 단지 Context 인터페이스를 구현합니다

cancelCtxtype cancelCtx struct {  mu  sync.Mutex  children map[c  anceler]struct{} error Deadline time.Time } 에서 상속됨, 시간 초과 메커니즘 추가 valueCtxtype valueCtx struct {

1.3 context的创建

为了更方便的创建Context,包里头定义了Background来作为所有Context的根,它是一个emptyCtx的实例。

var (
    background = new(emptyCtx)
    todo       = new(emptyCtx) // 
)

func Background() Context {
    return background
}

你可以认为所有的Context是树的结构,Background是树的根,当任一Context被取消的时候,那么继承它的Context 都将被回收。

2.context实战应用

2.1 WithCancel

实现源码:

func WithCancel(parent Context) (ctx Context, cancel CancelFunc) {
	c := newCancelCtx(parent)
	propagateCancel(parent, &c)
	return &c, func() { c.cancel(true, Canceled) }
}

实战场景:
执行一段代码,控制执行到某个度的时候,整个程序结束。

吃汉堡比赛,奥特曼每秒吃0-5个,计算吃到10的用时
实战代码:

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	eatNum := chiHanBao(ctx)
	for n := range eatNum {
		if n >= 10 {
			cancel()
			break
		}
	}

	fmt.Println("正在统计结果。。。")
	time.Sleep(1 * time.Second)
}

func chiHanBao(ctx context.Context) <-chan int {
	c := make(chan int)
	// 个数
	n := 0
	// 时间
	t := 0
	go func() {
		for {
			//time.Sleep(time.Second)
			select {
			case <-ctx.Done():
				fmt.Printf("耗时 %d 秒,吃了 %d 个汉堡 \n", t, n)
				return
			case c <- n:
				incr := rand.Intn(5)
				n += incr
				if n >= 10 {
					n = 10
				}
				t++
				fmt.Printf("我吃了 %d 个汉堡\n", n)
			}
		}
	}()

	return c
}

输出:

我吃了 1 个汉堡
我吃了 3 个汉堡
我吃了 5 个汉堡
我吃了 9 个汉堡
我吃了 10 个汉堡
正在统计结果。。。
耗时 6 秒,吃了 10 个汉堡

2.2 WithDeadline & WithTimeout

实现源码:

func WithDeadline(parent Context, d time.Time) (Context, CancelFunc) {
	if cur, ok := parent.Deadline(); ok && cur.Before(d) {
		// The current deadline is already sooner than the new one.
		return WithCancel(parent)
	}
	c := &timerCtx{
		cancelCtx: newCancelCtx(parent),
		deadline:  d,
	}
	propagateCancel(parent, c)
	dur := time.Until(d)
	if dur <= 0 {
		c.cancel(true, DeadlineExceeded) // deadline has already passed
		return c, func() { c.cancel(true, Canceled) }
	}
	c.mu.Lock()
	defer c.mu.Unlock()
	if c.err == nil {
		c.timer = time.AfterFunc(dur, func() {
			c.cancel(true, DeadlineExceeded)
		})
	}
	return c, func() { c.cancel(true, Canceled) }
}

func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) {
	return WithDeadline(parent, time.Now().Add(timeout))
}

实战场景:
执行一段代码,控制执行到某个时间的时候,整个程序结束。

吃汉堡比赛,奥特曼每秒吃0-5个,用时10秒,可以吃多少个
实战代码:

func main() {
    // ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(10))
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	chiHanBao(ctx)
	defer cancel()
}

func chiHanBao(ctx context.Context) {
	n := 0
	for {
		select {
		case <-ctx.Done():
			fmt.Println("stop \n")
			return
		default:
			incr := rand.Intn(5)
			n += incr
			fmt.Printf("我吃了 %d 个汉堡\n", n)
		}
		time.Sleep(time.Second)
	}
}

输出:

我吃了 1 个汉堡
我吃了 3 个汉堡
我吃了 5 个汉堡
我吃了 9 个汉堡
我吃了 10 个汉堡
我吃了 13 个汉堡
我吃了 13 个汉堡
我吃了 13 个汉堡
我吃了 14 个汉堡
我吃了 14 个汉堡
stop

2.3 WithValue

实现源码:

func WithValue(parent Context, key, val interface{}) Context {
	if key == nil {
		panic("nil key")
	}
	if !reflect.TypeOf(key).Comparable() {
		panic("key is not comparable")
	}
	return &valueCtx{parent, key, val}
}

实战场景:
携带关键信息,为全链路提供线索,比如接入elk等系统,需要来一个trace_id,那WithValue就非常适合做这个事。
实战代码:

func main() {
	ctx := context.WithValue(context.Background(), "trace_id", "88888888")
	// 携带session到后面的程序中去
	ctx = context.WithValue(ctx, "session", 1)

	process(ctx)
}

func process(ctx context.Context) {
	session, ok := ctx.Value("session").(int)
	fmt.Println(ok)
	if !ok {
		fmt.Println("something wrong")
		return
	}

	if session != 1 {
		fmt.Println("session 未通过")
		return
	}

	traceID := ctx.Value("trace_id").(string)
	fmt.Println("traceID:", traceID, "-session:", session)
}

输出:

traceID: 88888888 -session: 1

3.context建议

不多就一个。

Context要是全链路函数的第一个参数

func myTest(ctx context.Context)  {
    ...
}

(写好了竟然忘记发送了。。。汗)

 Context  done  chan struct{}
cancelCtx
 Context
 key, val 인터페이스{}
}

키-값 쌍 데이터 저장


위 내용은 Golang 컨텍스트에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 csdn.net에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제