PHP code example of maestrodimateo / simple-consul
1. Go to this page and download the library: Download maestrodimateo/simple-consul library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
maestrodimateo / simple-consul example snippets
use Maestrodimateo\SimpleConsul\Facades\Consul;
// Store & retrieve
Consul::put('config/app/name', 'My Application');
$name = Consul::get('config/app/name');
// Auto JSON encode/decode for arrays
Consul::put('config/database', ['host' => 'db.example.com', 'port' => 5432]);
$db = Consul::get('config/database');
echo $db['host']; // "db.example.com"
// Get with default
$debug = Consul::get('config/debug', false);
// Check existence
if (Consul::has('config/api-key')) { ... }
// Delete
Consul::delete('config/old-key');
// List keys
$keys = Consul::keys('config/');
// ["config/app/name", "config/database", ...]
// Register a service manually (with health check)
Consul::registerService(
name: 'payment-api',
port: 8080,
tags: ['v2', 'production'],
meta: ['version' => '2.1.0'],
check: [
'HTTP' => 'http://10.0.0.5:8080/up',
'Interval' => '10s',
],
);
// List all services
$services = Consul::services();
// Get instances of a service
$instances = Consul::service('payment-api');
// Deregister
Consul::deregisterService('payment-api');
// Get healthy instances only
$healthy = Consul::healthyService('payment-api');
// Quick boolean check
if (Consul::isHealthy('payment-api')) {
// At least one instance is passing
}
$result = Consul::withLock('jobs/send-emails', function () {
// Runs only if the lock is acquired.
// Lock is auto-released when done (even on exceptions).
return sendEmails();
}, ttlSeconds: 30);
if ($result === false) {
// Another process holds the lock
}