github.com/polarismesh/polaris@v1.17.8/store/store.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 store 19 20 import ( 21 "errors" 22 "fmt" 23 "os" 24 "sync" 25 ) 26 27 // Config Store的通用配置 28 type Config struct { 29 Name string 30 Option map[string]interface{} 31 } 32 33 var ( 34 // StoreSlots store slots 35 StoreSlots = make(map[string]Store) 36 37 once = &sync.Once{} 38 config = &Config{} 39 ) 40 41 // RegisterStore 注册一个新的Store 42 func RegisterStore(s Store) error { 43 name := s.Name() 44 if _, ok := StoreSlots[name]; ok { 45 return errors.New("store name already existed") 46 } 47 48 StoreSlots[name] = s 49 return nil 50 } 51 52 // GetStore 获取Store 53 func GetStore() (Store, error) { 54 name := config.Name 55 if name == "" { 56 return nil, errors.New("store name is empty") 57 } 58 59 store, ok := StoreSlots[name] 60 if !ok { 61 return nil, fmt.Errorf("store `%s` not found", name) 62 } 63 64 initialize(store) 65 return store, nil 66 } 67 68 // SetStoreConfig 设置store的conf 69 func SetStoreConfig(conf *Config) { 70 config = conf 71 } 72 73 // initialize 包裹了初始化函数,在GetStore的时候会在自动调用,全局初始化一次 74 func initialize(s Store) { 75 once.Do(func() { 76 fmt.Printf("[Store][Info] current use store plugin : %s\n", s.Name()) 77 if err := s.Initialize(config); err != nil { 78 fmt.Printf("[ERROR] initialize store `%s` fail: %v", s.Name(), err) 79 os.Exit(1) 80 } 81 }) 82 }