Provides an integration to Azure's Web PubSub service to deliver real-time messages between instances.
You must define a JSON Vault item to use this feature. The data field should be a JSON string containing endpoint
, hub
, group
and access_key
and optional secondary_access_key
:
{"endpoint": "<endpoint>", "hub": "<hub>", "group": "<group>", "access_key": "<access-key>", "secondary_access_key": "<secondary-access-key>"}
Use helfi_api_base.pubsub_manager
service to send real-time messages to other instances:
/** @var \Drupal\helfi_api_base\Azure\PubSub\PubSubManagerInterface $service */
$service = \Drupal::service('helfi_api_base.pubsub_manager')
$data = ['random' => 'data'];
$service->sendMessage($data);
The $data
variable can contain anything that can be converted into a JSON string.
Use drush helfi:azure:pubsub-listen
Drush command to listen to an incoming messages.
The command is run until \Drupal\helfi_api_base\Commands\PubSubCommands::MAX_MESSAGES
(500 by default) is reached and will exit with code 0 to prevent memory leaks.
Alternatively, you can listen to incoming messages using helfi_api_base.pubsub_manager
service:
/** @var \Drupal\helfi_api_base\Azure\PubSub\PubSubManagerInterface $service */
$service = \Drupal::service('helfi_api_base.pubsub_manager')
$service->receive();
See Responding to PubSub messages to see how to respond to incoming messages.
Create an event subscriber that responds to \Drupal\helfi_api_base\Azure\PubSub\Message
events:
<?php
declare(strict_types = 1);
namespace Drupal\yourmodule\EventSubscriber;
use Drupal\helfi_api_base\Azure\PubSub\PubSubMessage;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
final class YourEventSubscriber implements EventSubscriberInterface {
public function onReceive(PubSubMessage $message) : void {
// Logic here.
// $message->data should contain the data passed to '::sendMessage()'.
}
public static function getSubscribedEvents() : array {
return [
PubSubMessage::class => ['onReceive'],
];
}
}
See CacheTagInvalidatorSubscriber for an example implementation.
# public/sites/default/local.settings.php
$pubsub_account = [
'id' => 'pubsub',
'plugin' => 'json',
'data' => json_encode(
'endpoint' => '<endpoint-here>',
'hub' => '<hub>',
'group' => '<group>',
'access_key' => '<access-key>',
'secondary_access_key' => '<secondary-access-key>',
]),
];
$config['helfi_api_base.api_accounts']['vault'][] = $pubsub_account;