Groovy Script Using Redis to Pick Conference Lottery Winners

| Comments

At the end of gr8conf today there were quite a few door prize giveaways. Winners were picked using a printout with attendees listed in (I’m assuming) random order. The guys running the lottery were going down the list and calling off names.

This was right after my talk on using Redis with Groovy and I thought to myself, “this is a perfect example of where a quick redis script could automate this and make it a bit more groovy”. So I threw together this script in about 15 minutes:

The majority of the script is just parsing command line options, the redis portion is very small.

It populates a set of conference attendees from a text file if there isn’t already a set of people there (my sample file just uses conference speakers:

if (!redis.exists("conference-attendees")) {
    new File("./conference-attendees.txt").eachLine { redis.sadd("conference-attendees", it) }
}

Next, it pops a random attendee out of the set of all attendees that haven’t won prizes yet:

def winner = redis.spop("conference-attendees")

It will then add that winner to a hash of prizes mapped to winners.

redis.hset("prize-winners", prize, winner)

The winner is then printed to stdout with println. Pipe the command it through big:

% ./pickLotteryWinner.groovy Groovy in Action 2nd Edition | big

and you’ll get something like this:

If someone isn’t around to claim the prize, just run the script again with that same prize and it’ll replace the last person picked in the hash of prizes to winners.

Forget who won a prize? Just run it with -l to list all prize winners so far:

def printPrizeWinner(prize, winner) { println "$winner wins $prize" }
...
if (options.'list') {
    def prizeWinners = redis.hgetAll("prize-winners")
    println "Prize winners so far:"
    prizeWinners.each { prize, winner -> printPrizeWinner(prize, winner) }
    System.exit(0)
}

Pipe that through big and you’ll get this:

I love how flexible Redis is, and how easy it makes solving problems. If I had been given this problem before redis, I probably would have hacked together something ugly that persisted/read JSON from the file system or maybe a small grails app with Prizes and Winners. With redis, this is a 15 minute problem (and an hour blog post :), instead of a problem that takes an hour or two to solve.

Comments