Golang Web Development Session cache: How do I use Redigo to save a struct data to Redis?

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed. Custom session Structure:
Type Session struct {SessionID  string        ' json: ' SessionID ' Bson: ' SessionID ' ' User       *user         ' json: '-' Bson: "User" ' Usertype   string        ' JSON: "Usertype" Bson: "usertype" ' nickname   string        ' JSON: "nickname" Bson: " Nickname "' Createtime time. Time     ' JSON: "-" Bson: "Createtime" ' UpdateTime time. Time     ' JSON: "-" Bson: "UpdateTime" ' Expires time    . Time     ' JSON: '-' Bson: ' Expires ' locale     string        ' json: '-' Bson: ' Locale '//default is Zh_cnmenus      [] Wmodel. Menu ' JSON: ' Menus ' bson: ' Menus '}

1. Save the session

Use JSON. Marshal the structure to Redis after JSON:

/* "Add" description: Insert a Session object session top key, top key can set expiration time <[session]: Session object to insert >[error]: Insert failure related information */func (s *session Service) Setsession (Session *model. Session) Error {//Get connection from Pool conn: = Pool. Get () If conn = = nil {log. Errorf ("Redis connnection is nil") return errors. New ("Redis connnection is nil")}//the connection back to the connection pool defer conn after the run-out. Close ()//convert session to JSON data, note: The converted value is a byte array of value, err: = json. Marshal (session) If err! = Nil {log. Errorf ("JSON Marshal err,%s", err) return Err}log.infof ("Send data[%s]", session. SessionID, value) _, Err = conn. Do ("SET", session.) SessionID, value, "EX", sessiontimeoutinseconds) if err! = Nil {return Err}return nil}

Golang Test Validation:

Func testsetsession (t *testing. T) {s: = &model. Session{sessionid: "20150421120000", Usertype:  "admin", Nickname:  "DF",}err: = Sessionservice.setsession (s) If err! = Nil {T.errorf ("fail to add one session (%+V):%s", S, err) T.failnow ()}}

The Redis client looks at the session Save:


2. Deletion of Session

Remote Call DEL command via Redigo driver:

/* "Delete" description: Deletes a Session object session top key, normally the session will expire in 30 minutes after the user has no operation, but the user log out operation can be deleted in advance, this is where this method is called <[sessi Onid]: Id>[error of the Session object to be deleted]: Delete failure related information */func (S *sessionservice) delsession (SessionID string) (err Error) {//received from dominant FETCH Connection Conn: = Pool. Get () If conn = = nil {log. Errorf ("Redis connnection is nil") return errors. New ("Redis connnection is nil")}//the connection back to the connection pool defer conn after the run-out. Close () log.infof ("Move data[%s", SessionID) _, err = conn. Do ("DEL", SessionID) if err! = Nil {return Err}return nil}
Golang Test Validation:

Func testdelsession (t *testing. T) {err: = Sessionservice.delsession ("20150421120000") if err! = Nil {T.errorf ("fail to delete one session (%s):%s", "20150 421120000 ", err) T.failnow ()}}

3. Session Acquisition

Use JSON. Unmarshal restores the structure after serialization:

/* Description: View and return a session entity session top Key<[sessionid]: Id>[error of the Session object to view]: View failure related information */func (s *sessionservic e) getsession (SessionID string) (Session *model. Session, err Error) {//Get connection from Pool conn: = Pool. Get () If conn = = nil {log. Errorf ("Redis connnection is nil") return nil, errors. New ("Redis connnection is nil")}//the connection back to the connection pool defer conn after the run-out. Close () log. Infof ("exists data[%s]", SessionID)//See if the session exists Var ifexists boolifexists, err = sessionservice.existssession ( SessionID) If err! = Nil {log. Errorf ("fail to exists one session (%s):%s", SessionID, err) return nil, errors. New ("Session not exists, SessionID:" + SessionID)}if ifexists {//JSON data is []byte type] in go, so use redis here. Bytes Conversion valuebytes, ERR2: = Redis. Bytes (Conn. Do ("GET", SessionID)) if err2! = Nil {return nil, err2}//log. Infof ("Receive data[%s]:%s", SessionID, String (valuebytes)) session = &model. Session{}err = json. Unmarshal (Valuebytes, session) if err! = Nil {return nil, Err}return session, nil} else {return nil, errors. New ("SessIon not exists, SessionID: "+ SessionID)}} 
Golang Test Validation:

Func testgetsession (t *testing. T) {s, err: = Sessionservice.getsession ("20150421120000") if err! = Nil {T.errorf ("fail to exists one session (%s):%s", "20 150421120000 ", err) T.failnow ()}log. Debug ("session exists, session nickname is:%s", S.nickname)}


Postscript

The Redis author has only allowed us to set the timeout for the top level key in order to maintain a simple schema, and the secondary key (such as each sub key in the Hash) cannot be set to timeout, so we used a single Redis library with index 3 to store s Ession, is convenient management. In addition, we set the key of each session (that is, the key of the top level) to a half-hour validity period to determine and process managed redis, bypassing the complexity of the program's management of the session timeout mechanism-especially the distributed environment.

In addition, this article only provides the session of the increase, delete, check operation, for the session of the modification and validity of the delay operation of the author suggested can be deleted and then added.

Resources

Go:how to save and retrieve a struct to Redis using Redigo
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.