template<class Key, template< typename >class HashKey = CHashFn>
class CConsistentHash< Key, HashKey >
A lightweight implementation of Consistent Hashng algorithm.
Consistent Hashing is a technique to map a large number of keys to limited amount of values.
Consider a common use case below:
You have 10 servers to serve for 1 million users, you need to decide which user is served by which server. CConsistentHash can do the mapping easily:
- Each user's ID is a key for CConsistentHash;
- Integer 1 to 10 are values denoting each server;
- Firstly you set weight for every value, which could mean the capability of each server, for example, like this:
- Then for every user request, get which server it should go to, like this:
uint32_t serverId = mapping.
hash(userId);
The real power of consistent hashing algorithm is that, when you want to add or remove a server from your servers pool, only a fraction of your users will be redirected to a different server, which could make the impact as small as possible. CConsistentHash makes this operation even easier by using one API setValue only:
- Set a positive weight for a new value to add a new server;
- Change the weight of an existing value to adjust the capability of the server;
- Set weight to 0 for an existing value to remove the server;
- Template Parameters
-
Key | Type of keys |
HashKey | Hash function for Key |