Skip to content

Commit

Permalink
Added UnsetContextInTaskWorkerListener which can be used to unset c…
Browse files Browse the repository at this point in the history
…onnection context when using non-coroutine task worker.


Co-authored-by: Deeka Wong <[email protected]>
Co-authored-by: 李铭昕 <[email protected]>
  • Loading branch information
3 people authored Jan 4, 2024
1 parent 9647e9e commit 3c5eb95
Showing 1 changed file with 53 additions and 0 deletions.
53 changes: 53 additions & 0 deletions src/Listener/UnsetContextInTaskWorkerListener.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php

declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact [email protected]
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
namespace Hyperf\DbConnection\Listener;

use Hyperf\Context\Context;
use Hyperf\Contract\ConfigInterface;
use Hyperf\Database\ConnectionResolverInterface;
use Hyperf\Event\Contract\ListenerInterface;
use Hyperf\Framework\Event\BeforeWorkerStart;
use Psr\Container\ContainerInterface;

class UnsetContextInTaskWorkerListener implements ListenerInterface
{
public function __construct(
private ContainerInterface $container,
private ConfigInterface $config
) {
}

public function listen(): array
{
return [
BeforeWorkerStart::class,
];
}

/**
* @param BeforeWorkerStart $event
*/
public function process(object $event): void
{
if (! $event instanceof BeforeWorkerStart || ! $event->server->taskworker) {
return;
}

$connectionResolver = $this->container->get(ConnectionResolverInterface::class);
$databases = (array) $this->config->get('databases', []);

foreach ($databases as $name => $_) {
$contextKey = (fn () => $this->getContextKey($name))->call($connectionResolver);
Context::destroy($contextKey);
}
}
}

0 comments on commit 3c5eb95

Please sign in to comment.