天天看点

golang常用代码块

目录

1. 格式化日期

2. 随机数

3. redis的MGet

4. 定时任务

5. 多线程

6. sort.Slice排序

7. 任意类型 interface{}

8. init函数

1. 格式化日期

//年月日时分秒
time.Now().Format("20060102150405")
           
//简单日期,如2019-06-06
date := time.Now().Format("2006-01-02")
           

2. 随机数

import "math/rand"

rand.Seed(time.Now().UnixNano()) //用时间做种子,可以保证每次运行结果不一样
index := rand.Intn(10)//取0-9之前随机数
           

3. redis的MGet

func (h *ChapterPusher) GetChapterBookFromRedis(userInfo []*core.UserInfo, redisName string) (ChapterPushMap, error) {
	redisClient, ok := client.Clientmanager.GetRedisClient(redisName)
	if !ok {
		log.Errorf("get %s redis client error", redisName)
		return nil, fmt.Errorf("get %s redis client error", redisName)
	}

	chapterPushMap := make(map[string]*ChapterPushInfo)
	key := make([]interface{}, 0)

	for i := 0; i < len(userInfo); i++ {
		key = append(key, userInfo[i].Uid)
		if len(key) == REDIS_MGET_COUNT {//可以设定REDIS_MGET_COUNT=1000,批量MGet
			data, err := redisClient.MGet(key)
			if err != nil {
				log.Errorf("data Mget Error:%v", key)
				continue
			}
			result, ok := data.([]interface{})
			if !ok {
				log.Errorf("result Error:%v", result)
				continue
			}
			if len(key) != len(result) {
				log.Errorf("len is not equal")
				continue
			}
			for index, value := range result {
				valueByte, ok1 := value.([]byte)
				if ok1 {
					chapterPushInfo := &ChapterPushInfo{}
					err := json.Unmarshal(valueByte, chapterPushInfo)
					if err != nil {
						log.Errorf("Unmarshal error:%v", err)
						continue
					}
					uid := key[index].(string)
					if len(uid) == 0 {
						continue
					}
					chapterPushMap[uid] = chapterPushInfo
				}
			}
			key = key[0:0] //清空
		}
	}

	if len(key) != 0 {
		data, err := redisClient.MGet(key)
		if err != nil {
			log.Errorf("data Mget Error:%v", key)
			return chapterPushMap, nil
		}
		result, ok := data.([]interface{})
		if !ok {
			log.Errorf("result Error:%v", result)
			return chapterPushMap, nil
		}
		if len(key) != len(result) {
			log.Errorf("len is not equal")
			return chapterPushMap, nil
		}

		for index, value := range result {
			valueByte, ok1 := value.([]byte)
			if ok1 {
				chapterPushInfo := &ChapterPushInfo{}
				err := json.Unmarshal(valueByte, chapterPushInfo)
				if err != nil {
					log.Errorf("Unmarshal error:%v", err)
					continue
				}

				uid := key[index].(string)
				if len(uid) == 0 {
					continue
				}
				chapterPushMap[uid] = chapterPushInfo
			}
		}
	}
	return chapterPushMap, nil
}
           

4. 定时任务

cron

"github.com/robfig/cron"

5. 多线程

chBuf := make(chan string, 5000)
var wg sync.WaitGroup

//起一个线程,读取数据到chan
wg.Add(1)	
go func() {
	for _, user := range freqUser {
		chBuf <- user.Uid
	}

	close(chBuf) //关闭chan
	wg.Done()

}()

//起100个线程,从chan中读数据,用于处理
for i := 0; i < 100; i++ {
	wg.Add(1)
	go func() {
		for {
			if uid, ok := <-chBuf; ok {
				fm.Printf("uid = %s\n", uid)
					
			} else {//通道已经空了,并且已被关闭了
				break
			}
		}
		wg.Done()
	}()
}

wg.Wait()
           

6. sort.Slice排序

import "sort"

type pair struct {
    doc int
    score float64
}

myPair := make([]pair, 0)
myPair = append(myPair, pair{1, 1.0})
myPair = append(myPair, pair{3, 3.0})
myPair = append(myPair, pair{2, 2.0})

sort.Slice(myPair, func(i, j int) bool {
    return myPair[i].score > myPair[j].score
})
           

7. 任意类型 interface{}

//example 1
var name interface{} = "zdchu"
if myName, ok := name.(string); ok {
    fmt.Printf("name = %s\n", myName)
}


//example 2
var name interface{} = "zdchu"
switch v := name.(type) {
case int:
    fmt.Printf("int: %d\n", v)
case string:
    fmt.Printf("string: %s\n", v)
}
           

8. init函数

  • 在golang中import 包A的时候,会自动隐式的调用该包A的init()函数(i字母小写)。
  • 调用顺序:如果该包A又import了别的包B,会优先调用包B的init()函数,最后才调用main包的init()函数。
  • 一个包的init()函数可以定义多个,每个都会被调用,调用的顺序按文件名排序。

9. select

var c <-chan int
select{
    case <- c:
    case <- time.After(1*time.Second) //1s后默认执行
        fmt.Println("Time out")
}