singleflight

package
v1.2.12 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 2, 2024 License: Apache-2.0 Imports: 1 Imported by: 1

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Group

type Group struct {
	// import "golang.org/x/sync/singleflight"
	singleflight.Group
}

type SingleFlight

type SingleFlight interface {
	// Do 同步调用单飞
	Do(key string, fn func() (interface{}, error)) (v interface{}, err error, shared bool)

	// DoChan 异步调用单飞
	DoChan(key string, fn func() (interface{}, error)) <-chan singleflight.Result

	// Forget 可以取消已经下发未执行的任务
	Forget(key string)
}

SingleFlight Merge back to source

func NewSingleFlight

func NewSingleFlight() SingleFlight

NewSingleFlight 实例化

Example

ExampleNewSingleFlight

package main

// getResources 一般用于去数据库去获取数据
func getResources() (interface{}, error) {
	return "test", nil
}

// cache 填充到 缓存中的数据
func cache(v interface{}) {
	return
}

// ExampleNewSingleFlight
func main() {
	singleFlight := NewSingleFlight()

	// 如果在key相同的情况下, 同一时间只有一个 func 可以去执行,其他的等待
	// 多用于缓存失效后,构造缓存,缓解服务器压力

	// 同步:
	v, err, _ := singleFlight.Do("test1", func() (interface{}, error) {
		// todo 这里去获取资源
		return getResources()
	})
	if err != nil {
		// todo 处理错误
	}
	// v 就是获取到的资源
	cache(v)

	// 异步:
	ch := singleFlight.DoChan("test2", func() (interface{}, error) {
		// todo 这里去获取资源
		return getResources()
	})

	result := <-ch
	if result.Err != nil {
		// todo 处理错误
	}
	cache(result.Val)

	// 尽力取消
	singleFlight.Forget("test2")
}
Output:

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL