example_test.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package cache_test
  2. import (
  3. "time"
  4. "go-common/library/cache/memcache"
  5. "go-common/library/container/pool"
  6. "go-common/library/ecode"
  7. "go-common/library/net/http/blademaster"
  8. "go-common/library/net/http/blademaster/middleware/cache"
  9. "go-common/library/net/http/blademaster/middleware/cache/store"
  10. xtime "go-common/library/time"
  11. "github.com/pkg/errors"
  12. )
  13. // This example create a cache middleware instance and two cache policy,
  14. // then attach them to the specified path.
  15. //
  16. // The `PageCache` policy will attempt to cache the whole response by URI.
  17. // It usually used to cache the common response.
  18. //
  19. // The `Degrader` policy usually used to prevent the API totaly unavailable if any disaster is happen.
  20. // A succeeded response will be cached per 600s.
  21. // The cache key is generated by specified args and its values.
  22. // You can using file or memcache as cache backend for degradation currently.
  23. //
  24. // The `Cache` policy is used to work with multilevel HTTP caching architecture.
  25. // This will cause client side response caching.
  26. // We only support weak validator with `ETag` header currently.
  27. func Example() {
  28. mc := store.NewMemcache(&memcache.Config{
  29. Config: &pool.Config{
  30. Active: 10,
  31. Idle: 2,
  32. IdleTimeout: xtime.Duration(time.Second),
  33. },
  34. Name: "test",
  35. Proto: "tcp",
  36. Addr: "172.16.33.54:11211",
  37. DialTimeout: xtime.Duration(time.Second),
  38. ReadTimeout: xtime.Duration(time.Second),
  39. WriteTimeout: xtime.Duration(time.Second),
  40. })
  41. ca := cache.New(mc)
  42. deg := cache.NewDegrader(10)
  43. pc := cache.NewPage(10)
  44. ctl := cache.NewControl(10)
  45. filter := func(ctx *blademaster.Context) bool {
  46. if ctx.Request.Form.Get("cache") == "false" {
  47. return false
  48. }
  49. return true
  50. }
  51. engine := blademaster.Default()
  52. engine.GET("/users/profile", ca.Cache(deg.Args("name", "age"), nil), func(c *blademaster.Context) {
  53. values := c.Request.URL.Query()
  54. name := values.Get("name")
  55. age := values.Get("age")
  56. err := errors.New("error from others") // error from other call
  57. if err != nil {
  58. // mark this response should be degraded
  59. c.JSON(nil, ecode.Degrade)
  60. return
  61. }
  62. c.JSON(map[string]string{"name": name, "age": age}, nil)
  63. })
  64. engine.GET("/users/index", ca.Cache(pc, nil), func(c *blademaster.Context) {
  65. c.String(200, "%s", "Title: User")
  66. })
  67. engine.GET("/users/list", ca.Cache(ctl, filter), func(c *blademaster.Context) {
  68. c.JSON([]string{"user1", "user2", "user3"}, nil)
  69. })
  70. engine.Run(":18080")
  71. }