Saturday, January 27, 2018

PHP Netflix Eureka client

Netflix Eureka is a REST service that is primarily used in the AWS cloud for locating services. It comes with a Java-based client. But if you need a PHP-based client - welcome under the cut.

PHP Eureka client supports all the Eureka operations: register, de-register, send heartbeat, take instance out, put instance back, update metadata etc. How to use:

1. Create Eureka app instance definition:
// We will use app name and instance id for making requests below.
$appName = 'new_app';
$instanceId = 'test_instance_id';

// Create app instance metadata.
$metadata = new Metadata();
$metadata->set('test_key', 'test_value');

// Create data center metadata.
$dataCenterMetadata = new Metadata();
$dataCenterMetadata->set('data_center_test_key', 'data_center_test_value');

// Create data center info (Amazon example).
$dataCenterInfo = new DataCenterInfo();
$dataCenterInfo
  ->setName('Amazon')
  ->setClass('com.netflix.appinfo.AmazonInfo')
  ->setMetadata($dataCenterMetadata);

// Create Eureka app instance.
$instance = new Instance();
$instance
  ->setInstanceId($instanceId)
  ->setHostName('test_host_name')
  ->setApp($appName)
  ->setIpAddr('127.0.0.1')
  ->setPort(80)
  ->setSecurePort(433)
  ->setHomePageUrl('http://localhost')
  ->setStatusPageUrl('http://localhost/status')
  ->setHealthCheckUrl('http://localhost/health-check')
  ->setSecureHealthCheckUrl('https://localhost/health-check')
  ->setVipAddress('test_vip_address')
  ->setSecureVipAddress('test_secure_vip_address')
  ->setMetadata($metadata)
  ->setDataCenterInfo($dataCenterInfo);

2. Create Eureka client (it is based on Guzzle HTTP client):
// Eureka client usage example.
// Create guzzle client.
$guzzle = new Client();

// Create eureka client.
$eurekaClient = new EurekaClient('localhost', 8080, $guzzle);

3. Communicate with Eureka server:
try {
  // Register new application instance.
  $response = $eurekaClient->register($appName, $instance);

  // Send application instance heartbeat.
  $response = $eurekaClient->heartBeat($appName, $instanceId);

  // De-register application instance.
  $response = $eurekaClient->deRegister($appName, $instanceId);
}
catch (Exception $e) {
  echo $e->getMessage() . PHP_EOL;
}

See repository for more information.

No comments:

Post a Comment