Nacos v2 SDK integration client with service registration and configuration management.
π― Service Registration: Auto IP detection with ephemeral instance registration β‘ Service Discovery: Health-check based instance selection with group support π Config Management: Dynamic configuration retrieval from Nacos config center π Online/Offline Control: Graceful service state management without restart π Multi-Environment: Namespace and group-based service isolation
go get github.com/go-xlan/go-nacos-v2This example demonstrates complete service registration, discovery, and graceful shutdown handling.
package main
import (
"context"
"os"
"os/signal"
"time"
"github.com/go-xlan/go-nacos-v2/nacosv2"
"github.com/nacos-group/nacos-sdk-go/common/constant"
"github.com/yyle88/must"
"github.com/yyle88/neatjson/neatjsons"
"github.com/yyle88/rese"
"github.com/yyle88/zaplog"
)
func main() {
config := &nacosv2.Config{
Endpoint: "127.0.0.1:8848",
AppName: "demo1x",
Address: "0.0.0.0:8080",
Group: "DEFAULT_GROUP",
Namespace: "public",
}
clientOptions := []constant.ClientOption{
constant.WithCacheDir("/tmp/nacos/cache"),
constant.WithLogDir("/tmp/nacos/log"),
}
client := rese.P1(nacosv2.NewNacosClient(config, clientOptions, zaplog.ZAP.NewZap("module", "demo1x")))
must.Done(client.RegisterService())
must.Done(client.Online(context.Background()))
serviceInstance := rese.P1(client.GetServiceInstance(context.Background(), "demo1x"))
zaplog.SUG.Debugln(neatjsons.S(serviceInstance))
ctx, cancelFunc := context.WithTimeout(context.Background(), time.Minute)
defer cancelFunc()
waitChan := make(chan os.Signal, 1)
signal.Notify(waitChan, os.Interrupt)
select {
case <-waitChan:
zaplog.SUG.Debugln("Received Ctrl+C, shutting down...")
case <-ctx.Done():
zaplog.SUG.Debugln("Context timeout, shutting down...")
}
must.Done(client.Offline(context.Background()))
must.Done(client.DeregisterService())
zaplog.SUG.Debugln("Returning from main(), exiting...")
}β¬οΈ Source: Source
config := &nacosv2.Config{
Endpoint: "127.0.0.1:8848", // Nacos server address
AppName: "my-service", // Service name
Address: "0.0.0.0:8080", // Service bind address
Group: "DEFAULT_GROUP", // Service group
Namespace: "public", // Namespace ID
}clientOptions := []constant.ClientOption{
constant.WithCacheDir("/tmp/nacos/cache"),
constant.WithLogDir("/tmp/nacos/log"),
constant.WithLogLevel("info"),
constant.WithNotLoadCacheAtStart(true),
}NewNacosClient(config, options, zapLog)- Create Nacos client with auto service info detectionRegisterService()- Register service instance to NacosDeregisterService()- Remove service instance from NacosOnline(ctx)- Bring service online by re-registeringOffline(ctx)- Take service offline by deregisteringGetServiceInstance(ctx, serviceName)- Discover healthy service instanceGetConfig(ctx, dataID)- Retrieve configuration from config center
The client detects service IP from allowed network interfaces:
- macOS:
en0(Ethernet/Wi-Fi) - Linux:
eth0(Ethernet) - VMware:
ens224 - AWS EC2:
ens5
Falls back to 0.0.0.0 detection when bind address is configured.
All registered instances are ephemeral with health checks enabled, ensuring:
- Auto deregistration on service crash
- Real-time instance health status
- Load balancing based on healthy instances
Use namespaces to separate environments:
// Production environment
prodConfig := &nacosv2.Config{
Namespace: "prod-namespace-id",
// ...
}
// Testing environment
testConfig := &nacosv2.Config{
Namespace: "test-namespace-id",
// ...
}Register service instance:
client := rese.P1(nacosv2.NewNacosClient(config, clientOptions, zapLog))
rese.V0(client.RegisterService())Deregister on shutdown:
defer rese.V0(client.DeregisterService())Get healthy service instance:
instance := rese.P1(client.GetServiceInstance(context.Background(), "service-name"))
fmt.Printf("Instance: %s:%d\n", instance.Ip, instance.Port)Retrieve configuration:
configData := rese.P1(client.GetConfig(context.Background(), "database-config"))
fmt.Println("Config:", configData)Bring service online:
rese.V0(client.Online(context.Background()))Take service offline (without stopping):
rese.V0(client.Offline(context.Background()))Production configuration:
prodConfig := &nacosv2.Config{
Endpoint: "nacos-prod.company.com:8848",
AppName: "payment-service",
Namespace: "prod-namespace-id",
Group: "PROD_GROUP",
}Testing configuration:
testConfig := &nacosv2.Config{
Endpoint: "nacos-test.company.com:8848",
AppName: "payment-service",
Namespace: "test-namespace-id",
Group: "TEST_GROUP",
}MIT License. See LICENSE.
Contributions are welcome! Report bugs, suggest features, and contribute code:
- π Found a mistake? Open an issue on GitHub with reproduction steps
- π‘ Have a feature idea? Create an issue to discuss the suggestion
- π Documentation confusing? Report it so we can improve
- π Need new features? Share the use cases to help us understand requirements
- β‘ Performance issue? Help us optimize through reporting slow operations
- π§ Configuration problem? Ask questions about complex setups
- π’ Follow project progress? Watch the repo to get new releases and features
- π Success stories? Share how this package improved the workflow
- π¬ Feedback? We welcome suggestions and comments
New code contributions, follow this process:
- Fork: Fork the repo on GitHub (using the webpage UI).
- Clone: Clone the forked project (
git clone https://github.com/yourname/repo-name.git). - Navigate: Navigate to the cloned project (
cd repo-name) - Branch: Create a feature branch (
git checkout -b feature/xxx). - Code: Implement the changes with comprehensive tests
- Testing: (Golang project) Ensure tests pass (
go test ./...) and follow Go code style conventions - Documentation: Update documentation to support client-facing changes and use significant commit messages
- Stage: Stage changes (
git add .) - Commit: Commit changes (
git commit -m "Add feature xxx") ensuring backward compatible code - Push: Push to the branch (
git push origin feature/xxx). - PR: Open a merge request on GitHub (on the GitHub webpage) with detailed description.
Please ensure tests pass and include relevant documentation updates.
Welcome to contribute to this project via submitting merge requests and reporting issues.
Project Support:
- β Give GitHub stars if this project helps you
- π€ Share with teammates and (golang) programming friends
- π Write tech blogs about development tools and workflows - we provide content writing support
- π Join the ecosystem - committed to supporting open source and the (golang) development scene
Have Fun Coding with this package! πππ