Refine the rest structure.

This commit is contained in:
zicla
2019-04-26 11:43:54 +08:00
parent c55e8699b4
commit e88930e13a
49 changed files with 201 additions and 183 deletions

View File

@ -1,8 +0,0 @@
package code
type BaseDao struct {
Bean
}

View File

@ -5,9 +5,9 @@ import (
_ "github.com/go-sql-driver/mysql"
"log"
"net/http"
"tank/code"
"tank/code/config"
"tank/code/logger"
"tank/code/rest"
)
func main() {
@ -20,10 +20,10 @@ func main() {
config.CONFIG.Init()
//全局运行的上下文
code.CONTEXT.Init()
defer code.CONTEXT.Destroy()
rest.CONTEXT.Init()
defer rest.CONTEXT.Destroy()
http.Handle("/", code.CONTEXT.Router)
http.Handle("/", rest.CONTEXT.Router)
logger.LOGGER.Info("App started at http://localhost:%v", config.CONFIG.ServerPort)

View File

@ -1,4 +1,4 @@
package code
package rest
import (
"fmt"

View File

@ -1,4 +1,4 @@
package code
package rest
import (
"fmt"

View File

@ -1,4 +1,4 @@
package code
package rest
import (
"fmt"

26
code/rest/base_dao.go Normal file
View File

@ -0,0 +1,26 @@
package rest
import "tank/code/tool/builder"
type BaseDao struct {
Bean
}
//根据一个sortMap获取到order字符串
func (this *BaseDao) GetSortString(sortArray []builder.OrderPair) string {
if sortArray == nil || len(sortArray) == 0 {
return ""
}
str := ""
for _, pair := range sortArray {
if pair.Value == "DESC" || pair.Value == "ASC" {
if str != "" {
str = str + ","
}
str = str + " " + pair.Key + " " + pair.Value
}
}
return str
}

View File

@ -1,4 +1,4 @@
package code
package rest
import (
"math"

View File

@ -1,4 +1,4 @@
package code
package rest
import (
"net/http"

View File

@ -1,4 +1,4 @@
package code
package rest
import (
"fmt"
@ -17,7 +17,7 @@ type Context struct {
//数据库连接
DB *gorm.DB
//session缓存
SessionCache *cache2.CacheTable
SessionCache *cache2.Table
//各类的Bean Map。这里面是包含ControllerMap中所有元素
BeanMap map[string]IBean
//只包含了Controller的map
@ -30,7 +30,7 @@ type Context struct {
func (this *Context) Init() {
//创建一个用于存储session的缓存。
this.SessionCache = cache2.NewCacheTable()
this.SessionCache = cache2.NewTable()
//初始化Map
this.BeanMap = make(map[string]IBean)

View File

@ -1,8 +1,9 @@
package code
package rest
import (
"net/http"
"strconv"
"tank/code/tool/builder"
"tank/code/tool/result"
)
@ -72,7 +73,7 @@ func (this *DashboardController) Page(writer http.ResponseWriter, request *http.
}
}
sortArray := []OrderPair{
sortArray := []builder.OrderPair{
{
key: "create_time",
value: orderCreateTime,

View File

@ -1,8 +1,9 @@
package code
package rest
import (
"github.com/jinzhu/gorm"
"github.com/nu7hatch/gouuid"
"tank/code/tool/builder"
"time"
)
@ -54,12 +55,12 @@ func (this *DashboardDao) FindByDt(dt string) *Dashboard {
}
//获取某个文件夹下所有的文件和子文件
func (this *DashboardDao) Page(page int, pageSize int, dt string, sortArray []OrderPair) *Pager {
func (this *DashboardDao) Page(page int, pageSize int, dt string, sortArray []builder.OrderPair) *Pager {
var wp = &WherePair{}
var wp = &builder.WherePair{}
if dt != "" {
wp = wp.And(&WherePair{Query: "dt = ?", Args: []interface{}{dt}})
wp = wp.And(&builder.WherePair{Query: "dt = ?", Args: []interface{}{dt}})
}
var conditionDB *gorm.DB
@ -82,7 +83,7 @@ func (this *DashboardDao) ActiveIpTop10() []*DashboardIpTimes {
var dashboardIpTimes []*DashboardIpTimes
sortArray := []OrderPair{
sortArray := []builder.OrderPair{
{
key: "times",
value: "DESC",

View File

@ -1,4 +1,4 @@
package code
package rest
import "tank/code/config"

View File

@ -1,4 +1,4 @@
package code
package rest
import (
"tank/code/tool/util"

View File

@ -1,4 +1,4 @@
package code
package rest
import (
"bytes"

View File

@ -1,12 +1,12 @@
package code
package rest
import (
"fmt"
"net/http"
"path"
"strconv"
dav2 "tank/code/tool/dav"
xml2 "tank/code/tool/dav/xml"
"tank/code/tool/dav"
"tank/code/tool/dav/xml"
)
//访问前缀,这个是特殊入口
@ -19,7 +19,7 @@ type LiveProp struct {
}
//所有的动态属性定义及其值的获取方式
var LivePropMap = map[xml2.Name]LiveProp{
var LivePropMap = map[xml.Name]LiveProp{
{Space: "DAV:", Local: "resourcetype"}: {
findFn: func(user *User, matter *Matter) string {
if matter.Dir {
@ -35,7 +35,7 @@ var LivePropMap = map[xml2.Name]LiveProp{
if path.Clean("/"+matter.Name) == "/" {
return ""
} else {
return dav2.EscapeXML(matter.Name)
return dav.EscapeXML(matter.Name)
}
},
dir: true,
@ -72,7 +72,7 @@ var LivePropMap = map[xml2.Name]LiveProp{
if matter.Dir {
return ""
} else {
return dav2.EscapeXML(matter.Name)
return dav.EscapeXML(matter.Name)
}
},
dir: false,

View File

@ -1,4 +1,4 @@
package code
package rest
import (
"fmt"

View File

@ -1,4 +1,4 @@
package code
package rest
import (

View File

@ -1,4 +1,4 @@
package code
package rest
import (
"tank/code/config"

View File

@ -1,8 +1,9 @@
package code
package rest
import (
"net/http"
"strconv"
"tank/code/tool/builder"
"tank/code/tool/result"
)
@ -92,7 +93,7 @@ func (this *FootprintController) Page(writer http.ResponseWriter, request *http.
}
}
sortArray := []OrderPair{
sortArray := []builder.OrderPair{
{
key: "create_time",
value: orderCreateTime,

View File

@ -1,7 +1,8 @@
package code
package rest
import (
"github.com/jinzhu/gorm"
"tank/code/tool/builder"
"github.com/nu7hatch/gouuid"
"time"
@ -36,12 +37,12 @@ func (this *FootprintDao) CheckByUuid(uuid string) *Footprint {
}
//按分页条件获取分页
func (this *FootprintDao) Page(page int, pageSize int, userUuid string, sortArray []OrderPair) *Pager {
func (this *FootprintDao) Page(page int, pageSize int, userUuid string, sortArray []builder.OrderPair) *Pager {
var wp = &WherePair{}
var wp = &builder.WherePair{}
if userUuid != "" {
wp = wp.And(&WherePair{Query: "user_uuid = ?", Args: []interface{}{userUuid}})
wp = wp.And(&builder.WherePair{Query: "user_uuid = ?", Args: []interface{}{userUuid}})
}
var conditionDB *gorm.DB

View File

@ -1,4 +1,4 @@
package code
package rest
import "tank/code/config"

View File

@ -1,4 +1,4 @@
package code
package rest
import (
"encoding/json"

View File

@ -1,9 +1,10 @@
package code
package rest
import (
"net/http"
"strconv"
"strings"
"tank/code/tool/builder"
"tank/code/tool/result"
)
@ -97,7 +98,7 @@ func (this *ImageCacheController) Page(writer http.ResponseWriter, request *http
}
}
sortArray := []OrderPair{
sortArray := []builder.OrderPair{
{
key: "create_time",
value: orderCreateTime,

View File

@ -1,4 +1,4 @@
package code
package rest
import (
"fmt"
@ -6,6 +6,7 @@ import (
"github.com/nu7hatch/gouuid"
"os"
"path/filepath"
"tank/code/tool/builder"
"tank/code/tool/util"
"time"
)
@ -41,14 +42,14 @@ func (this *ImageCacheDao) CheckByUuid(uuid string) *ImageCache {
//按照名字查询文件夹
func (this *ImageCacheDao) FindByMatterUuidAndMode(matterUuid string, mode string) *ImageCache {
var wp = &WherePair{}
var wp = &builder.WherePair{}
if matterUuid != "" {
wp = wp.And(&WherePair{Query: "matter_uuid = ?", Args: []interface{}{matterUuid}})
wp = wp.And(&builder.WherePair{Query: "matter_uuid = ?", Args: []interface{}{matterUuid}})
}
if mode != "" {
wp = wp.And(&WherePair{Query: "mode = ?", Args: []interface{}{mode}})
wp = wp.And(&builder.WherePair{Query: "mode = ?", Args: []interface{}{mode}})
}
var imageCache = &ImageCache{}
@ -87,16 +88,16 @@ func (this *ImageCacheDao) ListByUserUuidAndPuuidAndDirAndName(userUuid string)
}
//获取某个文件夹下所有的文件和子文件
func (this *ImageCacheDao) Page(page int, pageSize int, userUuid string, matterUuid string, sortArray []OrderPair) *Pager {
func (this *ImageCacheDao) Page(page int, pageSize int, userUuid string, matterUuid string, sortArray []builder.OrderPair) *Pager {
var wp = &WherePair{}
var wp = &builder.WherePair{}
if userUuid != "" {
wp = wp.And(&WherePair{Query: "user_uuid = ?", Args: []interface{}{userUuid}})
wp = wp.And(&builder.WherePair{Query: "user_uuid = ?", Args: []interface{}{userUuid}})
}
if matterUuid != "" {
wp = wp.And(&WherePair{Query: "matter_uuid = ?", Args: []interface{}{matterUuid}})
wp = wp.And(&builder.WherePair{Query: "matter_uuid = ?", Args: []interface{}{matterUuid}})
}
var conditionDB *gorm.DB
@ -169,9 +170,9 @@ func (this *ImageCacheDao) Delete(imageCache *ImageCache) {
//删除一个matter对应的所有缓存
func (this *ImageCacheDao) DeleteByMatterUuid(matterUuid string) {
var wp = &WherePair{}
var wp = &builder.WherePair{}
wp = wp.And(&WherePair{Query: "matter_uuid = ?", Args: []interface{}{matterUuid}})
wp = wp.And(&builder.WherePair{Query: "matter_uuid = ?", Args: []interface{}{matterUuid}})
//查询出即将删除的图片缓存
var imageCaches []*ImageCache

View File

@ -1,4 +1,4 @@
package code
package rest
import (
"tank/code/config"

View File

@ -1,4 +1,4 @@
package code
package rest
import (
"fmt"

View File

@ -1,4 +1,4 @@
package code
package rest
import (
"fmt"
@ -12,6 +12,7 @@ import (
"regexp"
"strconv"
"tank/code/config"
"tank/code/tool/builder"
"tank/code/tool/result"
"tank/code/tool/util"
"time"
@ -285,9 +286,9 @@ func (this *InstallController) AdminList(writer http.ResponseWriter, request *ht
db := this.openDbConnection(writer, request)
defer this.closeDbConnection(db)
var wp = &WherePair{}
var wp = &builder.WherePair{}
wp = wp.And(&WherePair{Query: "role = ?", Args: []interface{}{USER_ROLE_ADMINISTRATOR}})
wp = wp.And(&builder.WherePair{Query: "role = ?", Args: []interface{}{USER_ROLE_ADMINISTRATOR}})
var users []*User
db = db.Where(wp.Query, wp.Args...).Offset(0).Limit(10).Find(&users)

View File

@ -1,4 +1,4 @@
package code
package rest
import "github.com/jinzhu/gorm"

View File

@ -1,9 +1,10 @@
package code
package rest
import (
"net/http"
"strconv"
"strings"
"tank/code/tool/builder"
"tank/code/tool/result"
)
@ -134,7 +135,7 @@ func (this *MatterController) Page(writer http.ResponseWriter, request *http.Req
extensions = strings.Split(extensionsStr, ",")
}
sortArray := []OrderPair{
sortArray := []builder.OrderPair{
{
key: "dir",
value: orderDir,

View File

@ -1,10 +1,11 @@
package code
package rest
import (
"github.com/jinzhu/gorm"
"github.com/nu7hatch/gouuid"
"os"
"tank/code/config"
"tank/code/tool/builder"
"tank/code/tool/result"
"tank/code/tool/util"
"time"
@ -93,21 +94,21 @@ func (this *MatterDao) CheckWithRootByPath(path string, user *User) *Matter {
//按照名字查询文件夹
func (this *MatterDao) FindByUserUuidAndPuuidAndNameAndDirTrue(userUuid string, puuid string, name string) *Matter {
var wp = &WherePair{}
var wp = &builder.WherePair{}
if userUuid != "" {
wp = wp.And(&WherePair{Query: "user_uuid = ?", Args: []interface{}{userUuid}})
wp = wp.And(&builder.WherePair{Query: "user_uuid = ?", Args: []interface{}{userUuid}})
}
if puuid != "" {
wp = wp.And(&WherePair{Query: "puuid = ?", Args: []interface{}{puuid}})
wp = wp.And(&builder.WherePair{Query: "puuid = ?", Args: []interface{}{puuid}})
}
if name != "" {
wp = wp.And(&WherePair{Query: "name = ?", Args: []interface{}{name}})
wp = wp.And(&builder.WherePair{Query: "name = ?", Args: []interface{}{name}})
}
wp = wp.And(&WherePair{Query: "dir = ?", Args: []interface{}{1}})
wp = wp.And(&builder.WherePair{Query: "dir = ?", Args: []interface{}{1}})
var matter = &Matter{}
db := CONTEXT.DB.Model(&Matter{}).Where(wp.Query, wp.Args...).First(matter)
@ -137,21 +138,21 @@ func (this *MatterDao) CountByUserUuidAndPuuidAndDirAndName(userUuid string, puu
var matter Matter
var count int
var wp = &WherePair{}
var wp = &builder.WherePair{}
if puuid != "" {
wp = wp.And(&WherePair{Query: "puuid = ?", Args: []interface{}{puuid}})
wp = wp.And(&builder.WherePair{Query: "puuid = ?", Args: []interface{}{puuid}})
}
if userUuid != "" {
wp = wp.And(&WherePair{Query: "user_uuid = ?", Args: []interface{}{userUuid}})
wp = wp.And(&builder.WherePair{Query: "user_uuid = ?", Args: []interface{}{userUuid}})
}
if name != "" {
wp = wp.And(&WherePair{Query: "name = ?", Args: []interface{}{name}})
wp = wp.And(&builder.WherePair{Query: "name = ?", Args: []interface{}{name}})
}
wp = wp.And(&WherePair{Query: "dir = ?", Args: []interface{}{dir}})
wp = wp.And(&builder.WherePair{Query: "dir = ?", Args: []interface{}{dir}})
db := CONTEXT.DB.
Model(&matter).
@ -176,7 +177,7 @@ func (this *MatterDao) ListByUserUuidAndPuuidAndDirAndName(userUuid string, puui
}
//获取某个文件夹下所有的文件和子文件
func (this *MatterDao) List(puuid string, userUuid string, sortArray []OrderPair) []*Matter {
func (this *MatterDao) List(puuid string, userUuid string, sortArray []builder.OrderPair) []*Matter {
var matters []*Matter
db := CONTEXT.DB.Where(Matter{UserUuid: userUuid, Puuid: puuid}).Order(this.GetSortString(sortArray)).Find(&matters)
@ -186,40 +187,40 @@ func (this *MatterDao) List(puuid string, userUuid string, sortArray []OrderPair
}
//获取某个文件夹下所有的文件和子文件
func (this *MatterDao) Page(page int, pageSize int, puuid string, userUuid string, name string, dir string, alien string, extensions []string, sortArray []OrderPair) *Pager {
func (this *MatterDao) Page(page int, pageSize int, puuid string, userUuid string, name string, dir string, alien string, extensions []string, sortArray []builder.OrderPair) *Pager {
var wp = &WherePair{}
var wp = &builder.WherePair{}
if puuid != "" {
wp = wp.And(&WherePair{Query: "puuid = ?", Args: []interface{}{puuid}})
wp = wp.And(&builder.WherePair{Query: "puuid = ?", Args: []interface{}{puuid}})
}
if userUuid != "" {
wp = wp.And(&WherePair{Query: "user_uuid = ?", Args: []interface{}{userUuid}})
wp = wp.And(&builder.WherePair{Query: "user_uuid = ?", Args: []interface{}{userUuid}})
}
if name != "" {
wp = wp.And(&WherePair{Query: "name LIKE ?", Args: []interface{}{"%" + name + "%"}})
wp = wp.And(&builder.WherePair{Query: "name LIKE ?", Args: []interface{}{"%" + name + "%"}})
}
if dir == TRUE {
wp = wp.And(&WherePair{Query: "dir = ?", Args: []interface{}{1}})
wp = wp.And(&builder.WherePair{Query: "dir = ?", Args: []interface{}{1}})
} else if dir == FALSE {
wp = wp.And(&WherePair{Query: "dir = ?", Args: []interface{}{0}})
wp = wp.And(&builder.WherePair{Query: "dir = ?", Args: []interface{}{0}})
}
if alien == TRUE {
wp = wp.And(&WherePair{Query: "alien = ?", Args: []interface{}{1}})
wp = wp.And(&builder.WherePair{Query: "alien = ?", Args: []interface{}{1}})
} else if alien == FALSE {
wp = wp.And(&WherePair{Query: "alien = ?", Args: []interface{}{0}})
wp = wp.And(&builder.WherePair{Query: "alien = ?", Args: []interface{}{0}})
}
var conditionDB *gorm.DB
if extensions != nil && len(extensions) > 0 {
var orWp = &WherePair{}
var orWp = &builder.WherePair{}
for _, v := range extensions {
orWp = orWp.Or(&WherePair{Query: "name LIKE ?", Args: []interface{}{"%." + v}})
orWp = orWp.Or(&builder.WherePair{Query: "name LIKE ?", Args: []interface{}{"%." + v}})
}
conditionDB = CONTEXT.DB.Model(&Matter{}).Where(wp.Query, wp.Args...).Where(orWp.Query, orWp.Args...)
@ -329,7 +330,7 @@ func (this *MatterDao) SizeBetweenTime(startTime time.Time, endTime time.Time) i
//根据userUuid和path来查找
func (this *MatterDao) findByUserUuidAndPath(userUuid string, path string) *Matter {
var wp = &WherePair{Query: "user_uuid = ? AND path = ?", Args: []interface{}{userUuid, path}}
var wp = &builder.WherePair{Query: "user_uuid = ? AND path = ?", Args: []interface{}{userUuid, path}}
var matter = &Matter{}
db := CONTEXT.DB.Model(&Matter{}).Where(wp.Query, wp.Args...).First(matter)

View File

@ -1,4 +1,4 @@
package code
package rest
import (
"fmt"

View File

@ -1,4 +1,4 @@
package code
package rest
import (
"io"

View File

@ -1,4 +1,4 @@
package code
package rest
import (
"net/http"

View File

@ -1,4 +1,4 @@
package code
package rest
import (
"github.com/nu7hatch/gouuid"

View File

@ -1,4 +1,4 @@
package code
package rest
import "tank/code/config"

View File

@ -1,4 +1,4 @@
package code
package rest
//@Service
type PreferenceService struct {

View File

@ -1,4 +1,4 @@
package code
package rest
import (
"fmt"
@ -131,7 +131,6 @@ func (this *Router) ServeHTTP(writer http.ResponseWriter, request *http.Request)
writer.Header().Set("Cache-Control", "no-cache")
writer.Header().Set("Expires", "0")
if config.CONFIG.Installed {
//已安装的模式
@ -195,7 +194,12 @@ func (this *Router) ServeHTTP(writer http.ResponseWriter, request *http.Request)
if err != nil {
panic("cannot get file.")
}
defer diskFile.Close()
defer func() {
err := diskFile.Close()
if err != nil {
panic(err)
}
}()
_, err = io.Copy(writer, diskFile)
if err != nil {
panic("cannot get file.")

View File

@ -1,4 +1,4 @@
package code
package rest
import (

View File

@ -1,4 +1,4 @@
package code
package rest
import (
"tank/code/config"

View File

@ -1,4 +1,4 @@
package code
package rest
//@Service
type SessionService struct {

View File

@ -1,4 +1,4 @@
package code
package rest
import (

View File

@ -1,4 +1,4 @@
package code
package rest
import (
"tank/code/config"

View File

@ -1,10 +1,11 @@
package code
package rest
import (
"net/http"
"regexp"
"strconv"
"tank/code/config"
"tank/code/tool/builder"
"tank/code/tool/result"
"tank/code/tool/util"
"time"
@ -276,7 +277,7 @@ func (this *UserController) Page(writer http.ResponseWriter, request *http.Reque
}
}
sortArray := []OrderPair{
sortArray := []builder.OrderPair{
{
key: "create_time",
value: orderCreateTime,

View File

@ -1,7 +1,8 @@
package code
package rest
import (
"github.com/nu7hatch/gouuid"
"tank/code/tool/builder"
"time"
)
@ -78,24 +79,24 @@ func (this *UserDao) FindByEmail(email string) *User {
}
//显示用户列表。
func (this *UserDao) Page(page int, pageSize int, username string, email string, phone string, status string, sortArray []OrderPair) *Pager {
func (this *UserDao) Page(page int, pageSize int, username string, email string, phone string, status string, sortArray []builder.OrderPair) *Pager {
var wp = &WherePair{}
var wp = &builder.WherePair{}
if username != "" {
wp = wp.And(&WherePair{Query: "username LIKE ?", Args: []interface{}{"%" + username + "%"}})
wp = wp.And(&builder.WherePair{Query: "username LIKE ?", Args: []interface{}{"%" + username + "%"}})
}
if email != "" {
wp = wp.And(&WherePair{Query: "email LIKE ?", Args: []interface{}{"%" + email + "%"}})
wp = wp.And(&builder.WherePair{Query: "email LIKE ?", Args: []interface{}{"%" + email + "%"}})
}
if phone != "" {
wp = wp.And(&WherePair{Query: "phone = ?", Args: []interface{}{phone}})
wp = wp.And(&builder.WherePair{Query: "phone = ?", Args: []interface{}{phone}})
}
if status != "" {
wp = wp.And(&WherePair{Query: "status = ?", Args: []interface{}{status}})
wp = wp.And(&builder.WherePair{Query: "status = ?", Args: []interface{}{status}})
}
count := 0

View File

@ -1,4 +1,4 @@
package code
package rest
import (
"tank/code/config"

View File

@ -1,4 +1,4 @@
package code
package rest
import (
"net/http"
@ -15,7 +15,7 @@ type UserService struct {
sessionDao *SessionDao
//操作文件的锁。
locker *cache2.CacheTable
locker *cache2.Table
}
//初始化方法
@ -34,7 +34,7 @@ func (this *UserService) Init() {
}
//创建一个用于存储用户文件锁的缓存。
this.locker = cache2.NewCacheTable()
this.locker = cache2.NewTable()
}

View File

@ -1,8 +1,8 @@
package code
package builder
type OrderPair struct {
key string
value string
Key string
Value string
}
type WherePair struct {
@ -28,21 +28,3 @@ func (this *WherePair) Or(where *WherePair) *WherePair {
}
//根据一个sortMap获取到order字符串
func (this *BaseDao) GetSortString(sortArray []OrderPair) string {
if sortArray == nil || len(sortArray) == 0 {
return ""
}
str := ""
for _, pair := range sortArray {
if pair.value == "DESC" || pair.value == "ASC" {
if str != "" {
str = str + ","
}
str = str + " " + pair.key + " " + pair.value
}
}
return str
}

View File

@ -11,7 +11,7 @@ import (
//缓存项
//主要借鉴了cache2go https://github.com/muesli/cache2go
type CacheItem struct {
type Item struct {
sync.RWMutex //读写锁
//缓存键
key interface{}
@ -30,9 +30,9 @@ type CacheItem struct {
}
//新建一项缓存
func NewCacheItem(key interface{}, duration time.Duration, data interface{}) *CacheItem {
func NewItem(key interface{}, duration time.Duration, data interface{}) *Item {
t := time.Now()
return &CacheItem{
return &Item{
key: key,
duration: duration,
createTime: t,
@ -44,7 +44,7 @@ func NewCacheItem(key interface{}, duration time.Duration, data interface{}) *Ca
}
//手动获取一下,保持该项
func (item *CacheItem) KeepAlive() {
func (item *Item) KeepAlive() {
item.Lock()
defer item.Unlock()
item.accessTime = time.Now()
@ -52,73 +52,73 @@ func (item *CacheItem) KeepAlive() {
}
//返回生命周期
func (item *CacheItem) Duration() time.Duration {
func (item *Item) Duration() time.Duration {
return item.duration
}
//返回访问时间。可能并发,加锁
func (item *CacheItem) AccessTime() time.Time {
func (item *Item) AccessTime() time.Time {
item.RLock()
defer item.RUnlock()
return item.accessTime
}
//返回创建时间
func (item *CacheItem) CreateTime() time.Time {
func (item *Item) CreateTime() time.Time {
return item.createTime
}
//返回访问时间。可能并发,加锁
func (item *CacheItem) Count() int64 {
func (item *Item) Count() int64 {
item.RLock()
defer item.RUnlock()
return item.count
}
//返回key值
func (item *CacheItem) Key() interface{} {
func (item *Item) Key() interface{} {
return item.key
}
//返回数据
func (item *CacheItem) Data() interface{} {
func (item *Item) Data() interface{} {
return item.data
}
//设置回调函数
func (item *CacheItem) SetDeleteCallback(f func(interface{})) {
func (item *Item) SetDeleteCallback(f func(interface{})) {
item.Lock()
defer item.Unlock()
item.deleteCallback = f
}
// 统一管理缓存项的表
type CacheTable struct {
type Table struct {
sync.RWMutex
//所有缓存项
items map[interface{}]*CacheItem
items map[interface{}]*Item
// 触发缓存清理的定时器
cleanupTimer *time.Timer
// 缓存清理周期
cleanupInterval time.Duration
// 获取一个不存在的缓存项时的回调函数
loadData func(key interface{}, args ...interface{}) *CacheItem
loadData func(key interface{}, args ...interface{}) *Item
// 向缓存表增加缓存项时的回调函数
addedCallback func(item *CacheItem)
addedCallback func(item *Item)
// 从缓存表删除一个缓存项时的回调函数
deleteCallback func(item *CacheItem)
deleteCallback func(item *Item)
}
// 返回缓存中存储有多少项
func (table *CacheTable) Count() int {
func (table *Table) Count() int {
table.RLock()
defer table.RUnlock()
return len(table.items)
}
// 遍历所有项
func (table *CacheTable) Foreach(trans func(key interface{}, item *CacheItem)) {
func (table *Table) Foreach(trans func(key interface{}, item *Item)) {
table.RLock()
defer table.RUnlock()
@ -128,28 +128,28 @@ func (table *CacheTable) Foreach(trans func(key interface{}, item *CacheItem)) {
}
// SetDataLoader配置一个数据加载的回调当尝试去请求一个不存在的key的时候调用
func (table *CacheTable) SetDataLoader(f func(interface{}, ...interface{}) *CacheItem) {
func (table *Table) SetDataLoader(f func(interface{}, ...interface{}) *Item) {
table.Lock()
defer table.Unlock()
table.loadData = f
}
// 添加时的回调函数
func (table *CacheTable) SetAddedCallback(f func(*CacheItem)) {
func (table *Table) SetAddedCallback(f func(*Item)) {
table.Lock()
defer table.Unlock()
table.addedCallback = f
}
// 删除时的回调函数
func (table *CacheTable) SetDeleteCallback(f func(*CacheItem)) {
func (table *Table) SetDeleteCallback(f func(*Item)) {
table.Lock()
defer table.Unlock()
table.deleteCallback = f
}
//终结检查,被自调整的时间触发
func (table *CacheTable) checkExpire() {
func (table *Table) checkExpire() {
table.Lock()
if table.cleanupTimer != nil {
table.cleanupTimer.Stop()
@ -204,8 +204,8 @@ func (table *CacheTable) checkExpire() {
}
// 添加缓存项
func (table *CacheTable) Add(key interface{}, duration time.Duration, data interface{}) *CacheItem {
item := NewCacheItem(key, duration, data)
func (table *Table) Add(key interface{}, duration time.Duration, data interface{}) *Item {
item := NewItem(key, duration, data)
// 将缓存项放入表中
table.Lock()
@ -231,7 +231,7 @@ func (table *CacheTable) Add(key interface{}, duration time.Duration, data inter
}
// 从缓存中删除项
func (table *CacheTable) Delete(key interface{}) (*CacheItem, error) {
func (table *Table) Delete(key interface{}) (*Item, error) {
table.RLock()
r, ok := table.items[key]
if !ok {
@ -263,7 +263,7 @@ func (table *CacheTable) Delete(key interface{}) (*CacheItem, error) {
}
//单纯的检查某个键是否存在
func (table *CacheTable) Exists(key interface{}) bool {
func (table *Table) Exists(key interface{}) bool {
table.RLock()
defer table.RUnlock()
_, ok := table.items[key]
@ -272,7 +272,7 @@ func (table *CacheTable) Exists(key interface{}) bool {
}
//如果存在返回false. 如果不存在,就去添加一个键并且返回true
func (table *CacheTable) NotFoundAdd(key interface{}, lifeSpan time.Duration, data interface{}) bool {
func (table *Table) NotFoundAdd(key interface{}, lifeSpan time.Duration, data interface{}) bool {
table.Lock()
if _, ok := table.items[key]; ok {
@ -280,7 +280,7 @@ func (table *CacheTable) NotFoundAdd(key interface{}, lifeSpan time.Duration, da
return false
}
item := NewCacheItem(key, lifeSpan, data)
item := NewItem(key, lifeSpan, data)
table.log("Adding item with key %v and lifespan of %v to table", key, lifeSpan)
table.items[key] = item
@ -302,7 +302,7 @@ func (table *CacheTable) NotFoundAdd(key interface{}, lifeSpan time.Duration, da
}
//从缓存中返回一个被标记的并保持活性的值。你可以传附件的参数到DataLoader回调函数
func (table *CacheTable) Value(key interface{}, args ...interface{}) (*CacheItem, error) {
func (table *Table) Value(key interface{}, args ...interface{}) (*Item, error) {
table.RLock()
r, ok := table.items[key]
loadData := table.loadData
@ -330,13 +330,13 @@ func (table *CacheTable) Value(key interface{}, args ...interface{}) (*CacheItem
}
// 删除缓存表中的所有项目
func (table *CacheTable) Truncate() {
func (table *Table) Truncate() {
table.Lock()
defer table.Unlock()
table.log("Truncate table")
table.items = make(map[interface{}]*CacheItem)
table.items = make(map[interface{}]*Item)
table.cleanupInterval = 0
if table.cleanupTimer != nil {
table.cleanupTimer.Stop()
@ -344,31 +344,31 @@ func (table *CacheTable) Truncate() {
}
//辅助table中排序统计的
type CacheItemPair struct {
type ItemPair struct {
Key interface{}
AccessCount int64
}
type CacheItemPairList []CacheItemPair
type ItemPairList []ItemPair
func (p CacheItemPairList) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
func (p CacheItemPairList) Len() int { return len(p) }
func (p CacheItemPairList) Less(i, j int) bool { return p[i].AccessCount > p[j].AccessCount }
func (p ItemPairList) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
func (p ItemPairList) Len() int { return len(p) }
func (p ItemPairList) Less(i, j int) bool { return p[i].AccessCount > p[j].AccessCount }
// 返回缓存表中被访问最多的项目
func (table *CacheTable) MostAccessed(count int64) []*CacheItem {
func (table *Table) MostAccessed(count int64) []*Item {
table.RLock()
defer table.RUnlock()
p := make(CacheItemPairList, len(table.items))
p := make(ItemPairList, len(table.items))
i := 0
for k, v := range table.items {
p[i] = CacheItemPair{k, v.count}
p[i] = ItemPair{k, v.count}
i++
}
sort.Sort(p)
var r []*CacheItem
var r []*Item
c := int64(0)
for _, v := range p {
if c >= count {
@ -387,14 +387,14 @@ func (table *CacheTable) MostAccessed(count int64) []*CacheItem {
// 打印日志
func (table *CacheTable) log(format string, v ...interface{}) {
func (table *Table) log(format string, v ...interface{}) {
//TODO: 全局日志记录
//LOGGER.Info(format, v...)
}
//新建一个缓存Table
func NewCacheTable() *CacheTable {
return &CacheTable{
items: make(map[interface{}]*CacheItem),
func NewTable() *Table {
return &Table{
items: make(map[interface{}]*Item),
}
}

View File

@ -15,3 +15,6 @@ func SafeMethod(f func()) {
//执行函数
f()
}