potfur / health-json
健康JSON模式实现
dev-master
2016-12-10 21:20 UTC
Requires
- php: ^7.1
Requires (Dev)
- phpspec/phpspec: ^3.2
- phpunit/phpunit: ^5.7
This package is not auto-updated.
Last update: 2024-09-14 19:53:15 UTC
README
假设有一个服务需要定期检查其是否正在运行。最简单的解决方案是对主站点进行ping操作,如果它以200
响应,则一切正常。
但在现实中,服务可能无法连接到数据库,并且响应是由过时的缓存提供的。另一种情况是,所有操作都正常进行,但邮件服务无法访问。
这就是健康发挥作用的地方。 健康是健康JSON模式的一个实现,该模式为监控端点标准化了响应结构。
如何使用
创建一个Health
实例,其中将注册所有需要监控的服务
use Health\Health; use Health\Service\CallableService; $health = new Health( 'some-app', // application name 'healthy-server.com', // host name '1.2.3', // currently deployed version new \DateTime('2016-12-05T12:45:11+00:00') // deployment date ); $health->addService( 'database', // service group new CallableService( 'postgres', // service name function () use ($pdo) { $pdo->exec('SELECT 1'); }, // validating function true // true if service is essential ) );
当所有服务都已注册后,Health
可以创建状态快照。这样的快照可以用作简单true/false端点来公开服务健康状态
$state = $health->state(); $state->isHealthy(); // returns true if all services are working $state->summary(); // returns array with detailed information about all registered services
示例
例如在Symfony中
/ping
端点在基本服务正常运行时返回200,否则返回500/health
端点显示所有服务的摘要,响应状态码反映了其健康状况
class HealthController extends Controller { /** * @Route("/ping", name="health_ping") */ public function pingAction(): Response { return (new Response())->setStatusCode($this->get('health')->status()->isHealthy(true) ? 200 : 500); } /** * @Route("/health", name="health_summary") */ public function healthAction(string $sku): Response { $status = $this->get('health')->status(); $response = new JsonResponse(); $response->setData($status->summary()); $response->setStatusCode($status->isHealthy() ? 200 : 500); return $response; } }