go语言提供非常方便的创建轻量级的协程goroutine来并发处理任务,但是 协程过多影响程序性能,所以,这时goroutine池就登场了。本文简要介绍ants goroutine 池的基本的使用方法。

简介

ants是一个高性能的 goroutine 池,实现了对大规模 goroutine 的调度管理、goroutine 复用,允许使用者在开发并发程序的时候限制 goroutine 数量,复用资源,达到更高效执行任务的效果。 ants就是一个很多大厂广泛使用的goroute池。

官网地址

https://github.com/panjf2000/ants

功能

  • 自动调度海量的 goroutines,复用 goroutines
  • 定期清理过期的 goroutines,进一步节省资源
  • 提供了大量有用的接口:任务提交、获取运行中的 goroutine 数量、动态调整 Pool 大小、释放 Pool、重启 Pool
  • 优雅处理 panic,防止程序崩溃
  • 资源复用,极大节省内存使用量;在大规模批量并发任务场景下比原生 goroutine 并发具有更高的性能
  • 非阻塞机制

quick start

使用 ants v1 版本:

go get -u github.com/panjf2000/ants

使用 ants v2 版本 (开启 GO111MODULE=on):

go get -u github.com/panjf2000/ants/v2

接下来看一下官方demo:实现一个计算大量整数和的程序

NewPool

NewPool生成ants池实例。

package main

import (
	"fmt"
	"sync"
	"time"

	"github.com/panjf2000/ants/v2"
)

var sum int32

func demoFunc() {
	time.Sleep(10 * time.Millisecond)
	fmt.Println("Hello World!")
}

func main() {
	defer ants.Release()

	runTimes := 1000

	//使用公共池。
	var wg sync.WaitGroup
	syncCalculateSum := func() {
		demoFunc()
		wg.Done()
	}
	for i := 0; i < runTimes; i++ {
		wg.Add(1)
		_ = ants.Submit(syncCalculateSum)
	}
	wg.Wait()
	fmt.Printf("running goroutines: %d\n", ants.Running())
    fmt.Printf("finish all tasks.\n")
 }

其中:

生成一个具有特定函数的ants池实例

  • NewPool(size int, options …Option) (*PoolWithFunc, error)

args.size 即池容量,即池中最多有 10 个 goroutine。 arg.Option 定制化 goroutine pool.

  • p.Submit向此池提交任务。
  • ants.Release关闭此池并释放工作队列。
  • defaultAntsPool 导入ants时初始化实例池。

NewPoolWithFunc

package main

import (
	"fmt"
	"github.com/panjf2000/ants/v2"
	"sync"
	"sync/atomic"
)

var sum int32

func myFunc(i interface{}) {
	n := i.(int32)
	atomic.AddInt32(&sum, n)
	fmt.Printf("run with %d\n", n)
}

func main() {
	defer ants.Release()
	runTimes := 1000
	var wg sync.WaitGroup
	//使用带有函数的池
//设置goroutine池的容量为10,过期时间为1秒。
	p, _ := ants.NewPoolWithFunc(10, func(i interface{}) {
		myFunc(i)
		wg.Done()
	})
	defer p.Release()
	//逐个提交任务。
	for i := 0; i < runTimes; i++ {
		wg.Add(1)
		_ = p.Invoke(int32(i))
	}
	wg.Wait()
	fmt.Printf("running goroutines: %d\n", p.Running())
	fmt.Printf("finish all tasks, result is %d\n", sum)
}

OutPut:

run with 1
run with 5
run with 11
run with 12
run with 13
run with 14
run with 7
...
run with 789
run with 809
running goroutines: 10
finish all tasks, result is 499500

其中:

生成一个具有特定函数的ants池实例

  • NewPoolWithFunc(size int, pf func(interface{}), options …Option) (*PoolWithFunc, error)

args.pf 即为执行任务的函数

优雅处理 panic

测试一些当任务触发panic的情况

func myFunc(i interface{}) {
	n := i.(int32)
	atomic.AddInt32(&sum, n)
	if n%2 == 0 {
		panic(any(fmt.Sprintf("panic from task:%d", n)))
	}
	fmt.Printf("run with %d\n", n)
}

output:

run with 3
run with 13
...
run with 999
2022/10/21 21:41:05 worker with func exits from a panic: panic from task:6
2022/10/21 21:41:05 worker with func exits from a panic: panic from task:0
2022/10/21 21:41:07 worker with func exits from panic: goroutine 14 [running]:

可以看到,main routine 没有因此受影响。

Options

