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

Commit 4344ab8

Browse files
authored
Merge pull request #3 from hellofresh/feature/cache-socket-connection
Added opened socket reuse for statsd
2 parents 4a99107 + 0988b54 commit 4344ab8

File tree

2 files changed

+70
-2
lines changed

2 files changed

+70
-2
lines changed

src/Client/StatsD.php

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,9 @@
55
use HelloFresh\Stats\HTTPMetricAlterCallback;
66
use HelloFresh\Stats\Incrementer;
77
use HelloFresh\Stats\State;
8+
use HelloFresh\Stats\StatsD\CachingClient as StatsDClient;
89
use HelloFresh\Stats\Timer;
9-
use League\StatsD\Client as StatsDClient;
10+
use League\StatsD\Exception\ConfigurationException;
1011

1112
class StatsD extends AbstractClient implements Client
1213
{
@@ -25,7 +26,8 @@ class StatsD extends AbstractClient implements Client
2526
/**
2627
* StatsD constructor.
2728
*
28-
* @param string $dsn statsd connection dsn
29+
* @param string $dsn statsd connection dsn
30+
* @throws ConfigurationException
2931
*/
3032
public function __construct($dsn)
3133
{

src/StatsD/CachingClient.php

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

0 commit comments

Comments
 (0)