package Account import ( "Yunlot/conf" "Yunlot/logs" "Yunlot/models" "encoding/json" "fmt" "github.com/astaxie/beego/cache" _ "github.com/astaxie/beego/cache/redis" "github.com/beego/beego/v2/adapter/orm" _ "github.com/go-sql-driver/mysql" "time" ) type User struct { T_uuid string `orm:"size(100);pk"` T_user string `orm:"size(256);null"` // 用户名 T_pass string `orm:"size(256);null"` // 密码 T_hash string `orm:"size(256);null"` // hash T_State int `orm:"size(200);1"` // 1 正常 2 删除\禁用 CreateTime models.Time `orm:"column(create_time);type(timestamp);null;auto_now_add"` //auto_now 每次 model 保存时都会对时间自动更新 UpdateTime models.Time `orm:"column(update_time);type(timestamp);null;auto_now"` //auto_now_add 第一次保存时才设置时间 } type VCode struct { T_Code string } func (t *User) TableName() string { return "User" // 数据库名称 // ************** 替换 FormulaList ************** } var redis_User cache.Cache func init() { //注册模型 orm.RegisterModel(new(User)) config := fmt.Sprintf(`{"key":"%s","conn":"%s","dbNum":"%s","password":"%s"}`, "redis_User", conf.Redis_address, conf.Redis_dbNum, conf.Redis_password) var err error redis_User, err = cache.NewCache("redis", config) if err != nil || redis_User == nil { logs.Println(config) panic(any(err)) } } // ---------------- Redis ------------------- func (t *User) redis_Set() (err error) { //json序列化 str, err := json.Marshal(t) if err != nil { logs.PrintlnError("Redis_Set", err) return } err = redis_User.Put(t.T_uuid, str, 24*time.Hour) if err != nil { logs.Println("set key:", t.T_uuid, ",value:", str, err) } return } func (t *User) redis_Get(key string) (is bool) { if redis_User.IsExist(key) { //println("找到key:",key) v := redis_User.Get(key) if v == nil { return false } json.Unmarshal(v.([]byte), t) return true } //println("没有 找到key:",key) return false } func (t *User) redis_DelK() (err error) { err = redis_User.Delete(t.T_uuid) return } // ---------------- 方法 ------------------- // 获取 ById func (t *User) Read(T_uuid string) (r User, is bool) { if r.redis_Get(T_uuid) { return r, true } o := orm.NewOrm() r = User{T_uuid: T_uuid} err := o.Read(&r, "T_uuid") // o.Read(&r,"Tokey") 如果不是 主键 就得指定字段名 if err != nil { return r, false } r.redis_Set() // Redis 更新缓存 return r, true } // 添加 func (t *User) Add() (id int64, is bool) { o := orm.NewOrm() id, err := o.Insert(t) if err != nil { return 0, false } t.redis_Set() return id, true } // 修改 func (t *User) Update(cols ...string) bool { o := orm.NewOrm() if num, err := o.Update(&t, cols...); err == nil { fmt.Println("Number of records updated in database:", num) t.redis_Set() // Redis 更新缓存 return true } return false }