Skip to content

Instantly share code, notes, and snippets.

@codemartial
Last active April 24, 2018 12:02
Show Gist options
  • Save codemartial/2dc53caf7f467b40487a5d9a6354b650 to your computer and use it in GitHub Desktop.
Save codemartial/2dc53caf7f467b40487a5d9a6354b650 to your computer and use it in GitHub Desktop.
Co-ordinated Cache Filling using Redis Distributed Locks
package main
import (
"fmt"
"github.com/gomodule/redigo/redis"
redsync "gopkg.in/redsync.v1"
"sync"
"sync/atomic"
"time"
)
var pool *redis.Pool
var rs *redsync.Redsync
const slowProcessAvg time.Duration = time.Second
const slowProcessMax time.Duration = time.Second * 10
func init() {
// SET UP REDIS POOL
pool = &redis.Pool{
MaxIdle: 3,
IdleTimeout: 10 * time.Second,
Dial: func() (redis.Conn, error) {
c, err := redis.Dial("tcp", "localhost:6379")
if err != nil {
return nil, err
}
return c, err
},
}
// SET UP MUTEX CONNECTIONS
rs = redsync.New([]redsync.Pool{pool})
}
// DUMMY SLOW DATA SOURCE
func SlowProcess(caller int64) int64 {
time.Sleep(time.Second)
fmt.Println("Caller", caller, "invoked SlowProcess")
return caller
}
// CACHE VARIABLE
var cache_key int64 // 0 => empty cache
func getCacheUncoordinated(caller int64) int64 {
var v int64
if v = atomic.LoadInt64(&cache_key); v != 0 {
return v
}
// Cache Miss
fillCache(caller)
return atomic.LoadInt64(&cache_key)
}
func getCacheCoordinated(caller int64) int64 {
var v int64
fillRetryCount := 3
for i := 0; i < fillRetryCount; i++ {
if v = atomic.LoadInt64(&cache_key); v != 0 {
return v
}
// Cache Miss
mutex := rs.NewMutex("demo", redsync.SetExpiry(slowProcessMax), redsync.SetTries(1))
if err := mutex.Lock(); err != nil {
time.Sleep(slowProcessAvg)
continue // Couldn't obtain global lock. Retry
}
// Lock obtained. Fill Cache and remember to unlock mutex.
defer mutex.Unlock()
fillCache(caller)
break
}
return atomic.LoadInt64(&cache_key)
}
func fillCache(caller int64) {
// Check again if the cache is available
if atomic.LoadInt64(&cache_key) != 0 {
return
}
// Call SlowProcess to get a value for cache
v := SlowProcess(caller)
atomic.StoreInt64(&cache_key, v)
}
func main() {
var wg sync.WaitGroup
fmt.Println("UNCOORDINATED CACHE FILL BEGIN")
wg.Add(10)
for i := 1; i <= 10; i++ {
go func(i int) {
defer wg.Done()
getCacheUncoordinated(int64(i))
}(i)
}
wg.Wait()
fmt.Println("Cached value:", cache_key)
fmt.Println("UNCOORDINATED CACHE FILL END\n\n")
cache_key = 0
fmt.Println("COORDINATED CACHE FILL BEGIN")
wg.Add(10)
for i := 1; i <= 10; i++ {
go func(i int) {
defer wg.Done()
getCacheCoordinated(int64(i))
}(i)
}
wg.Wait()
fmt.Println("Cached value:", cache_key)
fmt.Println("COORDINATED CACHE FILL END")
}
/*
The MIT License
Copyright (c) 2018 Tahir Hashmi
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment