Skip to content
This repository has been archived by the owner on Jul 17, 2024. It is now read-only.

Added optional key parameter to publish #5

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ $adapter->publish('my_channel', 'HELLO WORLD');
$adapter->publish('my_channel', ['hello' => 'world']);
$adapter->publish('my_channel', 1);
$adapter->publish('my_channel', false);
$adapter->publish('my_channel', ['hello' => 'world'], 1);

// publish multiple messages
$messages = [
Expand Down
2 changes: 2 additions & 0 deletions examples/KafkaPublishExample.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,5 @@
for ($x = 0; $x < 10; $x++) {
$adapter->publish('my_channel', $x);
}

$adapter->publish('my_channel', 'With a key', 1);
11 changes: 5 additions & 6 deletions src/KafkaPubSubAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -91,15 +91,14 @@ public function subscribe($channel, callable $handler)
}

/**
* Publish a message to a channel.
*
* @param string $channel
* @param mixed $message
* @param $channel
* @param $message
* @param null $key
*/
public function publish($channel, $message)
public function publish($channel, $message, $key = null)
{
$topic = $this->producer->newTopic($channel);
$topic->produce(RD_KAFKA_PARTITION_UA, 0, Utils::serializeMessage($message));
$topic->produce(RD_KAFKA_PARTITION_UA, 0, Utils::serializeMessage($message), $key);
}

/**
Expand Down
25 changes: 25 additions & 0 deletions tests/KafkaPubSubAdapterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,31 @@ public function testPublish()
$adapter->publish('channel_name', ['hello' => 'world']);
}

public function testPublishWithKey()
{
$topic = Mockery::mock(\RdKafka\Topic::class);
$topic->shouldReceive('produce')
->withArgs([
RD_KAFKA_PARTITION_UA,
0,
'{"id:1", "hello":"world"}',
1
])
->once();

$producer = Mockery::mock(\RdKafka\Producer::class);
$producer->shouldReceive('newTopic')
->with('channel_name')
->once()
->andReturn($topic);

$consumer = Mockery::mock(\RdKafka\KafkaConsumer::class);

$adapter = new KafkaPubSubAdapter($producer, $consumer);

$adapter->publish('channel_name', ['id' => 1, 'hello' => 'world'], 1);
}

public function testPublishBatch()
{
$topic = Mockery::mock(\RdKafka\Topic::class);
Expand Down