github.com/polarismesh/polaris@v1.17.8/cache/cache.go (about)

     1  /**
     2   * Tencent is pleased to support the open source community by making Polaris available.
     3   *
     4   * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
     5   *
     6   * Licensed under the BSD 3-Clause License (the "License");
     7   * you may not use this file except in compliance with the License.
     8   * You may obtain a copy of the License at
     9   *
    10   * https://opensource.org/licenses/BSD-3-Clause
    11   *
    12   * Unless required by applicable law or agreed to in writing, software distributed
    13   * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
    14   * CONDITIONS OF ANY KIND, either express or implied. See the License for the
    15   * specific language governing permissions and limitations under the License.
    16   */
    17  
    18  package cache
    19  
    20  import (
    21  	"context"
    22  	"fmt"
    23  	"sync"
    24  	"time"
    25  
    26  	types "github.com/polarismesh/polaris/cache/api"
    27  	"github.com/polarismesh/polaris/store"
    28  )
    29  
    30  var (
    31  	cacheSet = map[string]int{}
    32  )
    33  
    34  const (
    35  	// UpdateCacheInterval 缓存更新时间间隔
    36  	UpdateCacheInterval = 1 * time.Second
    37  )
    38  
    39  // CacheManager 名字服务缓存
    40  type CacheManager struct {
    41  	storage store.Store
    42  	caches  []types.Cache
    43  }
    44  
    45  // Initialize 缓存对象初始化
    46  func (nc *CacheManager) Initialize() error {
    47  	if config.DiffTime != 0 {
    48  		types.DefaultTimeDiff = -1 * (config.DiffTime.Abs())
    49  	}
    50  	if types.DefaultTimeDiff > 0 {
    51  		return fmt.Errorf("cache diff time to pull store must negative number: %+v", types.DefaultTimeDiff)
    52  	}
    53  
    54  	for _, obj := range nc.caches {
    55  		var entryItem *ConfigEntry
    56  		for _, entry := range config.Resources {
    57  			if obj.Name() == entry.Name {
    58  				entryItem = &entry
    59  				break
    60  			}
    61  		}
    62  		if entryItem == nil {
    63  			continue
    64  		}
    65  		if err := obj.Initialize(entryItem.Option); err != nil {
    66  			return err
    67  		}
    68  	}
    69  
    70  	return nil
    71  }
    72  
    73  // update 缓存更新
    74  func (nc *CacheManager) update() error {
    75  	var wg sync.WaitGroup
    76  	for _, entry := range config.Resources {
    77  		index, exist := cacheSet[entry.Name]
    78  		if !exist {
    79  			return fmt.Errorf("cache resource %s not exists", entry.Name)
    80  		}
    81  		wg.Add(1)
    82  		go func(c types.Cache) {
    83  			defer wg.Done()
    84  			_ = c.Update()
    85  		}(nc.caches[index])
    86  	}
    87  
    88  	wg.Wait()
    89  	return nil
    90  }
    91  
    92  // clear 清除caches的所有缓存数据
    93  func (nc *CacheManager) clear() error {
    94  	for _, obj := range nc.caches {
    95  		if err := obj.Clear(); err != nil {
    96  			return err
    97  		}
    98  	}
    99  
   100  	return nil
   101  }
   102  
   103  // Close 关闭所有的 Cache 缓存
   104  func (nc *CacheManager) Close() error {
   105  	for _, obj := range nc.caches {
   106  		if err := obj.Close(); err != nil {
   107  			return err
   108  		}
   109  	}
   110  	return nil
   111  }
   112  
   113  // Start 缓存对象启动协程,定时更新缓存
   114  func (nc *CacheManager) Start(ctx context.Context) error {
   115  	log.Infof("[Cache] cache goroutine start")
   116  
   117  	// 启动的时候,先更新一版缓存
   118  	log.Infof("[Cache] cache update now first time")
   119  	if err := nc.update(); err != nil {
   120  		return err
   121  	}
   122  	log.Infof("[Cache] cache update done")
   123  
   124  	// 启动协程,开始定时更新缓存数据
   125  	go func() {
   126  		ticker := time.NewTicker(nc.GetUpdateCacheInterval())
   127  		defer ticker.Stop()
   128  
   129  		for {
   130  			select {
   131  			case <-ticker.C:
   132  				_ = nc.update()
   133  			case <-ctx.Done():
   134  				return
   135  			}
   136  		}
   137  	}()
   138  
   139  	return nil
   140  }
   141  
   142  // Clear 主动清除缓存数据
   143  func (nc *CacheManager) Clear() error {
   144  	return nc.clear()
   145  }
   146  
   147  // GetUpdateCacheInterval 获取当前cache的更新间隔
   148  func (nc *CacheManager) GetUpdateCacheInterval() time.Duration {
   149  	return UpdateCacheInterval
   150  }
   151  
   152  func (nc *CacheManager) AddListener(cacheIndex types.CacheIndex, listeners []types.Listener) {
   153  	nc.caches[cacheIndex].AddListener(listeners)
   154  }
   155  
   156  // Service 获取Service缓存信息
   157  func (nc *CacheManager) Service() types.ServiceCache {
   158  	return nc.caches[types.CacheService].(types.ServiceCache)
   159  }
   160  
   161  // Instance 获取Instance缓存信息
   162  func (nc *CacheManager) Instance() types.InstanceCache {
   163  	return nc.caches[types.CacheInstance].(types.InstanceCache)
   164  }
   165  
   166  // RoutingConfig 获取路由配置的缓存信息
   167  func (nc *CacheManager) RoutingConfig() types.RoutingConfigCache {
   168  	return nc.caches[types.CacheRoutingConfig].(types.RoutingConfigCache)
   169  }
   170  
   171  // CL5 获取l5缓存信息
   172  func (nc *CacheManager) CL5() types.L5Cache {
   173  	return nc.caches[types.CacheCL5].(types.L5Cache)
   174  }
   175  
   176  // RateLimit 获取限流规则缓存信息
   177  func (nc *CacheManager) RateLimit() types.RateLimitCache {
   178  	return nc.caches[types.CacheRateLimit].(types.RateLimitCache)
   179  }
   180  
   181  // CircuitBreaker 获取熔断规则缓存信息
   182  func (nc *CacheManager) CircuitBreaker() types.CircuitBreakerCache {
   183  	return nc.caches[types.CacheCircuitBreaker].(types.CircuitBreakerCache)
   184  }
   185  
   186  // FaultDetector 获取探测规则缓存信息
   187  func (nc *CacheManager) FaultDetector() types.FaultDetectCache {
   188  	return nc.caches[types.CacheFaultDetector].(types.FaultDetectCache)
   189  }
   190  
   191  // User Get user information cache information
   192  func (nc *CacheManager) User() types.UserCache {
   193  	return nc.caches[types.CacheUser].(types.UserCache)
   194  }
   195  
   196  // AuthStrategy Get authentication cache information
   197  func (nc *CacheManager) AuthStrategy() types.StrategyCache {
   198  	return nc.caches[types.CacheAuthStrategy].(types.StrategyCache)
   199  }
   200  
   201  // Namespace Get namespace cache information
   202  func (nc *CacheManager) Namespace() types.NamespaceCache {
   203  	return nc.caches[types.CacheNamespace].(types.NamespaceCache)
   204  }
   205  
   206  // Client Get client cache information
   207  func (nc *CacheManager) Client() types.ClientCache {
   208  	return nc.caches[types.CacheClient].(types.ClientCache)
   209  }
   210  
   211  // ConfigFile get config file cache information
   212  func (nc *CacheManager) ConfigFile() types.ConfigFileCache {
   213  	return nc.caches[types.CacheConfigFile].(types.ConfigFileCache)
   214  }
   215  
   216  // ConfigGroup get config group cache information
   217  func (nc *CacheManager) ConfigGroup() types.ConfigGroupCache {
   218  	return nc.caches[types.CacheConfigGroup].(types.ConfigGroupCache)
   219  }
   220  
   221  // GetCacher get types.Cache impl
   222  func (nc *CacheManager) GetCacher(cacheIndex types.CacheIndex) types.Cache {
   223  	return nc.caches[cacheIndex]
   224  }
   225  
   226  func (nc *CacheManager) RegisterCacher(cacheType types.CacheIndex, item types.Cache) {
   227  	nc.caches[cacheType] = item
   228  }
   229  
   230  // GetStore get store
   231  func (nc *CacheManager) GetStore() store.Store {
   232  	return nc.storage
   233  }
   234  
   235  // RegisterCache 注册缓存资源
   236  func RegisterCache(name string, index types.CacheIndex) {
   237  	if _, exist := cacheSet[name]; exist {
   238  		log.Warnf("existed cache resource: name = %s", name)
   239  	}
   240  
   241  	cacheSet[name] = int(index)
   242  }