Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use context context Management in Go language

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "how to use the context context management of the Go language". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn how to use the context context management of the Go language.

What is the function of context?

Context is mainly used to transmit context information between goroutine, including: cancellation signal, timeout, cutoff time, KMurv and so on.

Go is often used to write background services, and it usually takes only a few lines of code to build a http server.

In Go's server, usually each request initiates several goroutine to work at the same time: some go to the database to get data, some call downstream interfaces to get relevant data.

These goroutine need to share the basic data of the request, such as the token logged in, the maximum timeout for processing the request (if this value is exceeded and the data is returned, the requester cannot receive it because of the timeout), and so on. When the request is cancelled or the processing time is too long, it is possible that the user has closed the browser or has exceeded the timeout specified by the requestor, and the requestor directly abandons the result of the request. At this point, all goroutine that are working on this request need to exit quickly because their "work results" are no longer needed. After all the associated goroutine exits, the system can recycle the related resources.

In Go, we can't kill the co-program directly, and the shutdown of the co-program is usually controlled by channel+select. But in some scenarios, such as processing a request, there are many cooperators that are interrelated: some global variables need to be shared, a common deadline, and so on, and can be turned off at the same time. It will be troublesome to use channel+select again, and this can be achieved through context.

In a word: context is used to solve the functions of exit notification and metadata transfer between goroutine.

Context is very convenient to use. A function to create the root node context is provided in the source code:

Func Background () Context

Background is an empty context that cannot be canceled, has no value, and has no timeout. With the root node context, four more functions are provided to create the child node context:

Func WithCancel (parent Context) (ctx Context, cancel CancelFunc) func WithDeadline (parent Context, deadline time.Time) (Context, CancelFunc) func WithTimeout (parent Context, timeout time.Duration) (Context, CancelFunc) func WithValue (parent Context, key, val interface {}) Context

Context is passed between function passes. You just need to call the cancel function at the appropriate time to send a cancel signal to the goroutines or call the Value function to fetch the value in the context.

Do not tuck Context into the structure. The Context type is directly used as the first argument to the function, and is generally named ctx.

Do not pass a nil context to the function. If you really don't know what to pass, the standard library has a context:todo ready for you.

Instead of stuffing context with types that should be function arguments, context should store some common data. For example: login session, cookie and so on.

The same context may be passed to multiple goroutine, and don't worry, context is concurrently secure.

Transfer shared data

For Web server development, you often want to string together the entire process of processing a request, which is very dependent on the variables of Thread Local (which can be understood as unique to a single Go), but there is no such concept in the Go language, so you need to pass context when the function is called.

Package mainimport ("context" fmt ") func main () {ctx: = context.Background () process (ctx) ctx = context.WithValue (ctx," traceId "," qcrao-2019 ") process (ctx)} func process (ctx context.Context) {traceId, ok: = ctx.Value (" traceId "). (string) if ok {fmt.Printf (" process over. Trace_id=%s\ n ", traceId)} else {fmt.Printf (" process over. No trace_id\ n ")}}

Running result:

Process over. No trace_id

Process over. Trace_id=qcrao-2019

When the process function is called for the first time, ctx is an empty context, so the traceId cannot be fetched naturally. The second time, a context is created through the WithValue function, and the key of traceId is assigned, and the passed value value can be taken out naturally.

Cancel goroutine

Let's imagine a scenario: open the order page of takeout, and the map shows the location of the takeout guy, and it is updated once a second. After the app initiates a request for websocket connection (which may be polling in reality) to the backend, the backend starts a cooperative program, calculates the location of the elder brother every 1 second, and sends it to the end. If the user exits this page, the background needs to "cancel" the process, exit goroutine, and the system reclaims resources.

Func Perform () {for {calculatePos () sendResult () time.Sleep (time.Second)}}

If you need to implement the "cancel" function, and without knowing the context function, you may do this: add a pointer-type bool variable to the function, determine at the beginning of the for statement that the bool variable is sent from true to false, and if you change, exit the loop.

The simple approach given above can achieve the desired effect, no problem, but not elegant, and once the number of collaborators is large, and all kinds of nesting, it will be very troublesome. An elegant approach naturally requires the use of context.

Func Perform (ctx context.Context) {for {calculatePos () sendResult () select {case

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report