瀏覽代碼

fix read/write for cache map

Jackson Tian 7 年之前
父節點
當前提交
a79f28e3fc
共有 1 個文件被更改,包括 24 次插入19 次删除
  1. 24 19
      sdk/endpoints/location_resolver.go

+ 24 - 19
sdk/endpoints/location_resolver.go

@@ -24,15 +24,26 @@ const (
 	EndpointCacheExpireTime = 3600 //Seconds
 )
 
-var lastClearTimePerProduct = struct {
+type Cache struct {
 	sync.RWMutex
-	cache map[string]int64
-}{cache: make(map[string]int64)}
+	cache map[string]interface{}
+}
 
-var endpointCache = struct {
-	sync.RWMutex
-	cache map[string]string
-}{cache: make(map[string]string)}
+func (this Cache) Get(k string) (v interface{}) {
+	this.RLock()
+	v = this.cache[k]
+	this.RUnlock()
+	return
+}
+
+func (this Cache) Set(k string, v interface{}) {
+	this.Lock()
+	this.cache[k] = v
+	this.Unlock()
+}
+
+var lastClearTimePerProduct = Cache{cache: make(map[string]interface{})}
+var endpointCache = Cache{cache: make(map[string]interface{})}
 
 type LocationResolver struct {
 }
@@ -45,8 +56,8 @@ func (resolver *LocationResolver) TryResolve(param *ResolveParam) (endpoint stri
 
 	//get from cache
 	cacheKey := param.Product + "#" + param.RegionId
-	if endpointCache.cache != nil && len(endpointCache.cache[cacheKey]) > 0 && !CheckCacheIsExpire(cacheKey) {
-		endpoint = endpointCache.cache[cacheKey]
+	if endpointCache.cache != nil && len(endpointCache.Get(cacheKey).(string)) > 0 && !CheckCacheIsExpire(cacheKey) {
+		endpoint = endpointCache.Get(cacheKey).(string)
 		support = true
 		return
 	}
@@ -87,12 +98,8 @@ func (resolver *LocationResolver) TryResolve(param *ResolveParam) (endpoint stri
 	}
 	if len(getEndpointResponse.Endpoints.Endpoint[0].Endpoint) > 0 {
 		endpoint = getEndpointResponse.Endpoints.Endpoint[0].Endpoint
-		endpointCache.Lock()
-		endpointCache.cache[cacheKey] = endpoint
-		endpointCache.Unlock()
-		lastClearTimePerProduct.Lock()
-		lastClearTimePerProduct.cache[cacheKey] = time.Now().Unix()
-		lastClearTimePerProduct.Unlock()
+		endpointCache.Set(cacheKey, endpoint)
+		lastClearTimePerProduct.Set(cacheKey, time.Now().Unix())
 		support = true
 		return
 	}
@@ -102,12 +109,10 @@ func (resolver *LocationResolver) TryResolve(param *ResolveParam) (endpoint stri
 }
 
 func CheckCacheIsExpire(cacheKey string) bool {
-	lastClearTime := lastClearTimePerProduct.cache[cacheKey]
+	lastClearTime := lastClearTimePerProduct.Get(cacheKey).(int64)
 	if lastClearTime <= 0 {
 		lastClearTime = time.Now().Unix()
-		lastClearTimePerProduct.Lock()
-		lastClearTimePerProduct.cache[cacheKey] = lastClearTime
-		lastClearTimePerProduct.Unlock()
+		lastClearTimePerProduct.Set(cacheKey, lastClearTime)
 	}
 
 	now := time.Now().Unix()