consistent_hash_selector.cc 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /*
  2. * Copyright [2021] JD.com, Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include <alloca.h>
  17. #include <cstring>
  18. #include <cstdio>
  19. #include <cassert>
  20. #include <algorithm>
  21. #include "consistent_hash_selector.h"
  22. #include "log/log.h"
  23. const std::string &ConsistentHashSelector::Select(uint32_t hash)
  24. {
  25. static std::string empty;
  26. if (m_nodes.empty())
  27. return empty;
  28. std::map<uint32_t, int>::iterator iter = m_nodes.upper_bound(hash);
  29. if (iter != m_nodes.end())
  30. return m_nodeNames[iter->second];
  31. return m_nodeNames[m_nodes.begin()->second];
  32. }
  33. void ConsistentHashSelector::add_node(const char *name)
  34. {
  35. if (find(m_nodeNames.begin(), m_nodeNames.end(), name) !=
  36. m_nodeNames.end()) {
  37. log4cplus_error("duplicate node name: %s in ClusterConfig",
  38. name);
  39. abort();
  40. }
  41. m_nodeNames.push_back(name);
  42. int index = m_nodeNames.size() - 1;
  43. char *buf = (char *)alloca(strlen(name) + 16);
  44. for (int i = 0; i < VIRTUAL_NODE_COUNT; ++i) {
  45. snprintf(buf, strlen(name) + 16, "%s#%d", name, i);
  46. uint32_t value = Hash(buf, strlen(buf));
  47. std::map<uint32_t, int>::iterator iter = m_nodes.find(value);
  48. if (iter != m_nodes.end()) {
  49. //hash值冲突,选取字符串中较小者
  50. if (m_nodeNames[iter->second] < name)
  51. continue;
  52. }
  53. m_nodes[value] = index;
  54. }
  55. }