Skip to content

Instantly share code, notes, and snippets.

@gigq
Created October 30, 2013 20:25
Show Gist options
  • Save gigq/7239615 to your computer and use it in GitHub Desktop.
Save gigq/7239615 to your computer and use it in GitHub Desktop.
Moves redis list items from a source list to a target list one item at a time. Useful if you use lists as queues and can't rename the key because that would wipe out items in the target queue.
package main
import (
"flag"
"log"
"menteslibres.net/gosexy/redis"
"os"
"os/signal"
"time"
)
func main() {
source := flag.String("source", "", "source redis list")
target := flag.String("target", "", "target redis list")
limit := flag.Int("limit", 0, "max number of items to move")
flag.Parse()
if *source == "" || *target == "" {
flag.PrintDefaults()
os.Exit(1)
}
// capture ctrl+c and exit (useful if we later want to ensure we don't die inbetween an op)
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func() {
for sig := range c {
log.Printf("captured %v, exiting..", sig)
os.Exit(1)
}
}()
client := getClient()
count := 0
for {
if *limit > 0 && count >= *limit {
log.Printf("Limit of %d reached, exiting", *limit)
break
}
if count%100 == 0 {
log.Println(count)
}
data, err := client.LPop(*source)
if err != nil {
log.Fatalf("LPop failed %s\n", err.Error())
os.Exit(1)
}
if data == "" {
log.Println("No more data")
break
}
client.LPush(*target, data)
count = count + 1
// sleep to throttle how fast we move from one list to the other
time.Sleep(time.Millisecond * 2)
}
log.Printf("finished moving %d items from %s to %s", count, *source, *target)
}
func getClient() *redis.Client {
client := redis.New()
err := client.Connect("127.0.0.1", 6379)
if err != nil {
log.Fatalf("Connect failed: %s\n", err.Error())
return nil
}
return client
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment