Publishing & subscribing messages without CloudEvents

When adding Dapr to your application, some services may still need to communicate via pub/sub messages not encapsulated in CloudEvents, due to either compatibility reasons or some apps not using Dapr. These are referred to as “raw” pub/sub messages. Dapr enables apps to publish and subscribe to raw events not wrapped in a CloudEvent for compatibility.

Dapr apps are able to publish raw events to pub/sub topics without CloudEvent encapsulation, for compatibility with non-Dapr apps.

Warning

Not using CloudEvents disables support for tracing, event deduplication per messageId, content-type metadata, and any other features built using the CloudEvent schema.

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.

  1. from dapr.clients import DaprClient
  2. with DaprClient() as d:
  3. req_data = {
  4. 'order-number': '345'
  5. }
  6. # Create a typed message with content type and body
  7. resp = d.publish_event(
  8. pubsub_name='pubsub',
  9. topic_name='TOPIC_A',
  10. data=json.dumps(req_data),
  11. publish_metadata={'rawPayload': 'true'}
  12. # Print the request
  13. print(req_data, flush=True)

When subscribing programmatically, add the additional metadata entry for rawPayload so the Dapr sidecar automatically wraps the payloads into a CloudEvent that is compatible with current Dapr SDKs.

  1. import flask
  2. from flask_cors import CORS
  3. import json
  4. import sys
  5. app = flask.Flask(__name__)
  6. CORS(app)
  7. @app.route('/dapr/subscribe', methods=['GET'])
  8. def subscribe():
  9. subscriptions = [{'pubsubname': 'pubsub',
  10. 'topic': 'deathStarStatus',
  11. 'route': 'dsstatus',
  12. 'metadata': {
  13. 'rawPayload': 'true',
  14. } }]
  15. @app.route('/dsstatus', methods=['POST'])
  16. print(request.json, flush=True)
  17. return json.dumps({'success':True}), 200, {'ContentType':'application/json'}
  18. app.run()
  1. apiVersion: dapr.io/v1alpha1
  2. kind: Subscription
  3. metadata:
  4. name: myevent-subscription
  5. spec:
  6. topic: deathStarStatus
  7. route: /dsstatus
  8. pubsubname: pubsub
  9. metadata:
  10. rawPayload: "true"
  11. scopes:
  12. - app1
  13. - app2