Install agollo v5
masterTo use the Agollo Go client, install the latest version of the v5 package using go get.
go get -u github.com/apolloconfig/agollo/v5@latestrepository·master·Indexed 20 days ago
https://github.com/apolloconfig/agolloA high-performance Go client for the Apollo configuration center. It provides real-time configuration synchronization, gray releases, and fallback mechanisms. Key features include support for custom AppConfig initialization, namespace-specific configuration retrieval, ChangeListeners for monitoring updates, and extensible components for HTTP authentication, load balancing, logging, and caching.
To use the Agollo Go client, install the latest version of the v5 package using go get.
go get -u github.com/apolloconfig/agollo/v5@latestTo start using Agollo, you must define an AppConfig and initialize the client using agollo.StartWithConfig.
AppConfig requires the following fields:
AppID: The unique identifier for your application.Cluster: The deployment cluster (e.g., dev).IP: The Apollo server address (e.g., http://localhost:8080).NamespaceName: The specific namespace to monitor.IsBackupConfig: A boolean indicating if fallback configuration should be used.Secret: The access key/secret for configuration access.agollo.StartWithConfig takes a provider function that returns your *config.AppConfig and an error.
package main
import (
"fmt"
"github.com/apolloconfig/agollo/v5"
"github.com/apolloconfig/agollo/v5/env/config"
)
func main() {
c := &config.AppConfig{
AppID: "testApplication_yang",
Cluster: "dev",
IP: "http://localhost:8080",
NamespaceName: "dubbo",
IsBackupConfig: true,
Secret: "6ce3ff7e96a24335a9634fe9abca6d51",
}
client, _ := agollo.StartWithConfig(func() (*config.AppConfig, error) {
return c, nil
})
fmt.Println("Apollo configuration initialized successfully")
// Use your apollo key to test
cache := client.GetConfigCache(c.NamespaceName)
value, _ := cache.Get("key")
fmt.Println(value)
}The server package provides utilities for managing a local cache of Apollo cluster nodes (servers). It allows you to track which servers are available, set specific nodes as 'down' (unavailable), and manage connection retry logic based on a configured period.
Key concepts:
configIp (the configuration service address).SetDownNode.nextTryConnTime to prevent immediate reconnection attempts to failing nodes.You can start the Agollo client in two ways: using default file configurations or providing a custom configuration function.
Use Start() to initialize the client using the default configuration files recognized by the library.
Use StartWithConfig(loadAppConfig func() (*config.AppConfig, error)) to provide a custom function that returns an *config.AppConfig. This is useful if you need to load configuration from a non-standard source or perform custom logic during initialization.
If MustStart is set to true in your configuration and no configuration is read during startup, StartWithConfig will return an error.
package main
import (
"github.com/apolloconfig/agollo/v5"
"github.com/apolloconfig/agollo/v5/env/config"
)
func main() {
// Custom configuration approach
client, err := agollo.StartWithConfig(func() (*config.AppConfig, error) {
// Return your custom AppConfig here
return &config.AppConfig{
// ... configuration fields
}, nil
})
if err != nil {
panic(err)
}
defer client.Close()
// Use the client...
}Once the client is initialized, you can access configuration values via the local cache. Use client.GetConfigCache(namespaceName) to retrieve the cache object for a specific namespace, then use the .Get(key) method to fetch the value associated with a specific key.
// Assuming 'client' is an initialized agollo client
cache := client.GetConfigCache("dubbo")
value, err := cache.Get("key")
if err == nil {
fmt.Println(value)
}While the shorthand methods (like GetStringValue) target the default namespace, you can access specific namespaces using GetConfig or GetConfigAndInit.
GetConfig(namespace string) *storage.Config: Retrieves the configuration object for the specified namespace. If the namespace is not currently in the cache, it will attempt to sync it.GetConfigCache(namespace string) agcache.CacheInterface: Returns the underlying cache interface for a specific namespace.Once you have a *storage.Config object, you can call its specific getter methods (e.g., GetStringValue, GetIntValue) to retrieve values from that namespace.
// Get config for a specific namespace
cfg := client.GetConfig("production-namespace")
if cfg != nil {
val := cfg.GetStringValue("database.url", "localhost")
fmt.Println(val)
}Use SetServers to initialize or update the list of available Apollo servers for a specific configuration service address.
Signature:
func SetServers(configIp string, serverMap map[string]*config.ServerInfo)
import (
"github.com/apolloconfig/agollo/v5/env/server"
"github.com/apolloconfig/agollo/v5/env/config"
)
serverMap := map[string]*config.ServerInfo{
"192.168.1.1:8080": {HomepageURL: "http://192.168.1.1:8080"},
"192.168.1.2:8080": {HomepageURL: "http://192.168.1.2:8080"},
}
server.SetServers("127.0.0.1:8080", serverMap)Use GetServers to retrieve the map of available server information associated with a specific configuration IP address.
Signature:
func GetServers(configIp string) map[string]*config.ServerInfo
Returns nil if no servers are registered for the provided configIp.
import "github.com/apolloconfig/agollo/v5/env/server"
// Retrieve the map of server info
servers := server.GetServers("127.0.0.1:8080")
if servers != nil {
for host, info := range servers {
fmt.Printf("Host: %s, URL: %s\n", host, info.HomepageURL)
}
}The Client interface provides several methods to retrieve configuration values from the default namespace. These methods handle type conversion and allow for default values if a key is missing.
GetValue(key string) string: Returns the value as a string.GetStringValue(key string, defaultValue string) string: Returns the string value or the provided default.GetIntValue(key string, defaultValue int) int: Returns the integer value or the provided default.GetFloatValue(key string, defaultValue float64) float64: Returns the float value or the provided default.GetBoolValue(key string, defaultValue bool) bool: Returns the boolean value or the provided default.GetStringSliceValue(key string, defaultValue []string) []string: Returns a slice of strings (delimited by ,).GetIntSliceValue(key string, defaultValue []int) []int: Returns a slice of integers (delimited by ,).Note: All these methods target the default namespace. To target a specific namespace, use GetConfig(namespace string).
// Example of retrieving various types from the default namespace
valStr := client.GetStringValue("app.name", "default-app")
valInt := client.GetIntValue("app.port", 8080)
valBool := client.GetBoolValue("app.debug", false)
valSlice := client.GetStringSliceValue("app.tags", []string{"prod"})Use SetNextTryConnTime to define how long the client should wait before attempting to reconnect to a configuration service after a failure.
Signature:
func SetNextTryConnTime(configIp string, nextPeriod int64)
nextPeriod: The number of seconds to wait. If set to 0, it defaults to the internal nextTryConnectPeriod (currently 30 seconds).nextTryConnTime for the configIp to now + nextPeriod.import "github.com/apolloconfig/agollo/v5/env/server"
// Set a 60-second retry period for the config service
server.SetNextTryConnTime("127.0.0.1:8080", 60)Use SetSignature to provide a custom implementation of the auth.HTTPAuth interface. This allows you to define how HTTP authorization headers or signatures are generated for requests made by the Agollo client. The provided implementation is registered globally via the extension package.
import "github.com/apolloconfig/agollo/v5"
// Assuming you have an implementation of auth.HTTPAuth
var myAuth auth.HTTPAuth
agollo.SetSignature(myAuth)Agollo allows you to react to configuration updates by adding a ChangeListener.
Use AddChangeListener(listener storage.ChangeListener) to register a new listener. When a configuration in a namespace changes, the listener will be notified.
Use RemoveChangeListener(listener storage.ChangeListener) to stop receiving updates for a specific listener.
If you want to enable event dispatching for specific keys, call UseEventDispatch(). This adds a specialized listener that can be used to trigger application-level events when specific configuration keys change.
// Define a listener
listener := myCustomListener
// Add it to the client
client.AddChangeListener(listener)
// Optionally enable event dispatching
client.UseEventDispatch()
// Remember to clean up if necessary
client.RemoveChangeListener(listener)