Catena (时序存储引擎)中有一个函数的实现备受争议,它从 map 中根据指定的 name 获取一个 metricSource.每一次插入操作都会至少调用一次这个函数,现实场景中该函数调用更是频繁,并且是跨多个协程的,因此我们必须要考虑同步. 该函数从 map[string]*metricSource 中根据指定的 name 获取一个指向 metricSource 的指针,如果获取不到则创建一个并返回.其中要注意的关键点是我们只会对这个 map 进行插入操作. 简单实现如下:(为节省篇幅,省…
服务端代码示例: package main import ( "encoding/json" "fmt" "io/ioutil" "log" "net/http" "strings" ) type User struct { Name string `json:"name"` Age int `json:"age"` } func index(w…
1. 源码阅读 整个包实现原理基于令牌桶算法:随时间以 1/r 个令牌的速度向容积为 b 个令牌的桶中添加令牌,有请求就取走令牌,若令牌不足则不执行请求或者等待 Allow 方法的调用链:lim.Allow() bool → lim.AllowN(time.Now(), 1) → lim.reserveN(now, n, 0).ok,因此 reserveN 方法的实现很关键 // Allow is shorthand for AllowN(time.Now(), 1). func (lim *L…
golang垃圾回收 & 性能调优 参考资料: 如何监控 golang 程序的垃圾回收_Go语言_第七城市 golang的垃圾回收(GC)机制 - 两只羊的博客 - 博客频道 - CSDN.NET 说说Golang的使用心得 - 文章 - 伯乐在线 分析Golang垃圾回收机制-Read Go - GC | Go语言中文网 | Golang中文社区 | Golang中国 goroutine会不会对垃圾回收造成压力? - Golang中国 Go1.6与JVM CMS的垃圾回收对比 - 王鸿飞的专栏…
最佳实践 1 包管理 1.1 使用包管理对Golang项目进行管理,如:godep/vendor等工具 1.2 main/init函数使用,init函数参考python 1.2.1 main->import->const->var->init 1.2.2 同一个package属于一个作用域,所以不要重复定义变量等 1.3 万能的type 1.3.1 type ages int type money float32 type months map[string]int 定义新类型 1…
直接上代码: package main import ( "fmt" "runtime" "strconv" "sync" ) func say(str string) { ; i < ; i++ { runtime.Gosched() fmt.Println(str) } } func sayStat(str string, ch chan int64) { ; i < ; i++ { runtime.Gosch…
参考资料: http://studygolang.com/articles/7994--Defer函数调用参数的求值 golang的闭包和普通函数调用区别:http://studygolang.com/articles/356 结论: 闭包中参数是其地址 闭包中参数的确定是在声明时求值,而不是在调用时求值…
代码示例: package main import ( "fmt" "time" "golang.org/x/net/context" ) func main() { // ctx, cancelFunc := context.WithDeadline(context.Background(), time.Now().Add(time.Second*5)) ctx, cancelFunc := context.WithTimeout(contex…
apt-get install gcc-mingw-w64 env CGO_ENABLED= GOOS=windows GOARCH=amd64 CC=x86_64-w64-mingw32-gcc go build -o ./app/app.exe ./app/main.go env CGO_ENABLED= GOOS=windows GOARCH= CC=i686-w64-mingw32-gcc go build -o ./app/app.exe ./app/main.go Gox 是一个简单…
虽然golang是用C实现的,并且被称为下一代的C语言,但是golang跟C的差别还是很大的.它定义了一套很丰富的数据类型及数据结构,这些类型和结构或者是直接映射为C的数据类型,或者是用C struct来实现.了解golang的数据类型和数据结构的底层实现,将有助于我们更好的理解golang并写出质量更好的代码. 基础类型 源码在:$GOROOT/src/pkg/runtime/runtime.h .我们先来看下基础类型: ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1…