Symfony Messenger / RabbitMQ检测到被请求的消息

问题描述 投票:0回答:1

如果使用方消息失败,则默认情况下会延迟延迟重新排队消息。有没有一种方法可以在邮件中添加计数器,这样我就可以知道邮件是否正在最后一次尝试吗?

这是期望的行为:

第一次尝试:

App\Message\Message {
  body: array:2 [
    "id" => 2
    "alias" => "some_alias",
    "attempt" => 0,
  ]
}

第一次重试:

App\Message\Message {
  body: array:2 [
    "id" => 2
    "alias" => "some_alias",
    "attempt" => 1,
  ]
}

第二次重试:

App\Message\Message {
  body: array:2 [
    "id" => 2
    "alias" => "some_alias",
    "attempt" => 2,
  ]
}

第三次重试:

App\Message\Message {
  body: array:2 [
    "id" => 2
    "alias" => "some_alias",
    "attempt" => 3,
  ]
}
configuration rabbitmq symfony4 middleware symfony-messenger
1个回答
0
投票

解决方案:

messenger.yaml:

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

App \ Middleware \ RetryMiddleware:

namespace App\MessageMiddleware;


use Symfony\Component\Messenger\Middleware\MiddlewareInterface;
use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Messenger\Middleware\StackInterface;
use Psr\Log\LoggerInterface;

class RetryMiddleware implements MiddlewareInterface
{
    public function handle(Envelope $envelope, StackInterface $stack): Envelope
    {
        try {
            return $stack->next()->handle($envelope, $stack);
        } catch (\Throwable $error) {
            $msg = $envelope->getMessage();
            $body = $msg->getBody();
            $body['attempt']++;
            $msg->setBody($body);
        }
    }
}

App \ Message:

namespace App\Message;


class  Message
{
    public $body;

    public function getBody()
    {
        return $this->body;
    }

    public function setBody(array $body): void
    {
        $this->body = $body;
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.