agollo

repository·master·Indexed 20 days ago

https://github.com/apolloconfig/agollo

A 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.

Tokens
4.1K
Snippets
16
Records
20
Agent score
73%

What's inside agollo

  1. Initialize agollo with AppConfig

    master

    To 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)
    }
  2. Manage Apollo server nodes with the server package

    master

    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:

    • Server Mapping: Servers are grouped by a configIp (the configuration service address).
    • Node Health: You can mark specific server hosts as down using SetDownNode.
    • Retry Logic: The package tracks nextTryConnTime to prevent immediate reconnection attempts to failing nodes.
  3. Initialize the Agollo client

    master

    You can start the Agollo client in two ways: using default file configurations or providing a custom configuration function.

    Option 1: Default Configuration

    Use Start() to initialize the client using the default configuration files recognized by the library.

    Option 2: Custom Configuration

    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...
    }
  4. Retrieve configuration values from the cache

    master

    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)
    }
  5. Retrieve configuration for a specific namespace

    master

    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)
    }
  6. Register a set of servers

    master

    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)
  7. Get available servers for a configuration IP

    master

    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)
        }
    }
  8. Use the Client interface to retrieve configuration values

    master

    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.

    Available Value Methods

    • 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"})
  9. Set the next connection retry time

    master

    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).
    • This sets the 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)
  10. Configure custom HTTP authentication with SetSignature

    master

    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)
  11. Monitor configuration changes with ChangeListeners

    master

    Agollo allows you to react to configuration updates by adding a ChangeListener.

    Registering a Listener

    Use AddChangeListener(listener storage.ChangeListener) to register a new listener. When a configuration in a namespace changes, the listener will be notified.

    Removing a Listener

    Use RemoveChangeListener(listener storage.ChangeListener) to stop receiving updates for a specific listener.

    Event Dispatching

    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)