Building an Event-Driven Application With RabbitMQ using CloudAMQP and Acorn Services – Part 1
Step 1 – Create an Acorn Job acting as a Publisher
In the previous part, we built an Acorn Service that exposes an instance of RabbitMQ. In the final part, we will build two Acorns – a publisher that periodically publishes messages to the topic and a subscriber that reads from the same topic.
Ensure the Acorn Service is running before proceeding to the next steps.
Create a directory called pub to store all the relevant files for the publisher.
Under src, create the below Python script app.py that publishes to a topic called Hello:
Notice that the script receives the URL with the RabbitMQ endpoint and credentials through the environment variable.
Now, create the Dockerfile for the Python script.
FROM python:alpine3.9 RUN pip install pika==1.1.0 COPY ./src /src ENTRYPOINT ["python","-u","/src/app.py"]
It’s time to define the Acorn that runs this container as a Job. It will be scheduled to publish a message every minute.
We are referencing the Acorn Service already running in the services section of the Acornfile. We then define the job and pass the CLOUDAMQP URL exposed by the Service as an environment variable to the Python script.
Run the Acornfile to kick off the job.
acorn run -n publisher .
You can see that the job is publishing the messages from the logs:
acorn logs -f publisher
While this is running, let’s create the subscriber.
Create a directory called sub to store all the relevant files for the subscriber.
Under src, create the below Python script, app.py, which subscribes to the topic called Hello:
Let’s create the Dockerfile and Acornfile to run the subscriber.
Let’s run the subscriber and watch the logs if the messages are received by it.
acorn run -n subscriber . acorn logs -f subscriber
We can see the messages flowing from the publisher to the subscriber via the RabbitMQ instance running in the cloud.
This tutorial walked you through all the steps involved in publishing Acorn Services and consuming them from multiple Acorns. If you’d like to learn more about getting started with Acorn, view our getting started workshop.