Redis KeyValue Storage

The file storage method works well in single-node scenarios, but when it comes to deploying an application across multiple nodes, the Session cannot be shared between nodes, making it necessary to separate Session storage for independent management. The Redis server is a common choice.

The gsession Redis storage uses the StorageRedis object, similar to file storage. To improve execution efficiency, it adopts a memory + Redis approach. The only difference from file storage is that if Session operations are needed during each request, the latest Session data will be pulled from Redis (file storage only reads a file once when the Session does not exist). At the end of each request, the entire Session data is serialized using JSON and updated to the Redis service using the KeyValue method.

Session - Redis-KeyValue - 图1tip

For business scenarios where the Session data of each user is not large (taking the user dimension as an example), this storage method is recommended. If the Session data for a single user is large (e.g., >10MB), you can refer to the HashTable storage method: Session - Redis-HashTable

Usage Example

  1. package main
  2. import (
  3. "github.com/gogf/gf/v2/frame/g"
  4. "github.com/gogf/gf/v2/net/ghttp"
  5. "github.com/gogf/gf/v2/os/gsession"
  6. "github.com/gogf/gf/v2/os/gtime"
  7. "time"
  8. )
  9. func main() {
  10. s := g.Server()
  11. s.SetSessionMaxAge(time.Minute)
  12. s.SetSessionStorage(gsession.NewStorageRedis(g.Redis()))
  13. s.Group("/", func(group *ghttp.RouterGroup) {
  14. group.ALL("/set", func(r *ghttp.Request) {
  15. r.Session.Set("time", gtime.Timestamp())
  16. r.Response.Write("ok")
  17. })
  18. group.ALL("/get", func(r *ghttp.Request) {
  19. r.Response.Write(r.Session.Data())
  20. })
  21. group.ALL("/del", func(r *ghttp.Request) {
  22. _ = r.Session.RemoveAll()
  23. r.Response.Write("ok")
  24. })
  25. })
  26. s.SetPort(8199)
  27. s.Run()
  28. }

In this instance, to facilitate observing expiration, we set the Session expiration time to 1 minute. After execution,

  1. First, visit http://127.0.0.1:8199/set to set a Session variable;
  2. Then, visit http://127.0.0.1:8199/get to see that the Session variable has been set and successfully retrieved;
  3. Next, stop the program, restart it, and visit http://127.0.0.1:8199/get again, you will see the Session variable has been restored from Redis storage; if we manually modify the corresponding key-value data in Redis, the latest value will be read when the page is refreshed;
  4. After waiting 1 minute, visiting http://127.0.0.1:8199/get again shows that the Session cannot be retrieved since it has expired;