[Nguyen Minh Hoang]_Create db_to_gorm.go_Week 2#27
[Nguyen Minh Hoang]_Create db_to_gorm.go_Week 2#27NemCaBong wants to merge 2 commits intoEngineerProOrg:scott/sample-gormfrom
Conversation
| } | ||
| func generateSessionID() string { | ||
| // tạo ra 1 session ID ngẫu nhiên | ||
| return fmt.Sprintf("%d", time.Now().UnixNano()) |
There was a problem hiding this comment.
generate session id like this is not random, and may cause collision a lot, can use a hash function from user_name + timestamp, or uuid
| // HSet được sử dụng để lưu trữ một cặp khóa-giá trị trong một hash (bảng băm) của Redis | ||
| // khóa là sessionID còn "username"->field, username->value | ||
| // err := redisClient.HSet(redisClient.Context(), sessionID, "username", username, "password", password).Err() | ||
| err := redisClient.Set(redisClient.Context(), sessionID, username, 0).Err() |
There was a problem hiding this comment.
should set an expire time for this session data
| // lưu | ||
| c.JSON(http.StatusOK, gin.H{ | ||
| "message": "Login successful", | ||
| "session_id": sessionID, |
There was a problem hiding this comment.
session id is usually stored on header with field Set-Cookie but not body. Can use c.SetCookie function which provided by gin
| } | ||
| func pingHandler(c *gin.Context) { | ||
| // the sessionID will be saved as session_id | ||
| sessionID := c.Query("session_id") |
There was a problem hiding this comment.
same here, session id should be get from header
| // Check if the session ID is valid | ||
| // look up in the redis cached | ||
| // Result() sẽ trả về giá trị value với key cung cấp và err | ||
| userName, err := redisClient.Get(redisClient.Context(), sessionID).Result() |
There was a problem hiding this comment.
should generate a new context for every request something like context.WithTimeout(context.Background(), time.MilliSecond*50)
| } | ||
|
|
||
| // đặt khóa để chỉ 1 người /ping được 1 lúc mà thôi | ||
| mutex.Lock() |
There was a problem hiding this comment.
what happen if we have more than 2 instances, then there're 2 people can ping at a same time if you use this mutext. What we suppose to do here is a distributed lock implemented by redis
| // giảm số redis query | ||
| // lru.Cache.Get() sẽ lấy khóa callCountKey có dạng call_count:<userName | ||
| // rồi trả về value của key đó nếu không trả về nil | ||
| callCount, _ := lruCache.Get(callCountKey) |
There was a problem hiding this comment.
same here, we suppose to do here is using redis to store call count, because if you use this lruCache, it will only store in local memory, if we have more than 2 instances, the total count is wrong
No description provided.