add influxdb and stat of page view
This commit is contained in:
parent
d39759f88e
commit
f4169d20e9
46
src/Api/InfluxDB.php
Normal file
46
src/Api/InfluxDB.php
Normal file
|
@ -0,0 +1,46 @@
|
|||
<?php
|
||||
|
||||
namespace App\Api;
|
||||
|
||||
use InfluxDB2\Client;
|
||||
use InfluxDB2\Model\WritePrecision;
|
||||
|
||||
/**
|
||||
* class InfluxDB.
|
||||
*
|
||||
* @author Simon Vieille <simon@deblan.fr>
|
||||
*/
|
||||
class InfluxDB
|
||||
{
|
||||
protected ?Client $client = null;
|
||||
|
||||
public function __construct(
|
||||
protected ?string $url,
|
||||
protected ?string $token,
|
||||
protected ?string $bucket,
|
||||
protected ?string $org,
|
||||
protected bool $debug = false
|
||||
) {
|
||||
if (isset($this->url, $this->token, $this->bucket, $this->org)) {
|
||||
$this->client = new Client([
|
||||
'url' => $this->url,
|
||||
'token' => $this->token,
|
||||
'bucket' => $this->bucket,
|
||||
'org' => $this->org,
|
||||
'debug' => $this->debug,
|
||||
'precision' => WritePrecision::S,
|
||||
'timeout' => 1,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
public function isAvailable(): bool
|
||||
{
|
||||
return $this->getClient() !== null;
|
||||
}
|
||||
|
||||
public function getClient(): ?Client
|
||||
{
|
||||
return $this->client;
|
||||
}
|
||||
}
|
41
src/EventListener/StatListener.php
Normal file
41
src/EventListener/StatListener.php
Normal file
|
@ -0,0 +1,41 @@
|
|||
<?php
|
||||
|
||||
namespace App\EventListener;
|
||||
|
||||
use App\Api\InfluxDB;
|
||||
use Symfony\Component\HttpKernel\Event\RequestEvent;
|
||||
use InfluxDB2\WriteType;
|
||||
use InfluxDB2\Point;
|
||||
|
||||
/**
|
||||
* class StatListener.
|
||||
*
|
||||
* @author Simon Vieille <simon@deblan.fr>
|
||||
*/
|
||||
class StatListener
|
||||
{
|
||||
public function __construct(protected InfluxDB $influxDB)
|
||||
{
|
||||
}
|
||||
|
||||
public function onKernelRequest(RequestEvent $event)
|
||||
{
|
||||
if (!$this->influxDB->isAvailable()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$client = $this->influxDB->getClient();
|
||||
|
||||
$writeApi = $client->createWriteApi(['writeType' => WriteType::SYNCHRONOUS]);
|
||||
$pageView = new Point('page_view');
|
||||
$pageView
|
||||
->addTag('request', 'view')
|
||||
->addField('value', 1)
|
||||
->time(time())
|
||||
;
|
||||
|
||||
$writeApi->write($pageView);
|
||||
$writeApi->close();
|
||||
$client->close();
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue