当前仓库属于暂停状态,部分功能使用受限,详情请查阅 仓库状态说明
1 Star 0 Fork 0

Simbory/mego
暂停

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
sqlSessionProvider.go 1.75 KB
一键复制 编辑 原始数据 按行查看 历史
package mego
import (
"database/sql"
"time"
)
type sqlSessionProvider struct {
driver string
conn string
db *sql.DB
timeout time.Duration
}
func (prov *sqlSessionProvider) Init(timeout time.Duration) error {
prov.timeout = timeout
db, err := sql.Open(prov.driver, prov.conn)
if err != nil {
return err
}
prov.db = db
return nil
}
func (prov *sqlSessionProvider) Read(sid string) SessionStore {
store := &sqlSessionStore{
id: sid,
prov: prov,
newRecord: false,
timeout: prov.timeout,
}
selStmt, err := prov.db.Prepare(`SELECT * FROM session_state WHERE ID=? and Expired>?`)
if err != nil {
panic(err)
}
defer selStmt.Close()
row := selStmt.QueryRow(sid, time.Now())
var id string
var created, updated, expired time.Time
var data = make([]byte, 0)
err = row.Scan(&id, &created, &updated, &expired, &data)
if err != nil {
if err == sql.ErrNoRows {
store.newRecord = true
created = time.Now()
updated = created
expired = created.Add(prov.timeout)
} else {
panic(err)
}
}
store.created = created
store.updated = updated
store.expired = expired
store.init(data)
return store
}
func (prov *sqlSessionProvider) Destroy(sid string) error {
stmt, err := prov.db.Prepare(`DELETE FROM session_state WHERE ID=?`)
if err != nil {
return err
}
res, err := stmt.Exec(sid)
if err != nil {
return err
}
_, err = res.RowsAffected()
return err
}
func (prov *sqlSessionProvider) GC() {
stmt, err := prov.db.Prepare(`DELETE FROM session_state WHERE Expired<=?`)
if err != nil {
return
}
stmt.Exec(time.Now())
}
// NewSQLSessionProvider create a new sql session provider
func NewSQLSessionProvider(driver, conn string) SessionProvider {
return &sqlSessionProvider{
driver: driver,
conn: conn,
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/simbory/mego.git
git@gitee.com:simbory/mego.git
simbory
mego
mego
master

搜索帮助