Skip to content

Setting the default messaging backend

To instantiate a publishers or a consumer, you need to pass a MessagingBackend as a constructor argument. Depending on the circumstances, however, this might feel repetitive.

As an alternative, you could use the singleton BackendManager and register a backend for global usage in your initialization code:

BackendManager().set_default_backend(AWSBackend())

From that point forward, any instantiation of a Publisher or Consumer does not need a backend as an argument anymore. Revisiting one of the recurring examples of this documentation, we could use the BackendManager like this.

Usage of the backend manager
from melange.backends import BackendManager
from melange.backends import LocalSQSBackend
from melange.examples.shared import serializer_registry
from melange import QueuePublisher
from melange.serializers import PickleSerializer


class MyTestMessage:
    def __init__(self, message: str) -> None:
        self.message = message


if __name__ == "__main__":
    backend = LocalSQSBackend(host="localhost", port=9324)
    serializer = PickleSerializer()
    BackendManager().set_default_backend(backend)

    publisher = QueuePublisher(serializer_registry)
    message = MyTestMessage("Hello World!")
    publisher.publish("melangetutorial-queue", message)
    print("Message sent successfully!")

Notice that we are not passing the backend now as a parameter when creating the QueuePublisher object, since it will retrieve it from the BackendManager.

Warning

Use the BackendManager with caution though. Singletons are regarded sometimes as an antipattern depending on the situation, and dependency injection is usually regarded as a cleaner solution to construct objects.

Back to top