Nsq and Python

Trevor Olson
@ZombieFeynman

Download Nsq

wget https://s3.amazonaws.com/bitly-downloads/nsq/nsq-0.2.28.darwin-amd64.go1.2.1.tar.gz
tar xzf nsq-0.2.28.darwin-amd64.go1.2.1.tar.gz

Run nsqd

cd nsq-0.2.28.darwin-amd64.go1.2.1
./bin/nsqd

Install gnsq

mkvirtualenv nsqdemo
pip install gnsq
In [ ]:
import gnsq
conn = gnsq.Nsqd('localhost', 4150)

Publish a message

curl -d 'hello world!' 'http://127.0.0.1:4151/put?topic=test'
In [ ]:
conn.publish('test', 'hello world!')

Publish lots of messages

In [ ]:
messages = ['{} bottles of beer on the wall'.format(count) for count in xrange(99, 0, -1)]
conn.multipublish('beers', messages)

Read our messages back

In [ ]:
# Read our messages
import gevent
reader = gnsq.Reader('beers', 'singer', nsqd_tcp_addresses=['localhost:4150'])
In [ ]:
@reader.on_message.connect
def sing(reader, message):
    print message.body + '!'
    print message.body + ','
    print message.body + '.'
    print 'Take one down, pass it around...'
    
    if message.body.startswith('1 '):
        print '0 bottles of beer on the wall!!!!!'
        gevent.spawn(reader.close)
In [ ]:
reader.start()