Gin 中使用 base64Captcha 生成圖形驗證碼分布式架構-redis方案
base64Captcha 的資料存儲到 Redis 中
redis位址:github.com/go-redis/redis/v8
go get -u github.com/go-redis/redis/v8
連接配接redis: redisCore.go
package models
import (
"context"
"github.com/go-redis/redis/v8"
)
//全局定義
var (
RedisDb *redis.Client
)
//建立 redis 連結
func init() {
var ctx = context.Background()
RedisDb = redis.NewClient(&redis.Options{
Addr: "111.229.91.20:6379",
Password: "chengqiang", // no password set
DB: 0, // use default DB
})
_, err := RedisDb.Ping(ctx).Result()
if err != nil {
//連接配接失敗
println(err)
} }
配置用于存驗證碼的redis倉庫:redisStore.go
package models
import (
"context"
"fmt"
"time"
)
var ctx = context.Background()
const CAPTCHA = "captcha:"
type RedisStore struct {
}
//實作設定captcha的方法
func (r RedisStore) Set(id string, value string) error {
key := CAPTCHA + id
//time.Minute*2:有效時間2分鐘
err := RedisDb.Set(ctx, key, value, time.Minute*2).Err()
return err
}
//實作擷取captcha的方法
func (r RedisStore) Get(id string, clear bool) string {
key := CAPTCHA + id
val, err := RedisDb.Get(ctx, key).Result()
if err != nil {
fmt.Println(err)
return ""
}
if clear {
//clear為true,驗證通過,删除這個驗證碼
err := RedisDb.Del(ctx, key).Err()
if err != nil {
fmt.Println(err)
return ""
}
}
return val
}
//實作驗證captcha的方法
func (r RedisStore) Verify(id, answer string, clear bool) bool {
v := RedisStore{}.Get(id, clear)
//fmt.Println("key:"+id+";value:"+v+";answer:"+answer)
return v == answer
}
//配置RedisStore RedisStore實作base64Captcha.Store的接口
var store base64Captcha.Store = RedisStore{}