// Options包含实例化ants池时将应用的所有选项。
type Options struct {
	// ExpiryDuration is a period for the scavenger goroutine to clean up those expired workers,
	// the scavenger scans all workers every `ExpiryDuration` and clean up those workers that haven't been
	// used for more than `ExpiryDuration`.
	ExpiryDuration time.Duration

	// PreAlloc indicates whether to make memory pre-allocation when initializing Pool.
	PreAlloc bool

	// Max number of goroutine blocking on pool.Submit.
	// 0 (default value) means no such limit.
	MaxBlockingTasks int

	// When Nonblocking is true, Pool.Submit will never be blocked.
	// ErrPoolOverload will be returned when Pool.Submit cannot be done at once.
	// When Nonblocking is true, MaxBlockingTasks is inoperative.
	Nonblocking bool

	// PanicHandler is used to handle panics from each worker goroutine.
	// if nil, panics will be thrown out again from worker goroutines.
	PanicHandler func(interface{})

	// Logger is the customized logger for logging info, if it is not set,
	// default standard logger from log package is used.
	Logger Logger
}

比如 PanicHandler 遇到 panic会调用这里设置的处理函数,以上例中,我们遇到偶数会触发panic,修改NewPool函数

p, _ := ants.NewPoolWithFunc(10, func(i interface{}) {
		myFunc(i)
		wg.Done()
	}, ants.WithPanicHandler(func(i interface{}) {
		fmt.Printf("panic recover %v", i)
	}))

out:

panic recover panic from i:992run with 880
panic recover panic from i:880run with 972
panic recover panic from i:972run with 994
run with 991

还有更多关于 Benchmarks 性能报告,可参考https://github.com/panjf2000/ants

参考:

本文主要介绍 jinzhu/copier 的使用和常用场景

简介

在go后端项目开发中,内部rpc服务返回的字段跟api服务相差无几,一个个赋值比较费事儿。那么就需要Object、List、HashMap 等进行值拷贝。jinzhu/copier即提供了这些场景的支持。

copier 特性

  • 从方法复制到具有相同名称的字段
  • 从字段复制到具有相同名称的方法
  • 从一个切片复制到另一个切片
  • 从结构体复制到切片
  • 从map复制到map
  • 强制复制带有标记的字段
  • 忽略带有标记的字段
  • 深拷贝

Usage

Copy from struct

package main

import (
	"github.com/jinzhu/copier"
	"testing"
)

type User struct {
	Name         string
	Role         string
	Age          int32
	EmployeeCode int64 `copier:"EmployeeNum"` // specify field name

	// Explicitly ignored in the destination struct.
	Salary int
}

//目标结构体中的标签提供了copy指令。复制忽略
//或强制复制,如果字段没有被复制则惊慌或返回错误。
type Employee struct {
	//告诉copier。如果没有复制此字段,则复制到panic。
	Name string `copier:"must"`

	//告诉copier。 如果没有复制此字段,则返回错误。
	Age int32 `copier:"must,nopanic"`

	// 告诉copier。 显式忽略复制此字段。
	Salary int `copier:"-"`

	DoubleAge  int32
	EmployeeId int64 `copier:"EmployeeNum"` // 指定字段名
	SuperRole  string
}

func TestCopyStruct(t *testing.T) {
	var (
		user     = User{Name: "Jinzhu", Age: 18, Role: "Admin", Salary: 200000}
		employee = Employee{Salary: 150000}
	)
	copier.Copy(&employee, &user)
	t.Logf("%#v \n", employee)
}

output:

    copier_test.go:47: main.Employee{Name:"Jinzhu", Age:18, Salary:150000, DoubleAge:36, EmployeeId:0, SuperRole:"Super Admin"} 

Copy from slice to slice

