Skip to content

Commit 8bf19b6

Browse files
authored
feat/add_createAndPublishConfig_api (#248)
* feat: add UpsertAndPublishConfigFile interface * chore: add config UpsertAndPublishConfigFile example
1 parent 3835534 commit 8bf19b6

File tree

16 files changed

+271
-26
lines changed

16 files changed

+271
-26
lines changed

api.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,8 @@ type ConfigAPI interface {
151151
UpdateConfigFile(namespace, fileGroup, fileName, content string) error
152152
// PublishConfigFile publish configuration file
153153
PublishConfigFile(namespace, fileGroup, fileName string) error
154+
// UpsertAndPublishConfigFile insert and publish configuration file
155+
UpsertAndPublishConfigFile(namespace, fileGroup, fileName, content string) error
154156
}
155157

156158
// ConfigGroupAPI .

api/config_file.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,8 @@ type ConfigFileAPI interface {
4141
UpdateConfigFile(namespace, fileGroup, fileName, content string) error
4242
// PublishConfigFile 发布配置文件
4343
PublishConfigFile(namespace, fileGroup, fileName string) error
44+
// UpsertAndPublishConfigFile 创建配置文件并发布
45+
UpsertAndPublishConfigFile(namespace, fileGroup, fileName, content string) error
4446
}
4547

4648
type ConfigGroupAPI interface {

api/config_file_impl.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,11 @@ func (c *configFileAPI) PublishConfigFile(namespace, fileGroup, fileName string)
8282
return c.context.GetEngine().SyncPublishConfigFile(namespace, fileGroup, fileName)
8383
}
8484

85+
// UpsertAndPublishConfigFile 创建配置文件并发布
86+
func (c *configFileAPI) UpsertAndPublishConfigFile(namespace, fileGroup, fileName, content string) error {
87+
return c.context.GetEngine().SyncUpsertAndPublishConfigFile(namespace, fileGroup, fileName, content)
88+
}
89+
8590
// SDKContext 获取SDK上下文
8691
func (c *configFileAPI) SDKContext() SDKContext {
8792
return c.context

api_config.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,11 @@ func (c *configAPI) PublishConfigFile(namespace, fileGroup, fileName string) err
9393
return c.rawAPI.PublishConfigFile(namespace, fileGroup, fileName)
9494
}
9595

96+
// UpsertAndPublishConfigFile 创建配置文件并发布
97+
func (c *configAPI) UpsertAndPublishConfigFile(namespace, fileGroup, fileName, content string) error {
98+
return c.rawAPI.UpsertAndPublishConfigFile(namespace, fileGroup, fileName, content)
99+
}
100+
96101
// SDKContext 获取SDK上下文
97102
func (c *configAPI) SDKContext() api.SDKContext {
98103
return c.rawAPI.SDKContext()

examples/configuration/crud/main.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,7 @@ func main() {
103103
r.GET("/publish", publishHandler)
104104
r.GET("/get", getHandler)
105105
r.GET("/fetch", fetchHandler)
106+
r.GET("/upsertAndPublish", upsertAndPublishHandler)
106107
log.Printf("listening at %s\n", port)
107108
err = r.Run(port)
108109
if err != nil {
@@ -277,6 +278,31 @@ func fetchHandler(c *gin.Context) {
277278
c.String(http.StatusOK, "got config file content:\n %s\n", configFileFromFetch.GetContent())
278279
}
279280

281+
// 创建并发布配置文件
282+
func upsertAndPublishHandler(c *gin.Context) {
283+
var req struct {
284+
Namespace string `json:"namespace"`
285+
FileGroup string `json:"config-group"`
286+
FileName string `json:"config-name"`
287+
Content string `json:"content"`
288+
}
289+
// 尝试绑定JSON,如果失败则使用默认参数
290+
c.ShouldBindJSON(&req)
291+
// 如果请求体中没有传入需要的参数,则从启动参数中取值
292+
finalNamespace := getParamValue(req.Namespace, namespace)
293+
finalFileGroup := getParamValue(req.FileGroup, fileGroup)
294+
finalFileName := getParamValue(req.FileName, fileName)
295+
finalContent := getParamValue(req.Content, content)
296+
297+
if err := configAPI.UpsertAndPublishConfigFile(finalNamespace, finalFileGroup, finalFileName, finalContent); err != nil {
298+
log.Printf("failed to upsert and publish config file. err:%+v", err)
299+
c.String(http.StatusInternalServerError, "upsert and publish failed: %v", err)
300+
return
301+
}
302+
log.Println("upsert and publish config file success.")
303+
c.String(http.StatusOK, "upsert and publish success")
304+
}
305+
280306
func jsonString(v interface{}) string {
281307
b, err := json.Marshal(v)
282308
if err != nil {

examples/configuration/encrypt/main.go

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,14 @@ func main() {
4949
}
5050

5151
// 获取远程加密配置文件
52-
configFile, err := configAPI.GetConfigFile(namespace, fileGroup, fileName)
52+
configFile, err := configAPI.FetchConfigFile(&polaris.GetConfigFileRequest{
53+
GetConfigFileRequest: &model.GetConfigFileRequest{
54+
Namespace: namespace,
55+
FileGroup: fileGroup,
56+
FileName: fileName,
57+
Subscribe: true,
58+
},
59+
})
5360
if err != nil {
5461
log.Println("fail to get config.", err)
5562
return

examples/configuration/fallback/main.go

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,14 @@ func main() {
3838
fileGroup := "polaris-config-example"
3939
fileName := "example.yaml"
4040

41-
configFile, err := configAPI.GetConfigFile(namespace, fileGroup, fileName)
41+
configFile, err := configAPI.FetchConfigFile(&polaris.GetConfigFileRequest{
42+
GetConfigFileRequest: &model.GetConfigFileRequest{
43+
Namespace: namespace,
44+
FileGroup: fileGroup,
45+
FileName: fileName,
46+
Subscribe: true,
47+
},
48+
})
4249
if err != nil {
4350
log.Println("fail to get config.", err)
4451
return
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
GOPATH ?= $(shell go env GOPATH)
2+
3+
# Ensure GOPATH is set before running build process.
4+
ifeq "$(GOPATH)" ""
5+
$(error Please set the environment variable GOPATH before running `make`)
6+
endif
7+
8+
.PHONY: build
9+
build: clean
10+
go build -o bin *.go
11+
12+
.PHONY: run
13+
run: build
14+
./bin
15+
16+
.PHONY: clean
17+
clean:
18+
rm -f bin
19+
rm -rf polaris
20+

examples/configuration/group/main.go

Lines changed: 64 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@ package main
2020
import (
2121
"encoding/json"
2222
"flag"
23-
"fmt"
2423
"log"
2524
"sync"
2625

@@ -35,30 +34,90 @@ var (
3534

3635
func init() {
3736
flag.StringVar(&namesapceVal, "namespace", "default", "namespace")
38-
flag.StringVar(&groupVal, "group", "group", "group")
37+
flag.StringVar(&groupVal, "group", "polaris-config-example", "group")
38+
}
39+
40+
// isConfigGroupEqual 比较两个配置组是否相等(忽略数组顺序)
41+
func isConfigGroupEqual(before, after []*model.SimpleConfigFile) bool {
42+
if len(before) != len(after) {
43+
return false
44+
}
45+
46+
// 创建 map 用于快速查找和比较
47+
beforeMap := make(map[string]*model.SimpleConfigFile)
48+
for _, file := range before {
49+
key := file.Namespace + "/" + file.FileGroup + "/" + file.FileName
50+
beforeMap[key] = file
51+
}
52+
53+
// 检查 after 中的每个文件是否在 before 中存在且内容相同
54+
for _, file := range after {
55+
key := file.Namespace + "/" + file.FileGroup + "/" + file.FileName
56+
beforeFile, exists := beforeMap[key]
57+
if !exists {
58+
return false
59+
}
60+
// 比较版本号和 MD5
61+
if beforeFile.Version != file.Version || beforeFile.Md5 != file.Md5 {
62+
return false
63+
}
64+
}
65+
66+
return true
3967
}
4068

4169
func main() {
4270
flag.Parse()
71+
log.Printf("Starting config group example with namespace: %s, group: %s", namesapceVal, groupVal)
72+
4373
configAPI, err := polaris.NewConfigGroupAPI()
4474

4575
if err != nil {
46-
fmt.Println("fail to start example.", err)
76+
log.Printf("fail to create ConfigGroupAPI: %v", err)
4777
return
4878
}
79+
log.Println("ConfigGroupAPI created successfully")
4980

81+
log.Printf("Fetching config group: namespace=%s, group=%s", namesapceVal, groupVal)
5082
group, err := configAPI.GetConfigGroup(namesapceVal, groupVal)
5183
if err != nil {
52-
log.Panic(err)
84+
log.Panicf("fail to get config group: %v", err)
5385
return
5486
}
87+
88+
// 获取配置组中的所有文件
89+
files, revision, success := group.GetFiles()
90+
if !success {
91+
log.Println("Warning: Failed to get files from config group or group is empty")
92+
} else {
93+
log.Printf("Config group fetched successfully, revision: %s, file count: %d", revision, len(files))
94+
}
95+
96+
// 打印配置组中的所有文件名
97+
if len(files) > 0 {
98+
log.Println("Config files in group:")
99+
for _, file := range files {
100+
log.Printf(" - %s (version: %d, md5: %s)", file.FileName, file.Version, file.Md5)
101+
}
102+
} else {
103+
log.Println("No config files found in group")
104+
}
105+
106+
log.Println("Adding change listener for config group...")
55107
group.AddChangeListener(func(event *model.ConfigGroupChangeEvent) {
108+
// 判断配置是否真的发生了变化(忽略数组顺序)
109+
if isConfigGroupEqual(event.Before, event.After) {
110+
//log.Println("Config group polled, but no changes detected (content unchanged)")
111+
return
112+
}
113+
56114
before, _ := json.Marshal(event.Before)
57115
after, _ := json.Marshal(event.After)
58-
59116
log.Printf("receive config_group change event\nbefore: %s\nafter: %s", string(before), string(after))
60117
})
118+
log.Println("Change listener added successfully")
61119

120+
log.Println("Listening for config group changes... Press Ctrl+C to exit")
62121
wait := sync.WaitGroup{}
63122
wait.Add(1)
64123
wait.Wait()
Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
global:
22
serverConnector:
33
addresses:
4-
- 127.0.0.1:8091
4+
- ${POLARIS_SERVER}:8091
55
config:
66
configConnector:
77
addresses:
8-
- 127.0.0.1:8093
8+
- ${POLARIS_SERVER}:8093
9+
token: ${POLARIS_TOKEN}

0 commit comments

Comments
 (0)