在 buffalo 中使用 Redis 作为 session 的存储。

buffalo的官方文档中在介绍session部分的时候,比较简单。就是介绍了使用cookie存储的一种方法。

app = buffalo.New(buffalo.Options{
  Env:         ENV,
  SessionName: "_coke_session",
  SessionStore: sessions.NewCookieStore([]byte("some session secret")),
})

但是我们实际的项目中,使用redis或者其他分布式数据库来存储的会比较多。下面就来介绍一下如何使用redis来存储。

我们发现在buffalo的文档中有这么一段注释:

    // SessionStore is the `github.com/gorilla/sessions` store used to back
    // the session. It defaults to use a cookie store and the ENV variable
    // `SESSION_SECRET`.
    SessionStore sessions.Store `json:"-"`

于是我们去 github.com/gorilla/sessions看看,就可以看到他支持很多种存储,不过都需要独立安装。

那就简单了,我们按照 https://github.com/boj/redistore 执行就是了。不过我们需要从环境变量中,获取redis的配置信息。我们在app.go中新加入一个方法:

// init redisstore from env
func newRediStore() (*redistore.RediStore, error){
    return redistore.NewRediStore(
        10,
        envy.Get("REDIS_NETWORK", "TCP"),
        envy.Get("REDIS_ADDRESS", ":6379"),
        envy.Get("REDIS_PASSWORD",  ""),
        []byte(envy.Get("SESSION_SECRET", "apptest")),
    )
}

然后再app.gobuffalo.New时候,修改为:

    if app == nil {
        redisStore, err := newRediStore()
        if err != nil {
            panic(err)
        }

        app = buffalo.New(buffalo.Options{
            Env: ENV,
            SessionStore: redisStore,
            PreWares: []buffalo.PreWare{
                cors.Default().Handler,
            },
            SessionName: "_coke_api_session",
        })
        ......
    }

.env文件中配置环境变量:

REDIS_SIZE=10
REDIS_NETWORK=tcp
REDIS_ADDRESS=:6379
REDIS_PASSWORD=
SESSION_SECRET=appcswwet

这样就OK了,运行项目。访问网站看看没有问题。
同时我们也可以去redis里面看看是不是有了数据。

127.0.0.1:6379> keys session*
1) "session_C6WVOYOSZ5ID62CN7HIQKPOYSYP6VIKXCAMR46KPTOUOIGOQBFMQ"
127.0.0.1:6379> get session_C6WVOYOSZ5ID62CN7HIQKPOYSYP6VIKXCAMR46KPTOUOIGOQBFMQ
"\x0e\xff\x81\x04\x01\x02\xff\x82\x00\x01\x10\x01\x10\x00\x00Z\xff\x82\x00\x02\x06string\x0c\t\x00\a_flash_\a[]uint8\n\x04\x00\x02{}\x06string\x0c\x0e\x00\x0crequestor_id\x06string\x0c\x16\x00\x149986e6d446d91869a8ac"

顺利完成。

superwen
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!