Created
March 23, 2015 07:44
-
-
Save hirokazumiyaji/106c1114a81b2ac9fbbc to your computer and use it in GitHub Desktop.
Redis Sorted Set Sample(LastSignin)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"time" | |
"github.com/m4rw3r/uuid" | |
"gopkg.in/redis.v2" | |
) | |
var client = redis.NewTCPClient(&redis.Options{Addr: "127.0.0.1:6379"}) | |
var Location, _ = time.LoadLocation("Asia/Tokyo") | |
const LastSigninKey = "USER:LASTSIGNIN" | |
▽ | |
type UserLastSignin struct { | |
▽ | |
lastSignedin time.Time | |
} | |
type User struct { | |
Id string | |
UserLastSignin | |
} | |
func (u *User) LastSignedin() time.Time { | |
if u.lastSignedin.IsZero() { | |
result := client.ZScore(LastSigninKey, u.Id) | |
return time.Unix(int64(result.Val()), 0).In(Location) | |
} else { | |
return u.lastSignedin | |
} | |
} | |
func (u *User) Touch() error { | |
now := time.Now() | |
u.lastSignedin = now.In(Location) | |
result := client.ZAdd(LastSigninKey, redis.Z{Member: u.Id, Score: float64(now.Unix())}) | |
return result.Err() | |
} | |
func main() { | |
var ids []string | |
for i := 0; i < 10; i++ { | |
id, _ := uuid.V4() | |
ids = append(ids, id.String()) | |
u := User{Id: id.String()} | |
time.Sleep(time.Second) | |
u.Touch() | |
} | |
for _, id := range ids { | |
u := User{Id: id} | |
fmt.Println(u.Id, u.LastSignedin()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment