利用redis的原子性和string類型數據的incr函數,實現一個簡易的ID生成服務,封裝為函數。
// 生成唯一ID
func generateID() (id int64, err error) {
rdb := getRedisConn()
// 定義一個短網址的,用來保證唯一的key
key := "dwzid"
exists, err := rdb.Exists(ctx, key).Result()
if err != nil {
return 0, err
}
if exists == 0 {
// Key does not exist 設置string類型鍵值
err = rdb.Set(ctx, key, "10000000000000000", 0).Err()
if err != nil {
return 0, err
}
// 獲取并打印出剛才設置的值
valstr, err := rdb.Get(ctx, key).Result()
if err != nil {
return 0, err
}
id, err = strconv.ParseInt(valstr, 10, 64)
if err != nil {
return 0, err
}
return id, nil
}
// Key exists 使用INCR命令
id, err = rdb.Incr(ctx, key).Result()
if err != nil {
return 0, err
}
return id, nil
}
封裝redis連接器
// 獲取Redis連接
func getRedisConn() *redis.Client {
rdb := redis.NewClient(&redis.Options{
Addr: "127.0.0.1:6379", // Redis地址
Password: "", // Redis密碼,如果沒有則為空字符串
DB: 0, // 使用默認DB
})
return rdb
}