go beego redis mysql,redis作为cache和session的数据库的使用

package main

import (

_ "./routers"

"fmt"

"github.com/astaxie/beego"

_ "github.com/astaxie/beego/cache/redis"

"github.com/astaxie/beego/cache"

"log"

"time"

)

type hashes struct {

name string

age int

sex int

}

func main() {

//key的作用是在键前面加个:beego:

adapter, err := cache.NewCache("redis", `{"key":"beego","conn":":6379","dbNum":"0","password":""}`)

if err != nil {

log.Fatal(err)

}

err = adapter.Put("account", "张三", 3600 * time.Second)

if err != nil {

log.Fatal(err)

}

fmt.Println(fmt.Sprintf("%s", adapter.Get("account")))

//存数组/hash的方式

err = adapter.Put("hashes", hashes{name:"dingyi", age:18, sex:1}, 3600 * time.Second)

if err != nil {

log.Fatal(err)

}

fmt.Println(fmt.Sprintf("%s", adapter.Get("hashes")))

beego.Run()

}

3de4e4ecb78bb9aaeca98151aa7c2989.png

要安装github.com/gomodule/redigo/redis才能使用(虽然github.com/astaxie/beego/cache/redis继承了它)

要引入的:

"github.com/astaxie/beego/cache"

_ "github.com/astaxie/beego/cache/redis"

session以redis作为存储数据库的方法:

只要很简单的做个配置就行,不需要网上的一大段代码,app.conf:

sessionProvider = redis

sessionProviderConfig = 127.0.0.1:6379,100,

其中127.0.0.1:6379为ip和端口,100为连接池,最后一个空缺的为密码

再加上main方法中的:

beego.BConfig.WebConfig.Session.SessionOn = true

当然,同上,同样需要安装:github.com/gomodule/redigo/redis

5f31c6715834529a5083bca2f46351c4.png