`

用clojure实现一致性哈希算法(consistent hashing)

阅读更多
一、依赖的jar包
[com.google.guava/guava 14.0.1]


二、具体实现
(defn vnodes
  "生成n个随机的vnode"
  [n]
  (vec (sort (repeatedly n #(rand-int 65536)))))

(defn short-hash
  "产生一个0..2^16范围的hash值"
  [s]
  ;; SHA-1 used for uniform value distribution
  (bit-and (->> (.hashString (com.google.common.hash.Hashing/sha1) s) (.asInt)) 0xffff))

(defn closest-before
  "查找之前最近的一个vnode"
  [coll el]
  (let [idx (java.util.Collections/binarySearch coll el compare)]
    (cond
      (= -1 idx) -1 ;;
      (neg? idx) (coll (- -2 idx)) 
      :else      (coll idx))))

(defn responsible
  "超找某个数据hash之后应该属于哪个node。因为一个node包含一组vnode。所以多了个这个方法,不然用到closest-before其实就够了。"
  [hash ^List ring]
  (let [found (apply max-key #(closest-before % hash) ring)]
    (.lastIndexOf ring found)))


(closest-before [1 2 3 4 20 30 60 80 1020 34045] 50)
;;==>30
;;假设有node1:[100 200 300]。100,200,300是vnode。
;;假设有node2:[400 500 600]。
;;结果为1。可以把这连个node串成一个环(ring)来看。往前找最近的,就是node2了。所以返回index值为1。
(responsible 50 [[100 200 300] [400 500 600]] )
;;==> 1


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics