当缓存被击穿,DB不被压垮的一个解法

简介

这一切都源于一个大接口的优化,当并发升高,很多缓存有可能同时失效时,如何防止DB被打挂,尽可能的保护?重复的请求,重复的资源,如果节约成本?
这一切,有一个解法 -- singleflight

结构体

// call is an in-flight or completed singleflight.Do call
// call 表示一个正在执行的或已完成的函数调用,存储调用的接口、报错一些标记等等,
type call struct {
    // 可以看到,singleflight实现中用到了WaitGroup
	wg sync.WaitGroup

	// These fields are written once before the WaitGroup is done
	// and are only read after the WaitGroup is done.
    // 记录结果,在WaitGroup完成之前,只会写入一次,重点在此了
	val interface{}
	err error

	// forgotten indicates whether Forget was called with this call's key
	// while the call was still in flight.
    // 用来标识执行完成之后结果立马删除还是保留在singleflight中
	forgotten bool

	// These fields are read and written with the singleflight
	// mutex held before the WaitGroup is done, and are read but
	// not written after the WaitGroup is done.
    // 这个字段记录执行次数,更新时机是发起请求,waitGroup执行完成‘之前’
	dups  int
    // 用来记录DoChan中需要返回的数据
	chans []chan<- Result
}

// Group represents a class of work and forms a namespace in
// which units of work can be executed with duplicate suppression.
// 用来记录已经存在的对某key的请求和对应的实际请求函数(call)的映射
type Group struct {
	mu sync.Mutex       // protects m 加锁保护m
	m  map[string]*call // lazily initialized  懒加载
}

// Result holds the results of Do, so they can be passed
// on a channel.
// 记录结果,结果值Val,结果报错Err,结果是实际请求还是分享的返回
type Result struct {
	Val    interface{}
	Err    error
	Shared bool
}

方法

Do

// Do executes and returns the results of the given function, making
// sure that only one execution is in-flight for a given key at a
// time. If a duplicate comes in, the duplicate caller waits for the
// original to complete and receives the same results.
// The return value shared indicates whether v was given to multiple callers.
// Do执行并返回给定函数的结果,确保在给定时间仅对给定键进行一次执行。
// 如果出现重复,则重复的调用者将等待原始请求接收到相同的结果。
// 共享的返回值指示是否将v分配给多个调用者。
func (g *Group) Do(key string, fn func() (interface{}, error)) (v interface{}, err error, shared bool) {
    // 加锁,主要防止请求重复记录,并非加锁去做请求
	g.mu.Lock()
	if g.m == nil {
		g.m = make(map[string]*call)
	}
    // 校验是否已经完成请求,有则直接返回,shared肯定为true
	if c, ok := g.m[key]; ok {
		c.dups++
		g.mu.Unlock()
		c.wg.Wait()
		return c.val, c.err, true
	}
    // 校验是新的请求,waitGroup加1,存储,解锁
    // 注意,只有真正发起请求时候,才会执行waitGroup加1
	c := new(call)
	c.wg.Add(1)
	g.m[key] = c
	g.mu.Unlock()
    // 实际去请求,返回结果,此时
	g.doCall(c, key, fn)
    // 此时dups应该是恒定为0的?没想明白为什么需要判断,手动执行过Forget时?
	return c.val, c.err, c.dups > 0
}

DoChan

// DoChan is like Do but returns a channel that will receive the
// results when they are ready.
// 整体上与Do函数很类似,只是返回结果变为了chan
func (g *Group) DoChan(key string, fn func() (interface{}, error)) <-chan Result {
	ch := make(chan Result, 1)
	g.mu.Lock()
	if g.m == nil {
		g.m = make(map[string]*call)
	}
	if c, ok := g.m[key]; ok {
		c.dups++
		c.chans = append(c.chans, ch)
		g.mu.Unlock()
		return ch
	}
	c := &call{chans: []chan<- Result{ch}}
	c.wg.Add(1)
	g.m[key] = c
	g.mu.Unlock()

	go g.doCall(c, key, fn)

	return ch
}

doCall

// doCall handles the single call for a key.
// 实际执行函数
func (g *Group) doCall(c *call, key string, fn func() (interface{}, error)) {
	c.val, c.err = fn()
	c.wg.Done()
    // 请求完结果,置好waitGroup状态 Done,加锁开始处理后续逻辑
	g.mu.Lock()
    // 默认forgotten为false,会去删除请求好的状态,所以单飞只控制了同一时间相同请求
	if !c.forgotten {
		delete(g.m, key)
	}
    // 将chans中的结果发出去
	for _, ch := range c.chans {
		ch <- Result{c.val, c.err, c.dups > 0}
	}
	g.mu.Unlock()
}

Forget

// Forget tells the singleflight to forget about a key.  Future calls
// to Do for this key will call the function rather than waiting for
// an earlier call to complete.
func (g *Group) Forget(key string) {
	g.mu.Lock()
    // 防止重复删除
	if c, ok := g.m[key]; ok {
		c.forgotten = true
	}
    // 删除后,同样的请求,会同时去真实的发起请求
	delete(g.m, key)
	g.mu.Unlock()
}

总结

并发是一个双刃剑,节约了时间,但是也带来了很多的问题,不断学习,不断进步,自己要学习的还有很多,共勉!💪💪
希望能用好并发这个工具,解决更多的问题。

引用

深入理解singleflight
源码分析-singleflight
singleflight源码注释
曹大golang笔记 - sync包
singleflight 防缓存击穿 使用及原理