File Storage

By default, the session storage of ghttp.Server uses a combination of memory + file, implemented through the StorageFile object. The specific principles are:

  1. Session data operations are entirely memory-based;
  2. The gcache process caching module controls data expiration;
  3. File storage is used for persistent management of session data;
  4. Session serialization and file persistence storage are executed only when a session is marked as dirty (data has been updated);
  5. Deserialization from file storage to restore session data to memory only occurs when the session does not exist in memory, reducing IO calls;
  6. Serialization/deserialization uses the json.Marshal/UnMarshal methods from the standard library.

As can be seen from the principles, session data operations are very efficient in scenarios with more reads and fewer writes.

Session - File - 图1tip

A detail to note is that because file storage involves file operations, to reduce IO overhead and improve session operation performance, the TTL of the corresponding session is not immediately refreshed after each session request ends. It is only immediately refreshed when it involves update operations (marked as dirty). For read requests, the TTL of the session files corresponding to read operations in the previous minute is updated every one minute, allowing the session to automatically persist.

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/gtime"
  6. "time"
  7. )
  8. func main() {
  9. s := g.Server()
  10. s.SetSessionMaxAge(time.Minute)
  11. s.Group("/", func(group *ghttp.RouterGroup) {
  12. group.ALL("/set", func(r *ghttp.Request) {
  13. r.Session.Set("time", gtime.Timestamp())
  14. r.Response.Write("ok")
  15. })
  16. group.ALL("/get", func(r *ghttp.Request) {
  17. r.Response.Write(r.Session.Data())
  18. })
  19. group.ALL("/del", func(r *ghttp.Request) {
  20. _ = r.Session.RemoveAll()
  21. r.Response.Write("ok")
  22. })
  23. })
  24. s.SetPort(8199)
  25. s.Run()
  26. }

In this instance, to easily observe expiration and invalidation, 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 is set and successfully retrieved;
  3. Next, stop the program, restart it, and visit http://127.0.0.1:8199/get again to see that the session variable has been restored from file storage;
  4. After waiting for 1 minute, visit http://127.0.0.1:8199/get again to see that the session can no longer be retrieved because it has expired.