Python RabbitMQ on Lambda

winmeanyoung 2018-12-04

PythonRabbitMQonLambda

Checkingofficialdocuments

https://github.com/benjamin-hodgson/asynqp

MoredetailintheAPIdocument

https://asynqp.readthedocs.io/en/v0.4/reference.html#connecting-to-the-amqp-broker

Thatisthebasicmethodinpython

importasyncio

importasynqp

@asyncio.coroutine

defhello_world():

"""

Sendsa'helloworld'messageandthenreadsitfromthequeue.

"""

#connecttotheRabbitMQbroker

connection=yieldfromasynqp.connect('localhost',5672,username='guest',password='guest')

#Openacommunicationschannel

channel=yieldfromconnection.open_channel()

#Createaqueueandanexchangeonthebroker

exchange=yieldfromchannel.declare_exchange('test.exchange','direct')

queue=yieldfromchannel.declare_queue('test.queue')

#Bindthequeuetotheexchange,sothequeuewillgetmessagespublishedtotheexchange

yieldfromqueue.bind(exchange,'routing.key')

#IfyoupassinadictitwillbeautomaticallyconvertedtoJSON

msg=asynqp.Message({'hello':'world'})

exchange.publish(msg,'routing.key')

#Synchronouslygetamessagefromthequeue

received_message=yieldfromqueue.get()

print(received_message.json())#getJSONfromincomingmessageseasily

#Acknowledgeadeliveredmessage

received_message.ack()

yieldfromchannel.close()

yieldfromconnection.close()

if__name__=="__main__":

loop=asyncio.get_event_loop()

loop.run_until_complete(hello_world())

event_loop:endlessloop

coroutine:asyncfunction,itwillbebindtoevent_loop,event_loopwillrunthat.

task:statusofcoroutine

future:similartotask

async/await:asynccoroutine,awaitblockandwaitforresult

Oneexampletounderstand:

Importasyncio

Importtime

Now=lambda:time.time()

asyncdefdo_some_work(x):

print(‘waiting:‘,x)

start=now()

coroutine=do_some_work(2)

loop=asyncio.get_event_loop()

task=loop.create_task(coroutine)

print(task)

loop.run_until_complete(task)

print(task)

print(’Time:‘,now()-start)

Results

<Taskpendingcoro=<do_some_work()runningat/

Waiting:2

<Taskfinishedcoro=<do_some_work()done,definedatresult=None>

TIME:0.0003490447998046875

Veryusefuldetailshere

https://www.jianshu.com/p/b5e347b3a17c

References:

https://github.com/benjamin-hodgson/asynqp

https://asynqp.readthedocs.io/en/v0.4/

https://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html

https://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-context.html

https://aws.amazon.com/blogs/compute/container-reuse-in-lambda/

https://asynqp.readthedocs.io/en/v0.4/reference.html#connecting-to-the-amqp-broker

https://www.jianshu.com/p/b5e347b3a17c

https://lotabout.me/2017/understand-python-asyncio/

相关推荐