Kratos use nacos as config center

 1package main
 2
 3import (
 4        "flag"
 5        "os"
 6
 7        "ldap-manager/internal/conf"
 8
 9        nacos_config "github.com/go-kratos/kratos/contrib/config/nacos/v2"
10        "github.com/go-kratos/kratos/v2"
11        "github.com/go-kratos/kratos/v2/config"
12        "github.com/go-kratos/kratos/v2/log"
13        "github.com/go-kratos/kratos/v2/middleware/tracing"
14        "github.com/go-kratos/kratos/v2/transport/grpc"
15        "github.com/go-kratos/kratos/v2/transport/http"
16        "github.com/nacos-group/nacos-sdk-go/clients"
17        "github.com/nacos-group/nacos-sdk-go/common/constant"
18        "github.com/nacos-group/nacos-sdk-go/vo"
19)
20
21func main() {
22        nacosHost := os.Getenv("NACOS_HOST")
23        if nacosHost == "" {
24                nacosHost = "127.0.0.1"
25        }
26        sc := []constant.ServerConfig{
27                *constant.NewServerConfig(nacosHost, 8848),
28        }
29
30        namespaceId := os.Getenv("NAMESPACE_ID")
31
32        cc := &constant.ClientConfig{
33                NamespaceId:         namespaceId, //namespace id
34                TimeoutMs:           5000,
35                NotLoadCacheAtStart: true,
36                LogLevel:            "error",
37        }
38
39        // a more graceful way to create naming client
40        client, err := clients.NewConfigClient(
41                vo.NacosClientParam{
42                        ClientConfig:  cc,
43                        ServerConfigs: sc,
44                },
45        )
46        if err != nil {
47                panic(err)
48        }
49
50        c := config.New(
51                config.WithSource(
52                        nacos_config.NewConfigSource(
53                                client,
54                                nacos_config.WithDataID("test.yaml"),
55                                nacos_config.WithGroup("test"),
56                                //info level is noisy, always mess your console
57                                nacos_config.WithLogLevel("error"),
58                        ),
59                ),
60        )
61        //always remember close
62        defer c.Close()
63        //load config
64        if err := c.Load(); err != nil {
65                panic(err)
66        }
67
68        var bc conf.Bootstrap
69        //config covert to go struct
70        if err := c.Scan(&bc); err != nil {
71                panic(err)
72        }
73        //keep sync from server
74        c.Watch("data", func(key string, value config.Value) {
75                value.Scan(&bc.Data)
76        })
77}