Added UnsetContextInTaskWorkerListener which can be used to unset connection context when using non-coroutine task worker.

Co-authored-by: Deeka Wong <8337659+huangdijia@users.noreply.github.com>
Co-authored-by: 李铭昕 <715557344@qq.com>
This commit is contained in:
李帅西 2024-01-04 10:42:11 +08:00 committed by GitHub
parent 1501e79961
commit f9da6dbfaf
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 57 additions and 0 deletions

View File

@ -4,6 +4,10 @@
- [#6423](https://github.com/hyperf/hyperf/pull/6423) Fixed bug that the timezone of crontab task cannot work. - [#6423](https://github.com/hyperf/hyperf/pull/6423) Fixed bug that the timezone of crontab task cannot work.
## Added
- [#6431](https://github.com/hyperf/hyperf/pull/6431) Added `UnsetContextInTaskWorkerListener` which can be used to unset connection context when using non-coroutine task worker.
# v3.1.4 - 2023-12-29 # v3.1.4 - 2023-12-29
## Fixed ## Fixed

View File

@ -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 group@hyperf.io
* @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);
}
}
}