Home Backend Development PHP Tutorial Detailed introduction to implementing consistent hashing algorithm in PHP (code example)

Detailed introduction to implementing consistent hashing algorithm in PHP (code example)

Mar 04, 2019 pm 01:38 PM
php

This article brings you a detailed introduction (code example) about the implementation of consistent hashing algorithm in PHP. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. Case Analysis
(1) Problem Overview

Assume that our image data is evenly distributed among three services (labeled as Server A and Server A respectively) B, server C) above, now we want to get the picture from it. After getting this request, how can the server specify whether this picture exists on server A, server B, or server C? If we want to traverse, two or three servers are okay, but that is too out. When the number of servers reaches hundreds or thousands, do we still dare to talk about traversing?

(2) Solution

a. Through storage mapping relationship

First of all, we may think that we can create an intermediate layer to record image storage On which server, as follows:

logo1.png =====》 Service A

ogo2.png =====》 Service B

logo3.png == ===》Service C

In this way, whenever a request comes, we first request the mapping relationship between the image and the server, find the server where the image is stored, and then make a request to the specified server. From an implementation point of view, this is feasible, but when storing pictures, we must also store the mapping relationship between the pictures and the server, which obviously increases the workload, and its maintenance is also a problem. Once the stored pictures and the server If there is a problem with the mapping relationship, the entire system will hang up.

b. Hash algorithm

Since we want to exclude the storage mapping relationship, at this time, people think of the hash algorithm. For example, when the

Detailed introduction to implementing consistent hashing algorithm in PHP (code example)

picture is stored, the hash value val is obtained through the hash algorithm based on the picture name (logo1.png), and the hash value val is obtained by taking the modulo of val. value, you can determine which server the image should be stored on. As follows:

key = hash(imgName) % n
Copy after login

Where:

imgName is the name of the image,

n is the number of servers,

key represents the number where the image should be stored on the server.

When a request comes, such as requesting the image logo1.png, the server can determine which server the logo1.png is stored on based on the key calculated by the above formula. The PHP implementation is as follows:

$hostsMap = ['img1.findme.wang', 'img2.findme.wang', 'img3.findme.wang'];
 
function getImgSrc($imgName) {
    global $hostsMap;
    $key = crc32($imgName) % count($hostsMap);
    return 'http://' . $hostsMap[abs($key)] . '/' . $imgName;
}
//测试
var_dump(getImgSrc("logo1.png"));
var_dump(getImgSrc("logo2.png"));
var_dump(getImgSrc("logo3.png"));
Copy after login

Output:

Detailed introduction to implementing consistent hashing algorithm in PHP (code example)

At this point, we change from storing the mapping relationship to calculating the serial number of the server, which indeed greatly simplifies the work. quantity.

But once a new machine is added, it is very troublesome, because n changes, and almost all the serial number keys also change, so a lot of data migration work is required.

C. Consistent hash algorithm

Consistent hash algorithm is a special hash algorithm designed to solve the problem when the number of nodes (such as the number of servers storing pictures) ) changes, try to migrate as little data as possible.

The basic idea:

1. First, evenly distribute the points from 0 to 2 to the power of 32 on a ring, as follows:

Detailed introduction to implementing consistent hashing algorithm in PHP (code example)

2. Then calculate all the node nodes (servers that store pictures) through hash calculation, take the remainder of 232, and then map it to the hash ring, as follows:

Detailed introduction to implementing consistent hashing algorithm in PHP (code example)

3. When a request comes, for example, requesting the image logo1.png, after hash calculation, the remainder of 232 is taken, and then also mapped to the hash ring, as follows:

Detailed introduction to implementing consistent hashing algorithm in PHP (code example)

4. Then turn clockwise. The first node reached is considered to be the server that stores the logo1.png image.

As can be seen from the above, in fact, the highlight of consistent hashing is that the first is the hash calculation and mapping of both the node node (the server that stores the picture) and the object (picture), and the second is the closed-loop design.

