Skip to content

Commit

Permalink
Optimize UdpSocketAspect, AOP for getSocket (#5246)
Browse files Browse the repository at this point in the history
  • Loading branch information
huangdijia authored Dec 11, 2022
1 parent e7f6285 commit c8de4bc
Showing 1 changed file with 12 additions and 17 deletions.
29 changes: 12 additions & 17 deletions src/Aspect/UdpSocketAspect.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,37 +14,32 @@
use Hyperf\Context\Context;
use Hyperf\Di\Aop\AbstractAspect;
use Hyperf\Di\Aop\ProceedingJoinPoint;
use Hyperf\Engine\Socket;
use Hyperf\Utils\Coroutine;
use Monolog\Handler\SyslogUdp\UdpSocket;

class UdpSocketAspect extends AbstractAspect
{
public array $classes = [
UdpSocket::class . '::send',
UdpSocket::class . '::close',
UdpSocket::class . '::getSocket',
];

public function process(ProceedingJoinPoint $proceedingJoinPoint)
{
if (Coroutine::inCoroutine()) {
if ($proceedingJoinPoint->methodName == 'close') {
return;
}

/** @var string $chunk */
$chunk = $proceedingJoinPoint->arguments['keys']['chunk'] ?? '';
[$ip, $port] = (fn () => [$this->ip, $this->port])->call($proceedingJoinPoint->getInstance());

$key = sprintf('%s_%s_%s_%s', $proceedingJoinPoint->className, 'Socket', $ip, $port);
$socket = Context::getOrSet($key, fn () => tap(new Socket(AF_INET, SOCK_DGRAM, SOL_UDP), function (Socket $socket) use ($ip, $port) {
$socket->connect($ip, $port, 0.5);
defer(fn () => $socket->isClosed() || $socket->close());
}));

$socket->send($chunk);

return;
return Context::getOrSet($key, function () use ($port) {
$domain = AF_INET;
$protocol = SOL_UDP;
// Check if we are using unix sockets.
if ($port === 0) {
$domain = AF_UNIX;
$protocol = IPPROTO_IP;
}

return socket_create($domain, SOCK_DGRAM, $protocol);
});
}

return $proceedingJoinPoint->process();
Expand Down

0 comments on commit c8de4bc

Please sign in to comment.