路由架构修改,定时任务修复

This commit is contained in:
yxh
2020-08-07 12:13:39 +08:00
parent 913184f09e
commit 7c85e49905
20 changed files with 831 additions and 229 deletions
+50
View File
@@ -0,0 +1,50 @@
package admin
import (
"gfast/app/model/admin/web_set"
"gfast/app/service/admin/web_set_service"
"gfast/library/response"
"github.com/gogf/gf/encoding/gjson"
"github.com/gogf/gf/errors/gerror"
"github.com/gogf/gf/frame/g"
"github.com/gogf/gf/net/ghttp"
"github.com/gogf/gf/util/gvalid"
)
type WebSet struct{}
func (c *WebSet) Update(r *ghttp.Request) {
if r.Method == "POST" {
var req *web_set.UpdateReq
err := r.Parse(&req)
if err != nil {
response.FailJson(true, r, err.(*gvalid.Error).FirstString())
}
err = web_set_service.UpdateSave(req)
if err != nil {
response.FailJson(true, r, err.Error())
}
response.SusJson(true, r, "更新成功!")
}
// 不是post提交的请求就到修改页面后查询出要修改的记录
id := r.GetInt("webId")
params, err := web_set_service.GetInfoByID(id)
if err != nil {
response.FailJson(true, r, err.Error())
}
response.SusJson(true, r, "ok", params)
}
// 查询站点信息
func (c *WebSet) GetInfo(r *ghttp.Request) {
res, err := web_set.Model.FindOne()
if err != nil {
g.Log().Error(err)
err = gerror.New("查询站点信息失败!")
response.FailJson(true, r, err.Error())
}
response.SusJson(true, r, "站点信息", g.Map{
"web_id": res.WebId,
"web_content": gjson.New(res.WebContent),
})
}
@@ -1,4 +1,4 @@
package admin
package common
import (
"gfast/library/response"
@@ -7,7 +7,7 @@ import (
"github.com/gogf/gf/net/ghttp"
)
type Public struct{}
type Captcha struct{}
// @Summary 获取验证码图片信息
// @Description 获取验证码图片信息
@@ -15,7 +15,7 @@ type Public struct{}
// @Success 0 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /system/public/verify [post]
// @Security
func (p *Public) Verify(r *ghttp.Request) {
func (p *Captcha) Img(r *ghttp.Request) {
idKeyC, base64stringC := service.GetVerifyImgString()
response.SusJson(true, r, "ok", g.MapStrStr{"idKeyC": idKeyC, "base64stringC": base64stringC})
}
+2 -2
View File
@@ -180,7 +180,7 @@ func JobStart(job *Entity) error {
rs := gcron.Search(job.InvokeTarget)
if rs == nil {
if job.MisfirePolicy == 1 {
task, err := gcron.Add(job.CronExpression, f.Run, job.InvokeTarget)
task, err := gcron.AddSingleton(job.CronExpression, f.Run, job.InvokeTarget)
if err != nil || task == nil {
return err
}
@@ -208,7 +208,7 @@ func JobStop(job *Entity) error {
}
rs := gcron.Search(job.InvokeTarget)
if rs != nil {
gcron.Stop(job.InvokeTarget)
gcron.Remove(job.InvokeTarget)
}
job.Status = 1
job.Update()
@@ -20,6 +20,7 @@ type Entity struct {
Status int `orm:"status" json:"status"` // 登录状态(0成功 1失败)
Msg string `orm:"msg" json:"msg"` // 提示消息
LoginTime int64 `orm:"login_time" json:"login_time"` // 访问时间
Module string `orm:"module" json:"module"` //登录模块
}
// OmitEmpty sets OPTION_OMITEMPTY option for the model, which automatically filers
+6 -3
View File
@@ -15,7 +15,7 @@ type ReqListSearch struct {
}
//获取在线用户列表
func GetOnlineListPage(req *ReqListSearch) (total, page int, list []*Entity, err error) {
func GetOnlineListPage(req *ReqListSearch, hasToken bool) (total, page int, list []*Entity, err error) {
page = req.PageNum
model := Model
if req.Ip != "" {
@@ -30,8 +30,11 @@ func GetOnlineListPage(req *ReqListSearch) (total, page int, list []*Entity, err
err = gerror.New("获取总行数失败")
return
}
list, err = model.FieldsEx("token").Page(page, req.PageSize).Order("create_time DESC").All()
if !hasToken {
list, err = model.FieldsEx("token").Page(page, req.PageSize).Order("create_time DESC").All()
} else {
list, err = model.Page(page, req.PageSize).Order("create_time DESC").All()
}
if err != nil {
g.Log().Error(err)
err = gerror.New("获取数据失败")
+40
View File
@@ -0,0 +1,40 @@
package web_set
import (
"github.com/gogf/gf/errors/gerror"
"github.com/gogf/gf/frame/g"
"github.com/gogf/gf/util/gconv"
)
// updateReq 用于存储页面更新(新增、修改)网址的信息
type UpdateReq struct {
WebContent g.Map `p:"webContent" v:"required#站点信息不能为空"` // 站点信息
}
// 更新站点信息
func UpdateSave(req *UpdateReq) error {
var entity = Entity{
WebId: gconv.Int(req.WebContent["webId"]),
WebContent: gconv.String(req.WebContent),
}
_, err := entity.Replace()
if err != nil {
g.Log().Error(err)
return gerror.New("更新站点信息失败")
}
return nil
}
// GetInfoByID 根据ID查询站点信息
func GetInfoByID(id int) (*Entity, error) {
entity, err := Model.FindOne("web_id", id)
if err != nil {
g.Log().Error(err)
return nil, gerror.New("根据ID查询站点信息出错")
}
if entity == nil {
return nil, gerror.New("根据ID未能查询到站点信息")
}
return entity, nil
}
+58
View File
@@ -0,0 +1,58 @@
// ==========================================================================
// This is auto-generated by gf cli tool. You may not really want to edit it.
// ==========================================================================
package web_set
import (
"database/sql"
"github.com/gogf/gf/database/gdb"
)
// Entity is the golang structure for table web_set.
type Entity struct {
WebId int `orm:"web_id,primary" json:"web_id"` // 主键
WebContent string `orm:"web_content" json:"web_content"` // 站点信息
}
// OmitEmpty sets OPTION_OMITEMPTY option for the model, which automatically filers
// the data and where attributes for empty values.
func (r *Entity) OmitEmpty() *arModel {
return Model.Data(r).OmitEmpty()
}
// Inserts does "INSERT...INTO..." statement for inserting current object into table.
func (r *Entity) Insert() (result sql.Result, err error) {
return Model.Data(r).Insert()
}
// InsertIgnore does "INSERT IGNORE INTO ..." statement for inserting current object into table.
func (r *Entity) InsertIgnore() (result sql.Result, err error) {
return Model.Data(r).InsertIgnore()
}
// Replace does "REPLACE...INTO..." statement for inserting current object into table.
// If there's already another same record in the table (it checks using primary key or unique index),
// it deletes it and insert this one.
func (r *Entity) Replace() (result sql.Result, err error) {
return Model.Data(r).Replace()
}
// Save does "INSERT...INTO..." statement for inserting/updating current object into table.
// It updates the record if there's already another same record in the table
// (it checks using primary key or unique index).
func (r *Entity) Save() (result sql.Result, err error) {
return Model.Data(r).Save()
}
// Update does "UPDATE...WHERE..." statement for updating current object from table.
// It updates the record if there's already another same record in the table
// (it checks using primary key or unique index).
func (r *Entity) Update() (result sql.Result, err error) {
return Model.Data(r).Where(gdb.GetWhereConditionOfStruct(r)).Update()
}
// Delete does "DELETE FROM...WHERE..." statement for deleting current object from table.
func (r *Entity) Delete() (result sql.Result, err error) {
return Model.Where(gdb.GetWhereConditionOfStruct(r)).Delete()
}
+345
View File
@@ -0,0 +1,345 @@
// ==========================================================================
// This is auto-generated by gf cli tool. You may not really want to edit it.
// ==========================================================================
package web_set
import (
"database/sql"
"github.com/gogf/gf/database/gdb"
"github.com/gogf/gf/frame/g"
"github.com/gogf/gf/frame/gmvc"
"time"
)
// arModel is a active record design model for table web_set operations.
type arModel struct {
gmvc.M
}
var (
// Table is the table name of web_set.
Table = "web_set"
// Model is the model object of web_set.
Model = &arModel{g.DB("default").Table(Table).Safe()}
// Columns defines and stores column names for table web_set.
Columns = struct {
WebId string // 主键
WebContent string // 站点信息
}{
WebId: "web_id",
WebContent: "web_content",
}
)
// FindOne is a convenience method for Model.FindOne.
// See Model.FindOne.
func FindOne(where ...interface{}) (*Entity, error) {
return Model.FindOne(where...)
}
// FindAll is a convenience method for Model.FindAll.
// See Model.FindAll.
func FindAll(where ...interface{}) ([]*Entity, error) {
return Model.FindAll(where...)
}
// FindValue is a convenience method for Model.FindValue.
// See Model.FindValue.
func FindValue(fieldsAndWhere ...interface{}) (gdb.Value, error) {
return Model.FindValue(fieldsAndWhere...)
}
// FindArray is a convenience method for Model.FindArray.
// See Model.FindArray.
func FindArray(fieldsAndWhere ...interface{}) ([]gdb.Value, error) {
return Model.FindArray(fieldsAndWhere...)
}
// FindCount is a convenience method for Model.FindCount.
// See Model.FindCount.
func FindCount(where ...interface{}) (int, error) {
return Model.FindCount(where...)
}
// Insert is a convenience method for Model.Insert.
func Insert(data ...interface{}) (result sql.Result, err error) {
return Model.Insert(data...)
}
// InsertIgnore is a convenience method for Model.InsertIgnore.
func InsertIgnore(data ...interface{}) (result sql.Result, err error) {
return Model.InsertIgnore(data...)
}
// Replace is a convenience method for Model.Replace.
func Replace(data ...interface{}) (result sql.Result, err error) {
return Model.Replace(data...)
}
// Save is a convenience method for Model.Save.
func Save(data ...interface{}) (result sql.Result, err error) {
return Model.Save(data...)
}
// Update is a convenience method for Model.Update.
func Update(dataAndWhere ...interface{}) (result sql.Result, err error) {
return Model.Update(dataAndWhere...)
}
// Delete is a convenience method for Model.Delete.
func Delete(where ...interface{}) (result sql.Result, err error) {
return Model.Delete(where...)
}
// As sets an alias name for current table.
func (m *arModel) As(as string) *arModel {
return &arModel{m.M.As(as)}
}
// TX sets the transaction for current operation.
func (m *arModel) TX(tx *gdb.TX) *arModel {
return &arModel{m.M.TX(tx)}
}
// Master marks the following operation on master node.
func (m *arModel) Master() *arModel {
return &arModel{m.M.Master()}
}
// Slave marks the following operation on slave node.
// Note that it makes sense only if there's any slave node configured.
func (m *arModel) Slave() *arModel {
return &arModel{m.M.Slave()}
}
// LeftJoin does "LEFT JOIN ... ON ..." statement on the model.
// The parameter <table> can be joined table and its joined condition,
// and also with its alias name, like:
// Table("user").LeftJoin("user_detail", "user_detail.uid=user.uid")
// Table("user", "u").LeftJoin("user_detail", "ud", "ud.uid=u.uid")
func (m *arModel) LeftJoin(table ...string) *arModel {
return &arModel{m.M.LeftJoin(table...)}
}
// RightJoin does "RIGHT JOIN ... ON ..." statement on the model.
// The parameter <table> can be joined table and its joined condition,
// and also with its alias name, like:
// Table("user").RightJoin("user_detail", "user_detail.uid=user.uid")
// Table("user", "u").RightJoin("user_detail", "ud", "ud.uid=u.uid")
func (m *arModel) RightJoin(table ...string) *arModel {
return &arModel{m.M.RightJoin(table...)}
}
// InnerJoin does "INNER JOIN ... ON ..." statement on the model.
// The parameter <table> can be joined table and its joined condition,
// and also with its alias name, like:
// Table("user").InnerJoin("user_detail", "user_detail.uid=user.uid")
// Table("user", "u").InnerJoin("user_detail", "ud", "ud.uid=u.uid")
func (m *arModel) InnerJoin(table ...string) *arModel {
return &arModel{m.M.InnerJoin(table...)}
}
// Fields sets the operation fields of the model, multiple fields joined using char ','.
func (m *arModel) Fields(fields string) *arModel {
return &arModel{m.M.Fields(fields)}
}
// FieldsEx sets the excluded operation fields of the model, multiple fields joined using char ','.
func (m *arModel) FieldsEx(fields string) *arModel {
return &arModel{m.M.FieldsEx(fields)}
}
// Option sets the extra operation option for the model.
func (m *arModel) Option(option int) *arModel {
return &arModel{m.M.Option(option)}
}
// OmitEmpty sets OPTION_OMITEMPTY option for the model, which automatically filers
// the data and where attributes for empty values.
func (m *arModel) OmitEmpty() *arModel {
return &arModel{m.M.OmitEmpty()}
}
// Filter marks filtering the fields which does not exist in the fields of the operated table.
func (m *arModel) Filter() *arModel {
return &arModel{m.M.Filter()}
}
// Where sets the condition statement for the model. The parameter <where> can be type of
// string/map/gmap/slice/struct/*struct, etc. Note that, if it's called more than one times,
// multiple conditions will be joined into where statement using "AND".
// Eg:
// Where("uid=10000")
// Where("uid", 10000)
// Where("money>? AND name like ?", 99999, "vip_%")
// Where("uid", 1).Where("name", "john")
// Where("status IN (?)", g.Slice{1,2,3})
// Where("age IN(?,?)", 18, 50)
// Where(User{ Id : 1, UserName : "john"})
func (m *arModel) Where(where interface{}, args ...interface{}) *arModel {
return &arModel{m.M.Where(where, args...)}
}
// And adds "AND" condition to the where statement.
func (m *arModel) And(where interface{}, args ...interface{}) *arModel {
return &arModel{m.M.And(where, args...)}
}
// Or adds "OR" condition to the where statement.
func (m *arModel) Or(where interface{}, args ...interface{}) *arModel {
return &arModel{m.M.Or(where, args...)}
}
// Group sets the "GROUP BY" statement for the model.
func (m *arModel) Group(groupBy string) *arModel {
return &arModel{m.M.Group(groupBy)}
}
// Order sets the "ORDER BY" statement for the model.
func (m *arModel) Order(orderBy ...string) *arModel {
return &arModel{m.M.Order(orderBy...)}
}
// Limit sets the "LIMIT" statement for the model.
// The parameter <limit> can be either one or two number, if passed two number is passed,
// it then sets "LIMIT limit[0],limit[1]" statement for the model, or else it sets "LIMIT limit[0]"
// statement.
func (m *arModel) Limit(limit ...int) *arModel {
return &arModel{m.M.Limit(limit...)}
}
// Offset sets the "OFFSET" statement for the model.
// It only makes sense for some databases like SQLServer, PostgreSQL, etc.
func (m *arModel) Offset(offset int) *arModel {
return &arModel{m.M.Offset(offset)}
}
// Page sets the paging number for the model.
// The parameter <page> is started from 1 for paging.
// Note that, it differs that the Limit function start from 0 for "LIMIT" statement.
func (m *arModel) Page(page, limit int) *arModel {
return &arModel{m.M.Page(page, limit)}
}
// Batch sets the batch operation number for the model.
func (m *arModel) Batch(batch int) *arModel {
return &arModel{m.M.Batch(batch)}
}
// Cache sets the cache feature for the model. It caches the result of the sql, which means
// if there's another same sql request, it just reads and returns the result from cache, it
// but not committed and executed into the database.
//
// If the parameter <duration> < 0, which means it clear the cache with given <name>.
// If the parameter <duration> = 0, which means it never expires.
// If the parameter <duration> > 0, which means it expires after <duration>.
//
// The optional parameter <name> is used to bind a name to the cache, which means you can later
// control the cache like changing the <duration> or clearing the cache with specified <name>.
//
// Note that, the cache feature is disabled if the model is operating on a transaction.
func (m *arModel) Cache(duration time.Duration, name ...string) *arModel {
return &arModel{m.M.Cache(duration, name...)}
}
// Data sets the operation data for the model.
// The parameter <data> can be type of string/map/gmap/slice/struct/*struct, etc.
// Eg:
// Data("uid=10000")
// Data("uid", 10000)
// Data(g.Map{"uid": 10000, "name":"john"})
// Data(g.Slice{g.Map{"uid": 10000, "name":"john"}, g.Map{"uid": 20000, "name":"smith"})
func (m *arModel) Data(data ...interface{}) *arModel {
return &arModel{m.M.Data(data...)}
}
// All does "SELECT FROM ..." statement for the model.
// It retrieves the records from table and returns the result as []*Entity.
// It returns nil if there's no record retrieved with the given conditions from table.
//
// The optional parameter <where> is the same as the parameter of Model.Where function,
// see Model.Where.
func (m *arModel) All(where ...interface{}) ([]*Entity, error) {
all, err := m.M.All(where...)
if err != nil {
return nil, err
}
var entities []*Entity
if err = all.Structs(&entities); err != nil && err != sql.ErrNoRows {
return nil, err
}
return entities, nil
}
// One retrieves one record from table and returns the result as *Entity.
// It returns nil if there's no record retrieved with the given conditions from table.
//
// The optional parameter <where> is the same as the parameter of Model.Where function,
// see Model.Where.
func (m *arModel) One(where ...interface{}) (*Entity, error) {
one, err := m.M.One(where...)
if err != nil {
return nil, err
}
var entity *Entity
if err = one.Struct(&entity); err != nil && err != sql.ErrNoRows {
return nil, err
}
return entity, nil
}
// FindOne retrieves and returns a single Record by Model.WherePri and Model.One.
// Also see Model.WherePri and Model.One.
func (m *arModel) FindOne(where ...interface{}) (*Entity, error) {
one, err := m.M.FindOne(where...)
if err != nil {
return nil, err
}
var entity *Entity
if err = one.Struct(&entity); err != nil && err != sql.ErrNoRows {
return nil, err
}
return entity, nil
}
// FindAll retrieves and returns Result by by Model.WherePri and Model.All.
// Also see Model.WherePri and Model.All.
func (m *arModel) FindAll(where ...interface{}) ([]*Entity, error) {
all, err := m.M.FindAll(where...)
if err != nil {
return nil, err
}
var entities []*Entity
if err = all.Structs(&entities); err != nil && err != sql.ErrNoRows {
return nil, err
}
return entities, nil
}
// Chunk iterates the table with given size and callback function.
func (m *arModel) Chunk(limit int, callback func(entities []*Entity, err error) bool) {
m.M.Chunk(limit, func(result gdb.Result, err error) bool {
var entities []*Entity
err = result.Structs(&entities)
if err == sql.ErrNoRows {
return false
}
return callback(entities, err)
})
}
// LockUpdate sets the lock for update for current operation.
func (m *arModel) LockUpdate() *arModel {
return &arModel{m.M.LockUpdate()}
}
// LockShared sets the lock in share mode for current operation.
func (m *arModel) LockShared() *arModel {
return &arModel{m.M.LockShared()}
}
// Unscoped enables/disables the soft deleting feature.
func (m *arModel) Unscoped() *arModel {
return &arModel{m.M.Unscoped()}
}
+1 -39
View File
@@ -4,12 +4,8 @@ import (
"gfast/app/model/admin/user_online"
"gfast/boot"
"gfast/library/service"
"github.com/goflyfox/gtoken/gtoken"
"github.com/gogf/gf/encoding/gjson"
"github.com/gogf/gf/errors/gerror"
"github.com/gogf/gf/frame/g"
"github.com/gogf/gf/os/gcache"
"github.com/gogf/gf/util/gconv"
)
//获取在线用户列表
@@ -20,41 +16,7 @@ func GetOnlineListPage(req *user_online.ReqListSearch) (total, page int, list []
if req.PageSize == 0 {
req.PageSize = service.AdminPageNum
}
return user_online.GetOnlineListPage(req)
}
//通过token获取登录用户数据
func GetOnlineInfo(token string) g.Map {
uuid, userKey := GetUuidUserKeyByToken(token)
cacheKey := boot.AdminGfToken.CacheKey + userKey
switch boot.AdminGfToken.CacheMode {
case gtoken.CacheModeCache:
userCacheValue := gcache.Get(cacheKey)
if userCacheValue == nil {
return nil
}
return gconv.Map(userCacheValue)
case gtoken.CacheModeRedis:
var userCache g.Map
userCacheJson, err := g.Redis().Do("GET", cacheKey)
if err != nil {
g.Log().Error("[GToken]cache get error", err)
return nil
}
if userCacheJson == nil {
return nil
}
err = gjson.DecodeTo(userCacheJson, &userCache)
if err != nil {
g.Log().Error("[GToken]cache get json error", err)
return nil
}
if uuid != userCache["uuid"] {
return nil
}
return userCache
}
return nil
return user_online.GetOnlineListPage(req, false)
}
//通过token获取uuid和userKey
@@ -0,0 +1,13 @@
package web_set_service
import "gfast/app/model/admin/web_set"
// 更新站点信息
func UpdateSave(req *web_set.UpdateReq) error {
return web_set.UpdateSave(req)
}
// GetInfoByID 根据ID查询站点信息
func GetInfoByID(id int) (*web_set.Entity, error) {
return web_set.GetInfoByID(id)
}
+95
View File
@@ -1,5 +1,15 @@
package task
import (
"gfast/app/model/admin/user_online"
"gfast/boot"
"github.com/goflyfox/gtoken/gtoken"
"github.com/gogf/gf/encoding/gjson"
"github.com/gogf/gf/frame/g"
"github.com/gogf/gf/os/gcache"
"github.com/gogf/gf/util/gconv"
)
func init() {
var task1 Entity
task1.FuncName = "test1"
@@ -12,6 +22,12 @@ func init() {
task2.Param = nil
task2.Run = Test2
Add(task2)
var checkUserOnline Entity
checkUserOnline.FuncName = "checkUserOnline"
checkUserOnline.Param = nil
checkUserOnline.Run = CheckUserOnline
Add(checkUserOnline)
}
//无参测试
@@ -30,3 +46,82 @@ func Test2() {
println(v)
}
}
//检查在线用户
func CheckUserOnline() {
param := &user_online.ReqListSearch{
PageNum: 1,
PageSize: 50,
}
var total int
for {
var (
list []*user_online.Entity
err error
)
total, _, list, err = user_online.GetOnlineListPage(param, true)
if err != nil {
g.Log().Error(err)
break
}
if list == nil {
break
}
for _, entity := range list {
onlineInfo := GetOnlineInfo(entity.Token)
if onlineInfo == nil {
entity.Delete()
}
}
param.PageNum++
if param.PageNum*param.PageSize >= total {
break
}
}
}
//通过token获取登录用户数据
func GetOnlineInfo(token string) g.Map {
uuid, userKey := GetUuidUserKeyByToken(token)
cacheKey := boot.AdminGfToken.CacheKey + userKey
switch boot.AdminGfToken.CacheMode {
case gtoken.CacheModeCache:
userCacheValue := gcache.Get(cacheKey)
if userCacheValue == nil {
return nil
}
return gconv.Map(userCacheValue)
case gtoken.CacheModeRedis:
var userCache g.Map
userCacheJson, err := g.Redis().Do("GET", cacheKey)
if err != nil {
g.Log().Error("[GToken]cache get error", err)
return nil
}
if userCacheJson == nil {
return nil
}
err = gjson.DecodeTo(userCacheJson, &userCache)
if err != nil {
g.Log().Error("[GToken]cache get json error", err)
return nil
}
if uuid != userCache["uuid"] {
return nil
}
return userCache
}
return nil
}
//通过token获取uuid和userKey
func GetUuidUserKeyByToken(token string) (uuid, userKey string) {
decryptToken := boot.AdminGfToken.DecryptToken(token)
if !decryptToken.Success() {
return
}
userKey = decryptToken.GetString("userKey")
uuid = decryptToken.GetString("uuid")
return
}