trpc.group/trpc-go/trpc-go@v1.0.3/config/README.md (about) 1 English | [中文](README.zh_CN.md) 2 3 # Introduction 4 5 Configuration management plays an extremely important role in the microservices governance system. The tRPC framework provides a set of standard interfaces for business program development, supporting the retrieval of configuration from multiple data sources, parsing configuration, and perceiving configuration changes. The framework shields the details of data source docking, simplifying development. This article aims to provide users with the following information: 6 7 * What is business configuration and how does it differ from framework configuration. 8 * Some core concepts of business configuration such as: provider, codec, etc. 9 * How to use standard interfaces to retrieve business configurations. 10 * How to perceive changes in configuration items. 11 12 # Concept 13 14 ## What is Business Configuration? 15 16 Business configuration refers to configuration used by the business, defined by the business program in terms of format, meaning, and parameter range. The tRPC framework does not use business configuration nor care about its meaning. The framework only focuses on how to retrieve configuration content, parse configuration, discover configuration changes, and notify the business program. 17 18 The difference between business configuration and framework configuration lies in the subject using the configuration and the management method. Framework configuration is used for tRPC framework and defined by the framework in terms of format and meaning. Framework configuration only supports local file reading mode and is read during program startup to initialize the framework. Framework configuration does not support dynamic updates; if the framework configuration needs to be updated, the program needs to be restarted. 19 20 On the other hand, business configuration supports retrieval from multiple data sources such as local files, configuration centers, databases, etc. If the data source supports configuration item event listening, tRPC framework provides a mechanism to achieve dynamic updating of configurations. 21 22 ## Managing Business Configuration 23 24 For managing business configuration, we recommend the best practice of using a configuration center. Using a configuration center has the following advantages: 25 26 * Avoiding source code leaking sensitive information 27 * Dynamically updating configurations for services 28 * Allowing multiple services to share configurations and avoiding multiple copies of the same configuration 29 * Supporting gray releases, configuration rollbacks, and having complete permission management and operation logs 30 * Business configuration also supports local files. For local files, most use cases involve clients being used as independent tools or programs in the development and debugging phases. The advantage is that it can work without relying on an external system. 31 32 ## What is Multiple Data Sources? 33 34 A data source is the source from which configuration is retrieved and where it is stored. Common data sources include: file, etcd, configmap, env, etc. The tRPC framework supports setting different data sources for different business configurations. The framework uses a plugin-based approach to extend support for more data sources. In the implementation principle section later, we will describe in detail how the framework supports multiple data sources. 35 36 ## What is Codec? 37 38 In business configuration, Codec refers to the format of configurations retrieved from configuration sources. Common configuration file formats include: YAML, JSON, TOML, etc. The framework uses a plugin-based approach to extend support for more decoding formats. 39 40 # Implementation Principle 41 To better understand the use of configuration interfaces and how to dock with data sources, let's take a brief look at how the configuration interface module is implemented. The following diagram is a schematic diagram of the configuration module implementation (not a code implementation class diagram): 42 43 ![trpc](/.resources/user_guide/business_configuration/trpc_en.png) 44 45 The config interface in the diagram provides a standard interface for business code to retrieve configuration items, and each data type has an independent interface that supports returning default values. 46 47 We have already introduced Codec and DataProvider in section 2, and these two modules provide standard interfaces and registration functions to support plugin-based encoding/decoding and data source. Taking multi-data sources as an example, DataProvider provides the following three standard interfaces: 48 49 * Read(): provides how to read the original data of the configuration (raw bytes). 50 * Watch(): provides a callback function that the framework executes when the data source's data changes. 51 52 ```go 53 type DataProvider interface { 54 Name() string 55 Read(string) ([]byte, error) 56 Watch(ProviderCallback) 57 } 58 ``` 59 60 Finally, let's see how to retrieve a business configuration by specifying the data source and decoder: 61 62 ```go 63 // Load etcd configuration file: config.WithProvider("etcd"). 64 c, _ := config.Load("test.yaml", config.WithCodec("yaml"), config.WithProvider("etcd")) 65 // Read String type configuration. 66 c.GetString("auth.user", "admin") 67 ``` 68 69 In this example, the data source is the etcd configuration center, and the business configuration file in the data source is "test.yaml". When the ConfigLoader obtains the "test.yaml" business configuration, it specifies to use YAML format to decode the data content. Finally, the c.GetString("server.app", "default") function is used to obtain the value of the auth.user configuration item in the test.yaml file. 70 71 # Interface Usage 72 73 This article only introduces the corresponding interfaces from the perspective of using business configurations. If users need to develop data source plugins or Codec plugins, please refer to [tRPC-Go Development Configuration Plugin](/docs/developer_guide/develop_plugins/config.md). For specific interface parameters, please refer to the tRPC-Go API manual. 74 75 The tRPC-Go framework provides two sets of interfaces for "reading configuration items" and "watching configuration item changes". 76 77 ## Reading Configuration Items 78 79 Step 1: Selecting Plugins 80 81 Before using the configuration interface, it is necessary to configure data source plugins and their configurations in advance. Please refer to the Plugin Ecology for plugin usage. The tRPC framework supports local file data sources by default. 82 83 Step 2: Plugin Initialization 84 85 Since the data source is implemented using a plugin, tRPC framework needs to initialize all plugins in the server initialization function by reading the "trpc_go.yaml" file. The read operation of business configuration must be carried out after completing trpc.NewServer(). 86 87 ```go 88 import ( 89 trpc "trpc.group/trpc-go/trpc-go" 90 ) 91 // Plugin system will be initialized when the server is instantiated, and all configuration read operations need to be performed after this. 92 trpc.NewServer() 93 ``` 94 95 Step 3: Loading Configuration 96 Load configuration file from data source and return config data structure. The data source type and Codec format can be specified, with the framework defaulting to "file" data source and "YAML" Codec. The interface is defined as follows: 97 98 ```go 99 // Load configuration file: path is the path of the configuration file. 100 func Load(path string, opts ...LoadOption) (Config, error) 101 // Change Codec type, default is "YAML" format. 102 func WithCodec(name string) LoadOption 103 // Change data source, default is "file". 104 func WithProvider(name string) LoadOption 105 ``` 106 107 The sample code is as follows: 108 109 ```go 110 // Load etcd configuration file: config.WithProvider("etcd"). 111 c, _ := config.Load("test1.yaml", config.WithCodec("yaml"), config.WithProvider("etcd")) 112 // Load local configuration file, codec is json, data source is file. 113 c, _ := config.Load("../testdata/auth.yaml", config.WithCodec("json"), config.WithProvider("file")) 114 // Load local configuration file, default Codec is yaml, data source is file. 115 c, _ := config.Load("../testdata/auth.yaml") 116 ``` 117 118 Step 4: Retrieving Configuration Items 119 Get the value of a specific configuration item from the config data structure. Default values can be set, and the framework provides the following standard interfaces: 120 121 ```go 122 // Config general interface. 123 type Config interface { 124 Load() error 125 Reload() 126 Get(string, interface{}) interface{} 127 Unmarshal(interface{}) error 128 IsSet(string) bool 129 GetInt(string, int) int 130 GetInt32(string, int32) int32 131 GetInt64(string, int64) int64 132 GetUint(string, uint) uint 133 GetUint32(string, uint32) uint32 134 GetUint64(string, uint64) uint64 135 GetFloat32(string, float32) float32 136 GetFloat64(string, float64) float64 137 GetString(string, string) string 138 GetBool(string, bool) bool 139 Bytes() []byte 140 } 141 ``` 142 143 The sample code is as follows: 144 145 ```go 146 // Read bool type configuration. 147 c.GetBool("server.debug", false) 148 // Read String type configuration. 149 c.GetString("server.app", "default") 150 ``` 151 152 ## Watching configuration item changes 153 154 The framework provides a Watch mechanism for business programs to define and execute their own logic based on received configuration item change events in KV-type configuration centers. The monitoring interface is designed as follows: 155 156 ```go 157 // Get retrieves kvconfig by name. 158 func Get(name string) KVConfig 159 160 // KVConfig is the interface for KV configurations. 161 type KVConfig interface { 162 KV 163 Watcher 164 Name() string 165 } 166 167 // Watcher is the interface for monitoring. 168 type Watcher interface { 169 // Watch monitors the changes of the configuration item key. 170 Watch(ctx context.Context, key string, opts ...Option) (<-chan Response, error) 171 } 172 173 // Response represents the response from the configuration center. 174 type Response interface { 175 // Value gets the value corresponding to the configuration item. 176 Value() string 177 // MetaData provides additional metadata information. 178 // Configuration Option options can be used to carry extra functionality implementation of different configuration centers, such as namespace, group, lease, etc. 179 MetaData() map[string]string 180 // Event gets the type of the Watch event. 181 Event() EventType 182 } 183 184 // EventType represents the types of events monitored for configuration changes. 185 type EventType uint8 186 const ( 187 // EventTypeNull represents an empty event. 188 EventTypeNull EventType = 0 189 // EventTypePut represents a set or update configuration event. 190 EventTypePut EventType = 1 191 // EventTypeDel represents a delete configuration item event. 192 EventTypeDel EventType = 2 193 ) 194 ``` 195 196 The following example demonstrates how a business program monitors the "test.yaml" file on etcd, 197 prints configuration item change events, and updates the configuration: 198 199 ```go 200 import ( 201 "sync/atomic" 202 // ... 203 ) 204 type yamlFile struct { 205 Server struct { 206 App string 207 } 208 } 209 var cfg atomic.Value // Concurrent-safe Value. 210 // Listen to remote configuration changes on etcd using the Watch interface in trpc-go/config. 211 c, _ := config.Get("etcd").Watch(context.TODO(), "test.yaml") 212 go func() { 213 for r := range c { 214 yf := &yamlFile{} 215 fmt.Printf("Event: %d, Value: %s", r.Event(), r.Value()) 216 if err := yaml.Unmarshal([]byte(r.Value()), yf); err == nil { 217 cfg.Store(yf) 218 } 219 } 220 }() 221 // After the configuration is initialized, the latest configuration object can be obtained through the Load method of atomic.Value. 222 cfg.Load().(*yamlFile) 223 ``` 224 225 # Data Source Integration 226 227 Refer to [trpc-ecosystem/go-config-etcd](https://github.com/trpc-ecosystem/go-config-etcd).