Skip to content
This repository was archived by the owner on Dec 22, 2025. It is now read-only.

Commit 180cb25

Browse files
committed
Added opened socket reuse for statsd
1 parent 4a99107 commit 180cb25

File tree

2 files changed

+70
-1
lines changed

2 files changed

+70
-1
lines changed

src/Client/StatsD.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
use HelloFresh\Stats\Incrementer;
77
use HelloFresh\Stats\State;
88
use HelloFresh\Stats\Timer;
9-
use League\StatsD\Client as StatsDClient;
9+
use HelloFresh\Stats\StatsD\CachingClient as StatsDClient;
1010

1111
class StatsD extends AbstractClient implements Client
1212
{
@@ -26,6 +26,7 @@ class StatsD extends AbstractClient implements Client
2626
* StatsD constructor.
2727
*
2828
* @param string $dsn statsd connection dsn
29+
* @throws \League\StatsD\Exception\ConfigurationException
2930
*/
3031
public function __construct($dsn)
3132
{

src/StatsD/CachingClient.php

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
<?php
2+
3+
namespace HelloFresh\Stats\StatsD;
4+
5+
6+
use League\StatsD\Client;
7+
use League\StatsD\Exception\ConnectionException;
8+
9+
class CachingClient extends Client
10+
{
11+
/** @var resource */
12+
protected $socket;
13+
14+
/**
15+
* @return resource
16+
* @throws ConnectionException
17+
*/
18+
protected function getSocket()
19+
{
20+
if (!$this->socket) {
21+
$this->socket = @fsockopen('udp://' . $this->host, $this->port, $errno, $errstr, $this->timeout);
22+
if (!$this->socket) {
23+
throw new ConnectionException($this, '(' . $errno . ') ' . $errstr);
24+
}
25+
}
26+
27+
return $this->socket;
28+
}
29+
30+
/**
31+
* Send Data to StatsD Server
32+
* @param array $data A list of messages to send to the server
33+
* @return $this
34+
* @throws ConnectionException If there is a connection problem with the host
35+
*/
36+
protected function send(array $data)
37+
{
38+
try {
39+
$socket = $this->getSocket();
40+
$messages = [];
41+
$prefix = $this->namespace ? $this->namespace . '.' : '';
42+
foreach ($data as $key => $value) {
43+
$messages[] = $prefix . $key . ':' . $value;
44+
}
45+
$this->message = implode("\n", $messages);
46+
@fwrite($socket, $this->message);
47+
fflush($socket);
48+
} catch (ConnectionException $e) {
49+
if ($this->throwConnectionExceptions) {
50+
throw $e;
51+
} else {
52+
trigger_error(
53+
sprintf('StatsD server connection failed (udp://%s:%d)', $this->host, $this->port),
54+
E_USER_WARNING
55+
);
56+
}
57+
}
58+
59+
return $this;
60+
}
61+
62+
public function __destruct()
63+
{
64+
if ($this->socket) {
65+
fclose($this->socket);
66+
}
67+
}
68+
}

0 commit comments

Comments
 (0)