Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ThaiNgocThanhDat] redis excercise only #20

Open
wants to merge 2 commits into
base: scott/sample-gorm
Choose a base branch
from

Conversation

unitoflazy
Copy link

Sorry anh @tpdongcs em chỉ làm excercise của redis thôi còn gorm dùng nhiều ở cty rồi nên hơi ngán ạ 👍


func (s *cacheService) Login(userName string) (string, error) {
ctx := context.Background()
sessionId, err := s.redis.Do(ctx, "incr", "sessionId").Int64()
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this session id generation is accepted, but its better to generate a random id (uuid, or hash from user_name) in real world

}

ctx = context.Background()
err = s.redis.HMSet(ctx, "session", sessionId, userName).Err()
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why dont use a normal key in redis but hash map ? you can group these keys by adding a prefix like session_{session_id} instead. Because usually we need to set an expire time for these session keys, and keys in hash map can't do it

})

r.POST("/ping", func(c *gin.Context) {
var payload types.RequestPayload
Copy link
Collaborator

@tpdongcs tpdongcs Jun 5, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

actually session is should be stored in header (cookie) but not body can see how to set cookie

key := fmt.Sprintf("last-ping-%s", sessionId)
now := time.Now()

selfBlockTime, err := s.redis.Get(ctx, key).Int64()
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is not rate limiter implementation, should use incr and expire instead. If I change the requirement is 5 times / 1 min then your way is incorrect

return err
}
if currentBlockTime < now.Unix() {
err = s.redis.Set(ctx, "global-block", globalBlockTime, globalBlockDuration).Err()
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

still use setnx instead, what happen if more than one guys want to get this lock ? (never use set).
and you need a for loop to retry till you can get it but not one time only like this

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants