読者です 読者をやめる 読者になる 読者になる

RabbitMQ のテストサーバにつないでみた

amqp_send.py

# vim: fileencoding=utf8

from amqplib import client_0_8 as amqp

kUserId = 'guest'
kPassword = 'guest'
kHost = 'dev.rabbitmq.com'

def main():
  message_body = u'あいうえお'

  connection = amqp.Connection(kHost, userid=kUserId, password=kPassword, ssl=False)

  channel = connection.channel()
  channel.access_request('/data', active=True, write=True)

  channel.exchange_declare('myfan', 'fanout', auto_delete=True)

  kApplicationHeaders = {'foo': 7, 'bar': 'baz'}

  message = amqp.Message(message_body,
      content_type='text/plain', application_headers=kApplicationHeaders)

  channel.basic_publish(message, 'myfan')

  channel.close()
  connection.close()

if __name__ == '__main__':
    main()

amqp_receive.py

# vim: fileencoding=utf8

from amqplib import client_0_8 as amqp

kUserId = 'guest'
kPassword = 'guest'
kHost = 'dev.rabbitmq.com'

def callback(msg):
  for key, val in msg.properties.items():
    print '%s: %s' % (key, str(val))
  for key, val in msg.delivery_info.items():
    print '> %s: %s' % (key, str(val))

  print ''
  print msg.body
  print '-------'
  msg.channel.basic_ack(msg.delivery_tag)

  if msg.body == 'quit':
    msg.channel.basic_cancel(msg.consumer_tag)


def main():
  connection = amqp.Connection(kHost, userid=kUserId, password=kPassword, ssl=False)

  channel = connection.channel()
  channel.access_request('/data', active=True, read=True)

  channel.exchange_declare('myfan', 'fanout', auto_delete=True)
  qname, _, _ = channel.queue_declare()
  channel.queue_bind(qname, 'myfan')
  channel.basic_consume(qname, callback=callback)

  while channel.callbacks:
    channel.wait()

  channel.close()
  connection.close()

if __name__ == '__main__':
  main()