1. Code Organization
2. conhash.h
/************************************************************************* > File name:conhash.h > Author:ma 6174 > Mail: [email protected] > Created time:mon 08:51:23 PM WST ****************************** /#ifndef conhash_h#define conhash_h#include <stdio.h> #include < stdlib.h> #include <iostream> #include <map> #include <string> #include <sstream>using Namespace std;/* * Cache class for store object * */class cache {private:string identity; UINT vcnt; The count of Virtual Cachepublic:cache (); Cache (string, uint); string getidentity (); uint getvcnt ();}; struct CMP {bool operator () (UINT hash1, uint Hash2) const {return hash1-hash2 <= 0;}}; Class Conhash {private://map<uint, cache*, Cmp>cachemap;map<uint, Cache*>cachemap;public:conhash () {} UINT Hashfunc (string), void Addcache (Cache *cache); Cache * Search (String object);}; #endif
3. Conhash.cpp
/************************************************************************* > File Name:conhash.cpp > Author: ma6174 > Mail: [email protected] > Created time:mon Geneva 08:58:11 PM WST *********************** /#include "conhash.h" Cache::cache () {identity = ""; vcnt = 0;} Cache::cache (String _identity, uint _vcnt): Identity (_identity), vcnt (_vcnt) {}string cache::getidentity () {return this->identity;} UINT cache::getvcnt () {return this->vcnt;} UINT Conhash::hashfunc (string str) {UINT seed = 131;//131 1313 13131 131313 etc.. UINT HASH = 0;string::iterator index = Str.begin (); while (Index < Str.end ()) {hash = hash * seed + (*index++); } return (hash & 0x7FFFFFFF);} void Conhash::addcache (Cache *cache) {ostringstream oss;string identity = cache->getidentity (); UINT VCNT = cache-> GETVCNT (); UINT key;string Value;int i;for (i = 0;i < vcnt;i++) {OSS << identity << i;value = Oss.str (); key = This->hashfunc (value); This->cachemap.insert (Pair<uint, cache*> (key , cache));}} Cache *conhash::search (String object) {UINT hash = This->hashfunc (object); Map<uint, cache*>::iterator it; it = Cachemap.begin (); while (it = Cachemap.end ()) {if (It->first >= hash) {return it->second;} it++;} return NULL;}
4. main.cpp
/************************************************************************* > File Name:main.cpp > author:ma6174 > Mail: [email protected] > Created time:mon 09:12:53 PM WST ******************* /#include "conhash.h" int main () {Cache *cache1 = new Cache (" Machine A ", 20); Cache *cache2 = new cache ("Machine B", 30); Cache *cache3 = new cache ("Machine C", 10); Cache *cache4 = new cache ("Machine D", +); string request; Conhash Conhash;conhash.addcache (cache1); Conhash.addcache (cache2); Conhash.addcache (CACHE3); Conhash.addcache ( CACHE4);cout<<cache1<< "" <<cache2<< "<<cache3<<" "<<cache4<<endl while (1) {cout << "request from ..."; Cin>>request;cout<<conhash.search (Request)->getidentity ( ) <<endl;} return 0;}
5. Makefile
cc=g++all:$ (CC)-g-o main main.cpp conhash.cpp
6. Testing
Consistent hash algorithm (consistent hashing)