Solace PubSub+ Python API
The `solace-pubsubplus` library provides a Python API for interacting with Solace PubSub+ event brokers. It supports publishing and subscribing to messages, managing topics, queues, and handling various messaging patterns. Currently at version 1.11.0, it follows a regular release cadence with updates for new features and bug fixes, typically aligning with Solace PubSub+ broker releases.
Common errors
-
solace_pubsubplus.SolaceConnectionException: Connection refused
cause The Solace PubSub+ broker is either not running, the provided host/port is incorrect, or a firewall is blocking the connection.fixVerify that the Solace PubSub+ broker is running and accessible. Check the `SOLACE_HOST` and `SOLACE_VPN` settings for typos (e.g., ensure host includes the port like `localhost:55555`). Review firewall rules on both client and broker machines. -
solace_pubsubplus.SolaceAuthenticationException: Authentication failed
cause The username, password, or VPN name provided in the `SolaceSessionProperties` is incorrect or unauthorized.fixDouble-check the `SOLACE_USERNAME`, `SOLACE_PASSWORD`, and `SOLACE_VPN` values against your broker's configuration. Ensure the user has permissions to connect to the specified VPN. -
ModuleNotFoundError: No module named 'solace_pubsubplus'
cause The `solace-pubsubplus` package has not been installed in the current Python environment.fixInstall the package using pip: `pip install solace-pubsubplus`. -
solace_pubsubplus.SolaceOperationException: Subscription already exists
cause An attempt was made to subscribe to a topic that the session is already subscribed to.fixEnsure that your application logic does not attempt to subscribe to the same topic multiple times on the same session. If dynamic topic changes are needed, explicitly unsubscribe before resubscribing.
Warnings
- gotcha The SolaceSession object is generally not thread-safe. Interactions with the session (connect, disconnect, publish, subscribe, etc.) should be performed from a single thread or carefully synchronized to avoid race conditions and undefined behavior.
- gotcha Message receive callbacks execute on an internal client thread. Blocking operations within these callbacks can prevent other messages from being processed or halt the client's internal event loop, leading to performance issues or deadlocks.
- gotcha It's crucial to explicitly manage the `DeliveryMode` for messages. `DeliveryMode.DIRECT` offers high performance but no guaranteed delivery, while `DeliveryMode.PERSISTENT` ensures guaranteed delivery but with higher overhead. The default might be `DIRECT`.
- gotcha Forgetting to call `session.disconnect()` can leave open connections, consume broker resources, and prevent the client from gracefully cleaning up.
Install
-
pip install solace-pubsubplus
Imports
- SolaceSession
from solace_pubsubplus import SolaceSession
- Message
from solace_pubsubplus import Message
- Subscription
from solace_pubsubplus import Subscription
- SolaceSessionProperties
from solace_pubsubplus import SolaceSessionProperties
- DeliveryMode
from solace_pubsubplus import DeliveryMode
Quickstart
import os
import time
import threading
from solace_pubsubplus import SolaceSession, SolaceSessionProperties, Message, MessageBuilder, DeliveryMode, Subscription, SubscribeFlags, SolaceLogLevel
# Configuration from environment variables
SOLACE_HOST = os.environ.get("SOLACE_HOST", "localhost:55555") # e.g., 'tcp://your_broker_host:55555'
SOLACE_VPN = os.environ.get("SOLACE_VPN", "default")
SOLACE_USERNAME = os.environ.get("SOLACE_USERNAME", "username")
SOLACE_PASSWORD = os.environ.get("SOLACE_PASSWORD", "password")
TOPIC_NAME = "python/quickstart/hello"
# Global lock for thread-safe printing
print_lock = threading.Lock()
def on_message_received(message: Message):
"""Callback function for received messages."""
with print_lock:
print(f"Received message on topic '{message.get_destination_as_topic()}'")
if message.get_data():
print(f"Message data: {message.get_data().decode('utf-8')}")
def run_quickstart():
# 1. Configure Solace Session Properties
session_properties = SolaceSessionProperties()
session_properties.host = SOLACE_HOST
session_properties.vpn_name = SOLACE_VPN
session_properties.username = SOLACE_USERNAME
session_properties.password = SOLACE_PASSWORD
session_properties.connect_retries = 3
session_properties.reconnect_retries = 3
# Set log level for more detailed output (optional)
SolaceSession.set_log_level(SolaceLogLevel.INFO)
session = None
try:
# 2. Create and Connect the Solace Session
session = SolaceSession(session_properties)
session.connect()
with print_lock:
print(f"Connected to Solace PubSub+ broker at {SOLACE_HOST}")
# 3. Set up Message Callback
session.set_message_receive_callback(on_message_received)
# 4. Subscribe to a Topic
subscription = Subscription(TOPIC_NAME)
session.subscribe(subscription, SubscribeFlags.WAIT_FOR_CONFIRM)
with print_lock:
print(f"Subscribed to topic '{TOPIC_NAME}'")
# 5. Publish a Message
message_builder = MessageBuilder()
message = message_builder \
.with_delivery_mode(DeliveryMode.DIRECT) \
.with_topic(TOPIC_NAME) \
.with_property("user-property", "value") \
.build()
message.set_data(f"Hello from Python Quickstart! Timestamp: {time.time()}".encode('utf-8'))
session.publish(message)
with print_lock:
print(f"Published message to topic '{TOPIC_NAME}'")
# 6. Wait briefly for the message to be received (if publishing to self)
time.sleep(2)
except Exception as e:
with print_lock:
print(f"An error occurred: {e}")
finally:
if session:
# 7. Disconnect the Session
with print_lock:
print("Disconnecting Solace Session...")
session.disconnect()
with print_lock:
print("Disconnected.")
if __name__ == "__main__":
run_quickstart()