trorg/hashring-nginx

1.0.0 2019-05-15 08:50 UTC

README

Implements nginx's upstream consistent hashing. Allows to get upstream server for specified key like nginx upstream with consistent hashing. See http://nginx.org/en/docs/http/ngx_http_upstream_module.html#hash .

Usage example

Nginx's upstream:

upstream backends {
    hash $uri consistent;
    server 127.0.0.1:8080 weight=5;
    server 127.0.0.1:8081 weight=5;
    server 127.0.0.1:8082 weight=5;
    server 127.0.0.1:8083 weight=5;
}
<?php

use trorg\hashring\nginx\Hashring;

$servers = [
    '127.0.0.1:8080:5',
    '127.0.0.1:8081:5',
    '127.0.0.1:8082:5',
    '127.0.0.1:8083:5',
];

$uri = "/blog/post/1";
$hashring = new Hashring($servers);

# Get one server
$server = $hashring->getServer($uri);

/**
 * This list is identical to nginx upstream's fallback peer list
 */
$servers = $hashring->getServers($uri, 3);

print_r($server);
print_r($servers);