当前位置:网站首页>Gin framework uses session and redis to realize distributed session & Gorm operation mysql
Gin framework uses session and redis to realize distributed session & Gorm operation mysql
2022-07-24 09:21:00 【Naughty cat M】
Use Session And based on redis Implement distributed session
One . Environmental preparation
because gin The framework does not support session, So we need to introduce third-party dependencies .
go get -u github.com/gin-contrib/sessions
go get -u github.com/gin-contrib/sessions/cookie
Copy code Two . Middleware configuration
r := gin.Default()
//NewStore Create based on cookie Storage engine for ,secret123 Is the key used for encryption
store := cookie.NewStore([]byte("secret123"))
// To configure session middleware
r.Use(sessions.Sessions("mySession", store))
Copy code 3、 ... and .session stay http Set when requested
r.GET("/hello", func(context *gin.Context) {
session := sessions.Default(context)
session.Set("userName",123)
session.Save()
// dosomething
})
Copy code Pay attention to calling after storage Save Method .
Four .session stay http Read on request
r.GET("/hello", func(context *gin.Context) {
session := sessions.Default(context)
session.Get("userName")
// dosomething
})
Copy code 5、 ... and . Set up session Parameters
option := sessions.Options{MaxAge: 3600}
session.Options(option)
Copy code there MaxAge The unit is seconds . Options Other parameters are as follows
6、 ... and . be based on redis Implement distributed session
6.1. First introduce
go get -u github.com/gin-contrib/sessions/redis
Copy code 6.2 To configure gin
// be based on redis Of session To configure
store, _ := redis.NewStore(10, "tcp", "localhost:6379", "", []byte("secret"))
r.Use(sessions.Sessions("mySession", store))
Copy code After configuration, the distributed session Configuration of . When multiple nodes request access , according to sessionId Can get the same redis in key Corresponding session Information .
GORM operation MySQL
One . Environmental preparation
go get -u gorm.io/gorm
go get -u gorm.io/driver/sqlite
Copy code Two . Database connection configuration
db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
if err != nil {
panic("failed to connect database")
}
Copy code 3、 ... and . Definition Model
Note that the database field corresponds to model, The first letter should be capitalized
package models
// Structure names are capitalized
type User struct { // The default corresponding table name is users
Id int
Name string
AddTime int // The database field is add_time
}
// Specify the corresponding database table name
func (User) TableName() string {
return "user"
}
Copy code - Note that the first letter of the structure name needs to be capitalized .
- The field name should use the hump rule .
- By default, the database table corresponding to the structure name is the negative number of the structure name
users. You can write aTableNameMethod manually indicates the database table of the corresponding operation .
Four . Database operation
gorm Mainly skilled process , There are not many shortcuts . Follow the official documents to practice proficiency .
grom file : GORM guide
This article is participating in Technical topics 18 period - Chat Go Language framework
边栏推荐
- The next stop of data visualization platform | gifts from domestic open source data visualization datart "super iron powder"
- What is the component customization event we are talking about?
- Promise基础总结
- Getting started with web security - open source firewall pfsense installation configuration
- Attack and defense world ----- confusion1
- Gnuplot software learning notes
- 链表——19. 删除链表的倒数第 N 个结点
- [Luogu p5829] [template] mismatch tree (string) (KMP)
- 【翻译】使用gRPC和REST的微服务架构中的集成挑战
- Leetcode question brushing series -- 174. Dungeon games
猜你喜欢

Aruba learning notes 06 wireless control AC basic configuration (CLI)

One year after I came to Ali, I ushered in my first job change

js定位大全获取节点的兄弟,父级,子级元素含robot实例

《动手学深度学习》(七) -- 边界框和锚框
![[don't bother to strengthen learning] video notes (II) 1. What is Q-learning?](/img/4f/809adc96e30fad03a113acc3df4b61.png)
[don't bother to strengthen learning] video notes (II) 1. What is Q-learning?

dp最长公共子序列详细版本(LCS)

Virtual machine terminator terminal terminator installation tutorial
![[don't bother to strengthen learning] video notes (III) 3. SARS (lambda)](/img/3b/981bd564a5855a317ccdd4800871ce.png)
[don't bother to strengthen learning] video notes (III) 3. SARS (lambda)

Matlab各函数说明

Detailed explanation of the whole process of R & D demand splitting | agile practice
随机推荐
Tiktok's "online celebrity" was poached by Amazon and broadcast on Amazon live platform
JUC powerful auxiliary class
我们说的组件自定义事件到底是什么?
Foreign lead operation takes one month to collect money, and the sideline still needs it
Es search summary
TiFlash 源码阅读(五) DeltaTree 存储引擎设计及实现分析 - Part 2
[Luogu p5410] [template] extend KMP (Z function) (string)
【汇编语言实战】(二)、编写一程序计算表达式w=v-(x+y+z-51)的值(含代码、过程截图)
TCP triple handshake connection combing
Android system security - 5.3-apk V2 signature introduction
[example of URDF exercise based on ROS] use of four wheeled robot and camera
Xtrabackup realizes full backup and incremental backup of MySQL
Account 1-3
With 8 years of product experience, I have summarized these practical experience of continuous and efficient research and development
Paclitaxel loaded tpgs reduced albumin nanoparticles /ga-hsa gambogic acid human serum protein nanoparticles
Aruba learning notes 06 wireless control AC basic configuration (CLI)
Vim: extend the semantic analysis function of YCM for the third-party library of C language
[leetcode] 31. Next arrangement
xtrabackup 实现mysql的全量备份与增量备份
What does CRM mean? Three "key points" for CRM management software selection