Token生成器

首先需要調用StartGameServer啓動一個計時器

/**
服務器
*/
package util

import (
	"time"
)

//服務器全局對象
var Server _serverVO

func StartGameServer() {
	//啓動服務器自身的計時器與維護
	Server = _serverVO{}
	Server.TimeSec = time.Now().Unix()
	Server.LocalPath = GetCurrentDirectory()
	ticker := time.NewTicker(1 * time.Second)
	go func() {
		for _ = range ticker.C {
			Server.TimeSec = time.Now().Unix()
			Server.GoTime++
		}
	}()
	//初始化token獲取器
	InitTokenSession()
	Log("開啓服務器時間計時器", "Token獲取器")
}

type _serverVO struct {
	TimeSec   int64  //當前系統時間秒
	GoTime    int64  //當前系統已經運行了多久時間了
	LocalPath string //當前系統的運行目錄
}

//獲取當前系統的毫秒時間
func (this *_serverVO) TimeMillisec() int64 {
	return time.Now().UnixNano() / 1000000
}

//獲取當前系統的納秒時間
func (this *_serverVO) TimeMicro() int64 {
	return time.Now().UnixNano() / 1000
}

之後就可以調用該文件中的各種應用函數了

//token
package util

import (
	"bytes"
	"strconv"
	"sync"
)

var TokenSession *tokenSession

//初始化InitTokenSession
func InitTokenSession() {
	TokenSession = &tokenSession{lastString: strconv.FormatInt(Server.TimeSec, 10), lastServerTime: Server.TimeSec, addTime: 0, pj: "_"}
}

//全局token獲取器
type tokenSession struct {
	lastString     string
	lastServerTime int64
	addTime        int64
	buffer         bytes.Buffer
	pj             string
	sync.Mutex
}

//獲取一個輕量級的Token,不經過md5,主要在程序內部使用
func (this *tokenSession) GetTokenLite() string {
	this.Mutex.Lock()
	defer this.Mutex.Unlock()
	if Server.TimeSec != this.lastServerTime {
		this.addTime = 0
		this.lastServerTime = Server.TimeSec
		this.lastString = strconv.FormatInt(this.lastServerTime, 10)
	} else {
		this.addTime++
	}
	this.buffer.Reset()
	this.buffer.WriteString(this.lastString)
	this.buffer.WriteString(this.pj)
	this.buffer.WriteString(strconv.FormatInt(this.addTime, 10))
	return this.buffer.String()
}

//獲取一個完整的Token,經過md5
func (this *tokenSession) GetTokenMax() string {
	str := this.GetTokenLite()
	return MD5Hex(str)
}

//獲取一個私有的token,經過md5
func (this *tokenSession) GetTokenPrivate(v interface{}) string {
	str := strconv.FormatInt(this.lastServerTime, 10) + this.pj
	switch v.(type) {
	case string:
		str = str + v.(string)
	case int:
		str = str + strconv.Itoa(v.(int))
	case int64:
		str = str + strconv.FormatInt(v.(int64), 10)
	case uint:
		str = str + strconv.FormatUint(uint64(v.(uint)), 10)
	}
	return MD5Hex(str)
}
方法中用到了sync,本人接觸不久不知道是否有什麼安全的又不需要加鎖的方法?
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章