11package services
22
33import (
4+ "fmt"
45 "log"
56 "strings"
67
@@ -10,11 +11,12 @@ import (
1011type CacheRepository interface {
1112 Get (key string ) * models.CacheItem
1213 GetMany (keys []string ) []models.CacheItem
13- Set (key , value string )
14+ Set (key , value string ) models. CacheItem
1415}
1516
1617type HTTPClient interface {
17- Get (node string , key string ) (models.CacheItem , error )
18+ Set (node , key , value string ) (models.CacheItem , error )
19+ Get (node string , keys []string ) ([]models.CacheItem , error )
1820 Gossip (node string , nodes []string , tokensChecksum string ) (oldNodes []string , err error )
1921 Tokens (node string ) (models.TokenMappings , error )
2022}
@@ -34,11 +36,59 @@ type CacheSvc struct {
3436}
3537
3638func (svc CacheSvc ) Get (keys []string ) []models.CacheItem {
37- return svc .cacheRepo .GetMany (keys )
39+ keyToNode := map [string ]string {}
40+ sumToNode := map [string ]string {}
41+ for _ , key := range keys {
42+ sum := fmt .Sprintf ("%d" , models .HashKey (key ))
43+ node := svc .tokens .GetNode (key )
44+ sumToNode [sum ] = node
45+ keyToNode [key ] = node
46+ }
47+ 48+ nodeToSums := map [string ][]string {}
49+ for sum , node := range sumToNode {
50+ nodeToSums [node ] = append (nodeToSums [node ], sum )
51+ }
52+ nodeToKeys := map [string ][]string {}
53+ for key , node := range keyToNode {
54+ nodeToKeys [node ] = append (nodeToKeys [node ], key )
55+ }
56+ 57+ cacheItems := make ([]models.CacheItem , 0 )
58+ for node , sums := range nodeToSums {
59+ if node == svc .tokens .Nodes .CurrentNode {
60+ items := svc .cacheRepo .GetMany (sums )
61+ for _ , item := range items {
62+ item .Node = node
63+ cacheItems = append (cacheItems , item )
64+ }
65+ continue
66+ }
67+ 68+ nodeKeys := nodeToKeys [node ]
69+ items , err := svc .httpClient .Get (node , nodeKeys )
70+ if err != nil {
71+ log .Printf ("could not get cache items from node: %s, %v" , node , err )
72+ }
73+ 74+ for _ , item := range items {
75+ item .Node = node
76+ cacheItems = append (cacheItems , item )
77+ }
78+ }
79+ 80+ return cacheItems
3881}
3982
40- func (svc CacheSvc ) Set (key , value string ) {
41- svc .cacheRepo .Set (key , value )
83+ func (svc CacheSvc ) Set (key , value string ) (models.CacheItem , error ) {
84+ node := svc .tokens .GetNode (key )
85+ if node == svc .tokens .Nodes .CurrentNode {
86+ item := svc .cacheRepo .Set (key , value )
87+ item .Node = node
88+ return item , nil
89+ }
90+ 91+ return svc .httpClient .Set (node , key , value )
4292}
4393
4494func (svc CacheSvc ) Gossip () {
0 commit comments