gpt4 book ai didi

php - Symfony MessageHandler 计算一条消息被发送了多少次

转载 作者:行者123 更新时间:2023-12-05 02:08:21 26 4
gpt4 key购买 nike

我正在使用 Symfony Messenger,我想在处理程序中继续发送消息,直到它被发送多次。

我怎样才能跟踪它?

到目前为止,这是我的处理程序类的代码:

class RetryTestHandler implements MessageHandlerInterface
{
/**
* @var EntityManagerInterface
*/
private $entityManager;
/**
* @var MessageBusInterface
*/
private $bus;

public function __construct(MessageBusInterface $bus, EntityManagerInterface $entityManager)
{
$this->entityManager = $entityManager;
$this->bus = $bus;
}

public function __invoke(RetryTest $message)
{
// TODO: Keep dispatching message until it has been dispatched 10 times?
$this->bus->dispatch(new RetryTest("This is a test!"), [
new DelayStamp(5000)
]);
}
}

最佳答案

要将元数据添加到您的消息中,you can use stamps .

您以后可以在自己的自定义中间件中使用它。

例如对于此自定义 StampInterface 实现类:

class LoopCount implements StampInterface {


private int $count;

public function __construct($count) {
$this->count = $count;
}

public function getCount(): int {
return $this->count;
}
}

然后 create your own middleware检查此标记并在处理后重新发送:

class ResendingMiddleware implements MiddlewareInterface
{
private $bus;

public function __construct(MessageBusInterface $bus) {
$this->bus = $bus;
}

public function handle(Envelope $envelope, StackInterface $stack): Envelope
{

$envelope = $stack->next()->handle($envelope, $stack);

if (null !== $stamp = $envelope->last(LoopCount::class)) {
$count = $stamp->getCount();
} else {
return $envelope;
}

// Stop dispatching
if ($count > 9) {
return $envelope;
}

$this->bus->dispatch(new RetryTest("Dit is een test"), [
new DelayStamp(5000),
new LoopCount($count + 1)
]);

return $envelope;
}

如果它被处理超过 9 次,则不执行任何操作来使用该消息。

您还需要将中间件添加到配置中:

framework:
messenger:
buses:
messenger.bus.default:
middleware:
# service ids that implement Symfony\Component\Messenger\Middleware\MiddlewareInterface
- 'App\Middleware\ResendingMiddleware'

我写的很匆忙,现在无法测试,但 base 应该可以帮助你朝着正确的方向前进。测试和调试,你会得到它的工作。稍后我会回到这个问题上,看看是否有任何遗漏

关于php - Symfony MessageHandler 计算一条消息被发送了多少次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61077748/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com