Advantages: When a new machine is added, only the marked area is affected, as shown below:

Detailed introduction to implementing consistent hashing algorithm in PHP (code example)

Disadvantages: When there are relatively few nodes , often lacks balance, because after hash calculation, the nodes mapped to the hash ring are not evenly distributed, resulting in some machines having a high load and some machines being idle.

PHP implementation is as follows:

$hostsMap = ['img1.findme.wang', 'img2.findme.wang', 'img3.findme.wang'];
$hashRing = [];
 
function getImgSrc($imgName){
    global $hostsMap;
    global $hashRing;
    //将节点映射到hash环上面
    if (empty($hashRing)) {
        foreach($hostsMap as $h) {
            $hostKey = fmod(crc32($h) , pow(2,32));
            $hostKey = abs($hostKey);
            $hashRing[$hostKey] = $h;
        }
        //从小到大排序,便于查找
        ksort($hashRing);
    }
 
    //计算图片hash
    $imgKey = fmod(crc32($imgName) , pow(2,32));
    $imgKey = abs($imgKey);
    foreach($hashRing as $hostKey => $h) {
        if ($imgKey <p>The output result is as follows: </p><p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/image/534/248/963/1551677736513489.png" class="lazy" title="1551677736513489.png" alt="Detailed introduction to implementing consistent hashing algorithm in PHP (code example)"></p><p>至于为什么使用fmod函数不适用求余运算符%,主要是因为pow(2,32)在32位操作系统上面,超高了PHP_INT_MAX,具体可以参考上一篇文章“PHP中对大数求余报错Uncaught pisionByZeroError: Modulo by zero”。</p><p>d、通过虚拟节点优化一致性hash算法</p><p>为了提高一致性hash算法的平衡性,我们首先能够想到的是,增加节点数,但是机器毕竟是需要经费啊,不是说增就能随意增,那就增加虚拟节点,这样就没毛病了。思路如下:</p><p>1、假设host1、host2、host3,都分别有3个虚拟节点,如host1的虚拟节点为host1_1、host1_2、host1_3</p><p>2、然后将所有的虚拟节点node(存储图片的服务器)通过hash计算后,对232取余,然后也映射到hash环上面,如下:</p><p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/image/891/291/577/1551677752319649.png" class="lazy" title="1551677752319649.png" alt="Detailed introduction to implementing consistent hashing algorithm in PHP (code example)"></p><p>然后,接下来步骤同一致性hash算法一致,只是最后需要将虚拟节点,转为真实的节点。</p><p>PHP实现如下:</p><pre class="brush:php;toolbar:false">$hostsMap = ['img1.findme.wang', 'img2.findme.wang', 'img3.findme.wang'];
$hashRing = [];
 
function getImgSrc($imgName){
    global $hostsMap;
    global $hashRing;
    $virtualNodeLen = 3; //每个节点的虚拟节点个数
 
    //将节点映射到hash环上面
    if (empty($hashRing)) {
        foreach($hostsMap as $h) {
            $i = 0;
            while($i  $h) {
        if ($imgKey <p>执行结果如下:</p><p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/image/947/947/423/1551677769758146.png" class="lazy" title="1551677769758146.png" alt="Detailed introduction to implementing consistent hashing algorithm in PHP (code example)"></p><p><strong>二、备注</strong><br>1、取模与取余的区别?</p><p>取余,遵循尽可能让商向0靠近的原则</p><p>取模,遵循尽可能让商向负无穷靠近的原则</p><p>1、什么是CRC算法?</p><p>CRC(Cyclical Redundancy Check)即循环冗余码校验,主要用于数据校验,常用的有CRC16、CRC32,其中16、32代表多项式最高次幂。</p><p></p>
Copy after login

The above is the detailed content of Detailed introduction to implementing consistent hashing algorithm in PHP (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

See all articles