Recently, I've been playing with golang recently. I put all online data in redis. The previously written configuration is not suitable. Hot loading is the king's way!
As the saying goes, a programmer who can't search is not a good programmer
After observing the writing methods of other big men, most of them are adopted Timer + goroutine
Realized. It's not difficult. Start code
Configuration file structure
If our configuration file is a JSON file, it should be like this
// conf.json
{
"host": "127.0.0.1",
"port": 6379,
"passwd": "",
"db": 0
}
The first thing is to write a structure exactly like it
//JSON configuration file structure
type content struct {host string ` JSON: "host" '
port Int ` JSON: "port"'
passwd string ` JSON: "passwd" '
DB Int ` JSON: "DB"'}
If it is not safe to continue to write operation functions on this structure, serialized JSON is also a direct operation pointer. Before they split their trial and error, and finally let them together 233
Optimize structure
The file name, synchronization lock, last modification time and configuration file structure are integrated together
//Configuration structure
type config struct {file string
lastmodifytime Int64
lock * sync. Rwmutex
data interface {}}}
Write factory functions for instance configuration (this is a conventional rule. You can verify the specific source by yourself. It has many advantages)
func NewConfig(filename string, data interface{}) *Config {
conf := &Config{
Filename: filename,
Data: data,
Lock: &sync.RWMutex{},
}
conf.parse()
go conf.reload()
return conf
}
Here, the configuration structure is configured with default parameters. The external input parameters are The file name of the configuration file and Configuration file structure Here, the data type is the interface type. The advantage is that Config
Can be independent, code Multiple reuse 。 We also used it conf.parse()
Method, parse the file for the first time, go conf.reload()
Method starts a goroutine run separately (see the following for specific effects), and the result of course returns to the ontology
-Read the rest-