go context专题(四)- context 最佳实践和相关争议

xiaoxiao2021-02-28  85

 

context最佳实践

Do not store Contexts inside a struct type; instead, pass a Context explicitly to each function that needs it. The Context should be the first parameter, typically named ctx;

不要把Context存在一个结构体当中,显式地传入函数。Context变量需要作为第一个参数使用,一般命名为ctx;

Do not pass a nil Context, even if a function permits it. Pass context.TODO if you are unsure about which Context to use;

即使方法允许,也不要传入一个nil的Context,如果你不确定你要用什么Context的时候传一个context.TODO

Use context Values only for request-scoped data that transits processes and APIs, not for passing optional parameters to functions;

使用context的Value相关方法只应该用于在程序和接口中传递的和请求相关的元数据,不要用它来传递一些可选的参数

The same Context may be passed to functions running in different goroutines; Contexts are safe for simultaneous use by multiple goroutines;

同样的Context可以用来传递到不同的goroutine中,Context在多个goroutine中是安全的

争议--该不该使用context传递数据

首先要理解Context只是一种辅助机制,其是一种补偿机制,其使用不应该影响主业务流程;使用其辅助传递一些元信息,或者通知进行资源的回收;使用Context不能影响到你的正常的业务流程,程序不要期待在Context传递一些必须的参数等,没有这些参数,程序应该也能正常的工作。

在Context中传值的坏处: 1.传递的都是interface{}类型的值,编译器不能进行严格的类型校验; 2.从interface{}到具体类型需要使用类型断言和接口查询,这个有一定的运行期开销,有性能损失; 3.值在传递过程中有可能被覆盖,而不易被发现; 4.这种传递信息非常不简明,清晰,而是晦涩隐含的;不能通过代码或者文档一眼看到传递什么;

context可以传递什么

可以传递什么信息: 日志信息 调试信息 不影响正常行为的其他信息

参见 https://medium.com/@cep21/how-to-correctly-use-context-context-in-go-1-7-8f2c0fafdf39

转载请注明原文地址: https://www.6miu.com/read-52728.html

最新回复(0)