其實官網的講解已經很詳細了, 我這里只是演練一下,https://beego.me/docs/mvc/controller/session.md;分兩部分1, 是redis session的使用,2是看看redis session 是否和其他語言一樣 都阻塞
使用
1.首先需要在配置文件app.conf 啟用session, 設置如下:sessionon = true
2在main.go 文件中最添加代碼
beego.BConfig.WebConfig.Session.SessionProvider = "redis" beego.BConfig.WebConfig.Session.SessionProviderConfig = "127.0.0.1:6379"
當然要記得引用包 _ “github.com/astaxie/beego/session/redis”
我們在controller代碼如下:
func (c *MainController) Get() { v := c.GetSession("asta") if v == nil { c.SetSession("asta", int(1)) c.Data["num"] = 0 } else { c.SetSession("asta", v.(int)+1) c.Data["num"] = v.(int) } c.TplName = "index.tpl" }
訪問頁面如圖, http返回中有cookie, 同時redis 也確實有該值
驗證阻塞
修改controller文件 增加幾個方法V2-V5 和V1的方法完全一樣
添加路由配置router.go文件init方法
beego.Router("/v1", &controllers.MainController{}, "GET:V1") beego.Router("/v2", &controllers.MainController{}, "GET:V2") beego.Router("/v3", &controllers.MainController{}, "GET:V3") beego.Router("/v4", &controllers.MainController{}, "GET:V4") beego.Router("/v5", &controllers.MainController{}, "GET:V5")
修改頁面讓它通過ajax訪問接幾個接口
<body> <div>{{.num}}</div> <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script> <input type="button" value="ajax call" id="idajax"/> <script> $("#idajax").click(function(){ $.get("http://localhost:8080/v1"); $.get("http://localhost:8080/v2"); $.get("http://localhost:8080/v3"); $.get("http://localhost:8080/v4"); $.get("http://localhost:8080/v5"); }); </script> </body>
點擊按鈕 運行效果。從運行效果上看 並不像。net 那樣有阻塞
當然沒有阻塞也有一些問題, 比如v1讀取session 然后保存session, 在保存前v2不僅讀取了seeion 然后做了修改, 那么v1在保存的時候就會覆蓋v2保存的session數據。