Cache 中间件

Cache 中间件让你的应用可以非常简单的将对象保存到各种临时或者永久存储中。包括 memory, file, Redis, Memcache, PostgreSQL, MySQL, Ledis and Nodb.

安装

  1. go get github.com/tango-contrib/cache

默认使用memory存储

  1. package main
  2. import (
  3. "github.com/lunny/log"
  4. "github.com/lunny/tango"
  5. "github.com/tango-contrib/cache"
  6. )
  7. func main() {
  8. app := tango.Classic(log.Std)
  9. app.Use(cache.New())
  10. app.Get("/", new(Action))
  11. app.Run()
  12. }
  13. type Action struct {
  14. cache.Cache
  15. }
  16. func (this *Action) Get() interface{} {
  17. //写缓存,参数:键名,键值,生命期(秒)
  18. this.Cache.Put("test", "Hello Tango!", 20)
  19. //读取缓存
  20. return this.Cache.Get("test")
  21. }

使用redis存储

  1. package main
  2. import (
  3. "github.com/lunny/log"
  4. "github.com/lunny/tango"
  5. "github.com/tango-contrib/cache"
  6. _ "github.com/tango-contrib/cache-redis"
  7. )
  8. func main() {
  9. app := tango.Classic(log.Std)
  10. cacheOptions := cache.Options{
  11. Adapter: "redis",
  12. AdapterConfig: "addr=127.0.0.1:6379,prefix=cache:",
  13. }
  14. app.Use(cache.New(cacheOptions))
  15. app.Get("/", new(Action))
  16. app.Run()
  17. }
  18. type Action struct {
  19. cache.Cache
  20. }
  21. func (this *Action) Get() interface{} {
  22. this.Cache.Put("test", "Hello Tango!", 20)
  23. return this.Cache.Get("test")
  24. }