Skip to content

Instantly share code, notes, and snippets.

@hirokazumiyaji
Created March 23, 2015 07:44
Show Gist options
  • Save hirokazumiyaji/106c1114a81b2ac9fbbc to your computer and use it in GitHub Desktop.
Save hirokazumiyaji/106c1114a81b2ac9fbbc to your computer and use it in GitHub Desktop.
Redis Sorted Set Sample(LastSignin)
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