Pub/Sub without CloudEvents
Dapr uses CloudEvents to provide additional context to the event payload, enabling features like:
- Tracing
- Deduplication by message Id
- Content-type for proper deserialization of event’s data
For more information about CloudEvents, read the .
When adding Dapr to your application, some services may still need to communicate via raw pub/sub messages not encapsulated in CloudEvents. This may be for compatibility reasons, or because some apps are not using Dapr. Dapr enables apps to publish and subscribe to raw events that are not wrapped in a CloudEvent.
Warning
Dapr apps are able to publish raw events to pub/sub topics without CloudEvent encapsulation, for compatibility with non-Dapr apps.
To disable CloudEvent wrapping, set the metadata to true
as part of the publishing request. This allows subscribers to receive these messages without having to parse the CloudEvent schema.
from dapr.clients import DaprClient
with DaprClient() as d:
req_data = {
'order-number': '345'
}
# Create a typed message with content type and body
resp = d.publish_event(
pubsub_name='pubsub',
topic='TOPIC_A',
metadata=(
('rawPayload', 'true')
)
)
# Print the request
print(req_data, flush=True)
When subscribing programmatically, add the additional metadata entry for so the Dapr sidecar automatically wraps the payloads into a CloudEvent that is compatible with current Dapr SDKs.
import flask
from flask import request, jsonify
from flask_cors import CORS
import json
import sys
app = flask.Flask(__name__)
CORS(app)
@app.route('/dapr/subscribe', methods=['GET'])
def subscribe():
subscriptions = [{'pubsubname': 'pubsub',
'topic': 'deathStarStatus',
'route': 'dsstatus',
'metadata': {
} }]
return jsonify(subscriptions)
@app.route('/dsstatus', methods=['POST'])
def ds_subscriber():
print(request.json, flush=True)
return json.dumps({'success':True}), 200, {'ContentType':'application/json'}
app.run()
Similarly, you can subscribe to raw events declaratively by adding the rawPayload
metadata entry to your Subscription Custom Resource Definition (CRD):
apiVersion: dapr.io/v1alpha1
kind: Subscription
metadata:
name: myevent-subscription
spec:
topic: deathStarStatus
route: /dsstatus
pubsubname: pubsub
metadata:
rawPayload: "true"
scopes:
- app2
- Learn more about how to publish and subscribe
- Read the