github.com/dubbogo/gost@v1.14.0/hash/consistent/example_test.go (about) 1 /* 2 * Licensed to the Apache Software Foundation (ASF) under one or more 3 * contributor license agreements. See the NOTICE file distributed with 4 * this work for additional information regarding copyright ownership. 5 * The ASF licenses this file to You under the Apache License, Version 2.0 6 * (the "License"); you may not use this file except in compliance with 7 * the License. You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 */ 17 18 package consistent 19 20 import ( 21 "testing" 22 ) 23 24 func TestConsistent(t *testing.T) { 25 c := NewConsistentHash(WithReplicaNum(10), WithMaxVnodeNum(1023)) 26 27 // adds the hosts to the ring 28 c.Add("127.0.0.1:8000") 29 c.Add("92.0.0.1:8000") 30 31 // Returns the host that owns `key`. 32 // 33 // As described in https://en.wikipedia.org/wiki/Consistent_hashing 34 // 35 // It returns ErrNoHosts if the ring has no hosts in it. 36 host, err := c.Get("/app.html") 37 if err != nil { 38 t.Fatal(err) 39 } 40 41 t.Log(host) 42 } 43 44 func TestBounded(t *testing.T) { 45 c := NewConsistentHash(WithReplicaNum(10), WithMaxVnodeNum(1023)) 46 47 // adds the hosts to the ring 48 c.Add("127.0.0.1:8000") 49 c.Add("92.0.0.1:8000") 50 51 // It uses Consistent Hashing With Bounded loads 52 // https://research.googleblog.com/2017/04/consistent-hashing-with-bounded-loads.html 53 // to pick the least loaded host that can serve the key 54 // 55 // It returns ErrNoHosts if the ring has no hosts in it. 56 // 57 host, err := c.GetLeast("/app.html") 58 if err != nil { 59 t.Fatal(err) 60 } 61 // increases the load of `host`, we have to call it before sending the request 62 c.Inc(host) 63 // send request or do whatever 64 t.Log("send request to", host) 65 // call it when the work is done, to update the load of `host`. 66 c.Done(host) 67 }