func TestCopySlice(t *testing.T) {
	var (
		users     = []User{{Name: "Jinzhu", Age: 18, Role: "Admin", Salary: 100000}, {Name: "jinzhu 2", Age: 30, Role: "Dev", Salary: 60000}}
		employees = []Employee{}
	)
	employees = []Employee{}
	copier.Copy(&employees, &users)

	t.Logf("%#v \n", employees)
}`

output :

    copier_test.go:57: []main.Employee{main.Employee{Name:"Jinzhu", Age:18, Salary:0, DoubleAge:36, EmployeeId:0, SuperRole:"Super Admin"}, main.Employee{Name:"jinzhu 2", Age:30, Salary:0, DoubleAge:60, EmployeeId:0, SuperRole:"Super Dev"}} 

Copy from Map to Map

func TestCopyMap(t *testing.T) {
	// Copy map to map
	map1 := map[int]int{3: 6, 4: 8}
	map2 := map[int32]int8{}
	copier.Copy(&map2, map1)

	t.Logf("%#v \n", map2)
}

output :

    copier_test.go:66: map[int32]int8{3:6, 4:8} 

场景 1(rpc&api)

实际开发中,免不了服务间通讯,比较前文所说的场景,一个内部的rpc服务返回的参数和api服务差不多,那么就可以使用copier。

//伪代码如下
func ApiLogin(ctx context.Context,request *api.LoginRequest)(reply *api.LogingReply,err error)  {
	grpcClient := v1.NewGameGrpcClient(ctx)
	reply, err := client.Login(ctx, &grpc.api.LoginRequest{ 
					})
	user := api.LogingReply.User{}
 	copier.Copy(&user, reply.User())
return &api.LoginReply{
	User:user,
},err

场景 2 (model-object/aggregate)

实际开发中,不管是mvc\ddd 都会有从model到object/aggreate的repository,那么就可以使用copier。

func (r *UserRepo) Get(ctx context.Context, uid int64) (u User,err error) {
	model, err := db.User.Get(ctx, uid)
	if err != nil {
		return
	}
	obj:= User{}
	copy(&obj,model)
	return obj,nil
}

小结

copier提供不同类型之间相同的字段名,使用tag或者方法支持不同的字段名的赋值。减少一些重复的工作量,小巧实用。

参考

本文主要介绍 在go开发中 errors 的处理和第三方库 github.com/pkg/errors 的使用。

error interface

官方定义:

// The error built-in interface type is the conventional interface for
// representing an error condition, with the nil value representing no error.
type error interface {
	Error() string
}

常用的声明方式

//方式一
err1 := fmt.Errorf("io.EOF")
//方式二
err2 := errors.New("io.EOF")
//方式三: 实现interface
type err3 struct{
}
func (e err3) Error() string {
	return "err3"
}

go的错误常见是把错误层层传递,这样可能带来一些不友好的地方:

  • 错误判断,经过层次包裹的错误,使用层不好判断真实错误
  • 定位错误,error库过于简单,没有提供粗错误堆栈,不好定位问题

错误判断

常见错误的判断方式是:


type base struct{}

func (e base) Error() string {
	return "base error"
}

func wrapBase() error {
	return fmt.Errorf("wrapBase: %w", base{})
}

func TestErrors(t *testing.T) {
	t.Run("==", func(t *testing.T) {
		foo := &base{}
		bar := &base{}
		t.Log(foo)
		t.Log(bar)
		t.Log(foo == bar)
		assert.True(t, foo == bar)
	})
	t.Run("断言", func(t *testing.T) {
		var err error
		_, ok := err.(*base)
		assert.False(t, ok)
	})
	t.Run("Is", func(t *testing.T) {
		foo := base{}
		wrapFoo := wrapBase()
		assert.False(t, foo == wrapFoo)
		assert.True(t, errors.Is(wrapFoo, foo))
		assert.False(t, errors.Is(wrapFoo, &base{}))
	})
	t.Run("As", func(t *testing.T) {
		foo := base{}
		wrapFoo := wrapBase()
		assert.False(t, foo == wrapFoo)
		assert.True(t, errors.As(wrapFoo, &base{}))
	})
}

OutPut:

--- PASS: TestErrors (0.00s)
--- PASS: TestErrors/== (0.00s)
--- PASS: TestErrors/断言 (0.00s)
--- PASS: TestErrors/Is (0.00s)
 --- PASS: TestErrors/As (0.00s)
  • 当没有嵌套错误,可以使用 ==来判断;
  • 当有多层嵌套,可以使用 Is() :
    • //一个错误被认为匹配一个目标,如果它等于那个目标或如果它实现了一个方法Is(error) bool,使Is(target)返回true。
    • // As在err’s chain中找到第一个与target匹配的错误,如果找到,则设置指向错误值并返回true。否则,返回false

定位错误

常用的第三方库

github.com/pkg/errors/errors.go 提供了以下功能:

  • WithStack 包装堆栈
  • WithMessagef 包装异常
func TestWithStackCompare(t *testing.T) {
	t.Run("fmt.Errorf,无堆栈,不好定位", func(t *testing.T) {
		err1 := fmt.Errorf("io.EOF")
		fmt.Printf("err1: %+v", err1)
	})
	t.Run("errors ,无堆栈,不好定位", func(t *testing.T) {
		err2 := errors.New("io.EOF")
		fmt.Printf("err2: %+v", err2)
	})
	t.Run("pkgerrors,有堆栈,方便定位", func(t *testing.T) {
		err3 := pkgerrors.WithStack(io.EOF)
		fmt.Printf("err3: %+v", err3)
	})

}

OutPut:

=== RUN   TestWithStackCompare
=== RUN   TestWithStackCompare/fmt.Errorf,无堆栈,不好定位
err1: io.EOF=== RUN   TestWithStackCompare/errors_,无堆栈,不好定位
err2: io.EOF=== RUN   TestWithStackCompare/pkgerrors,有堆栈,便以定位
err3: EOF
tkingo.vip/egs/goerrors-demo.TestWithStackCompare.func3
	$ workspace/goerrors-demo/errors_test.go:113
testing.tRunner
	$ workspace/Go/src/testing/testing.go:1439
runtime.goexit

func TestWithMessagef(t *testing.T) {
	tests := []struct {
		err     error
		message string
		want    string
	}{
		{io.EOF, "read error", "read error: EOF"},
		{pkgerrors.WithMessagef(io.EOF, "read error without format specifier"), "client error", "client error: read error without format specifier: EOF"},
		{pkgerrors.WithMessagef(io.EOF, "read error with %d format specifier", 1), "client error", "client error: read error with 1 format specifier: EOF"},
	}

	for _, tt := range tests {
		got := pkgerrors.WithMessagef(tt.err, tt.message).Error()
		if got != tt.want {
			t.Errorf("WithMessage(%v, %q): got: %q, want %q", tt.err, tt.message, got, tt.want)
		}
	}
}

总结

pkg errors 应该能够支持错误堆栈、不同的打印格式很好的补充了go errors 的一些短板

参考:

  • github.com/pkg/errors

本文主要介绍一个好用的时间工具库,主要功能:

  • 当前时间
  • 修改地区
  • 解析字符串 等

Usage


import "github.com/jinzhu/now"

time.Now() // 2013-11-18 17:51:49.123456789 Mon

now.BeginningOfMinute()        // 2013-11-18 17:51:00 Mon
now.BeginningOfHour()          // 2013-11-18 17:00:00 Mon
now.BeginningOfDay()           // 2013-11-18 00:00:00 Mon
now.BeginningOfWeek()          // 2013-11-17 00:00:00 Sun
now.BeginningOfMonth()         // 2013-11-01 00:00:00 Fri
now.BeginningOfQuarter()       // 2013-10-01 00:00:00 Tue
now.BeginningOfYear()          // 2013-01-01 00:00:00 Tue

now.EndOfMinute()              // 2013-11-18 17:51:59.999999999 Mon
now.EndOfHour()                // 2013-11-18 17:59:59.999999999 Mon
now.EndOfDay()                 // 2013-11-18 23:59:59.999999999 Mon
now.EndOfWeek()                // 2013-11-23 23:59:59.999999999 Sat
now.EndOfMonth()               // 2013-11-30 23:59:59.999999999 Sat
now.EndOfQuarter()             // 2013-12-31 23:59:59.999999999 Tue
now.EndOfYear()                // 2013-12-31 23:59:59.999999999 Tue

now.WeekStartDay = time.Monday // Set Monday as first day, default is Sunday
now.EndOfWeek()                // 2013-11-24 23:59:59.999999999 Sun

修改地区

location, err := time.LoadLocation("Asia/Shanghai")

myConfig := &now.Config{
	WeekStartDay: time.Monday,
	TimeLocation: location,
	TimeFormats: []string{"2006-01-02 15:04:05"},
}

t := time.Date(2013, 11, 18, 17, 51, 49, 123456789, time.Now().Location()) // // 2013-11-18 17:51:49.123456789 Mon
myConfig.With(t).BeginningOfWeek()         // 2013-11-18 00:00:00 Mon

myConfig.Parse("2002-10-12 22:14:01")     // 2002-10-12 22:14:01
myConfig.Parse("2002-10-12 22:14")        // returns error 'can't parse string as time: 2002-10-12 22:14'

解析字符串

time.Now() // 2013-11-18 17:51:49.123456789 Mon

// Parse(string) (time.Time, error)
t, err := now.Parse("2017")                // 2017-01-01 00:00:00, nil
t, err := now.Parse("2017-10")             // 2017-10-01 00:00:00, nil
t, err := now.Parse("2017-10-13")          // 2017-10-13 00:00:00, nil
t, err := now.Parse("1999-12-12 12")       // 1999-12-12 12:00:00, nil
t, err := now.Parse("1999-12-12 12:20")    // 1999-12-12 12:20:00, nil
t, err := now.Parse("1999-12-12 12:20:21") // 1999-12-12 12:20:21, nil
t, err := now.Parse("10-13")               // 2013-10-13 00:00:00, nil
t, err := now.Parse("12:20")               // 2013-11-18 12:20:00, nil
t, err := now.Parse("12:20:13")            // 2013-11-18 12:20:13, nil
t, err := now.Parse("14")                  // 2013-11-18 14:00:00, nil
t, err := now.Parse("99:99")               // 2013-11-18 12:20:00, Can't parse string as time: 99:99`

参考

jefffff

Stay hungry. Stay Foolish COOL

Go backend developer

China Amoy