修复key缓存错误的问题

1. 修复连接默认数据库错误的问题。
2. 根据errcode存在且不为0判断为失败,否则为成功。而errmsg仅作参考,后续可能会有变动,因此不可作为是否调用成功的判据。
3. 修复判断查询数据库结果的逻辑错误。
4. 修复key缓存重复写入的问题。
This commit is contained in:
q629988171 2021-06-30 21:35:27 +08:00 committed by GitHub
parent dc627cbf38
commit e1d340d410
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 28 additions and 11 deletions

View File

@ -4,9 +4,12 @@ import (
"bytes" "bytes"
"context" "context"
"encoding/json" "encoding/json"
"fmt"
"io/ioutil" "io/ioutil"
"log" "log"
"net/http" "net/http"
"reflect"
"time" "time"
"github.com/go-redis/redis/v8" "github.com/go-redis/redis/v8"
@ -51,7 +54,7 @@ func redis_client() *redis.Client {
rdb := redis.NewClient(&redis.Options{ rdb := redis.NewClient(&redis.Options{
Addr: REDIS_ADDR, Addr: REDIS_ADDR,
Password: "", // no password set Password: "", // no password set
DB: 8, // use default DB DB: 0, // use default DB
}) })
return rdb return rdb
} }
@ -92,15 +95,23 @@ func post_msg(text_msg, msg_type, post_url string) string {
return string(body) return string(body)
} }
func IsZero(v interface{}) (bool, error) {
t := reflect.TypeOf(v)
if !t.Comparable() {
return false, fmt.Errorf("type is not comparable: %v", t)
}
return v == reflect.Zero(t).Interface(), nil
}
func main() { func main() {
var access_token string var access_token string
if redis_stat == "ON" { if redis_stat == "ON" {
log.Println("从redis获取token")
rdb := redis_client() rdb := redis_client()
vals, err := rdb.Get(ctx, "access_token").Result() vals, err := rdb.Get(ctx, "access_token").Result()
if err != redis.Nil { if err == redis.Nil {
log.Println(err) log.Println("access_token does not exist")
} }
log.Println("从redis获取token")
access_token = string(vals) access_token = string(vals)
} }
if access_token == "" { if access_token == "" {
@ -119,13 +130,19 @@ func main() {
log.Println(post_status) log.Println(post_status)
post_response := praser_json(string(post_status)) post_response := praser_json(string(post_status))
log.Println(post_response) log.Println(post_response)
if post_response["errmsg"] == "ok" && redis_stat == "ON" { errcode := post_response["errcode"]
log.Println("pre to set redis key") ok, err := IsZero(errcode)
rdb := redis_client() if err != nil {
set, err := rdb.SetEX(ctx, "access_token", access_token, 7000*time.Second).Result() fmt.Printf("%v", err)
log.Println(set) } else {
if err != redis.Nil { if ok && redis_stat == "ON" {
log.Println(err) log.Println("pre to set redis key")
rdb := redis_client()
set, err := rdb.SetNX(ctx, "access_token", access_token, 7000*time.Second).Result()
log.Println(set)
if err != nil {
log.Println(err)
}
} }
} }
} }