亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Symfony MessageHandler 計算一條消息被發送了多少次

Symfony MessageHandler 計算一條消息被發送了多少次

PHP
慕蓋茨4494581 2022-12-11 09:39:31
我正在使用 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)        ]);    }}
查看完整描述

1 回答

?
喵喵時光機

TA貢獻1846條經驗 獲得超7個贊

要將元數據添加到消息中,您可以使用 stamps。

您以后可以在自己的自定義中間件中使用它。

例如,對于這個自定義StampInterface實現類:

class LoopCount implements StampInterface {



    private int $count; 


    public function __construct($count) {

        $this->count = $count;

    }


    public function getCount(): int {

        return $this->count;

    } 

}

然后創建您自己的中間件來檢查此標記并在處理后重新發送:

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 應該可以幫助你朝著正確的方向前進。測試和調試,你會得到它的工作。我稍后會回到這個問題上,看看是否有遺漏的東西


查看完整回答
反對 回復 2022-12-11
  • 1 回答
  • 0 關注
  • 129 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號