RedisHashTableStorage

Unlike RedisKeyValueStorage, RedisHashTableStorage uses a HashTable to store Session data at its core. Each addition, deletion, or query operation on Session is directly implemented by accessing the Redis service (single data item operation). There is no full data fetch as in RedisKeyValueStorage, which fetches all data once during initialization and updates all data to the Redis service after modifications when the request ends.

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.NewStorageRedisHashTable(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 example, to conveniently observe expiration, the session expiration time is set to 1 minute. After running:

  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 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 can see that the session variable has been restored from the Redis storage. If we manually modify the corresponding key-value data in Redis, the page refresh will read the latest value;
  4. After waiting for 1 minute, visit http://127.0.0.1:8199/get again and see that the session cannot be retrieved because it has expired.