From 7ff71fed629ce14e37f00a3df4edaa37c216efe7 Mon Sep 17 00:00:00 2001 From: Wu <88076398+dengWuuu@users.noreply.github.com> Date: Tue, 7 Feb 2023 13:16:19 +0800 Subject: [PATCH] feat: add nacos example (#34) * feat: add one more hertz server in standard example * feat: add one more hertz server in custom_config example * refactor: put code in the main function in extract method * chore: change service name * feat: add different Configuration example * feat: add post method and param is json * style: change print * style: use two stage import * style: use gofumpt to format the code * refactor: made new code into a new folder * chore: reset previous code --- .../client/main.go | 164 ++++++++++++++++++ .../server/main.go | 126 ++++++++++++++ .../standard_multiple_server/client/main.go | 46 +++++ .../standard_multiple_server/server/main.go | 78 +++++++++ 4 files changed, 414 insertions(+) create mode 100644 nacos/examples/custom_config_multiple_server/client/main.go create mode 100644 nacos/examples/custom_config_multiple_server/server/main.go create mode 100644 nacos/examples/standard_multiple_server/client/main.go create mode 100644 nacos/examples/standard_multiple_server/server/main.go diff --git a/nacos/examples/custom_config_multiple_server/client/main.go b/nacos/examples/custom_config_multiple_server/client/main.go new file mode 100644 index 0000000..067fc03 --- /dev/null +++ b/nacos/examples/custom_config_multiple_server/client/main.go @@ -0,0 +1,164 @@ +// Copyright 2021 CloudWeGo Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package main + +import ( + "context" + "encoding/json" + "time" + + "github.com/cloudwego/hertz/pkg/app/client" + "github.com/cloudwego/hertz/pkg/app/client/discovery" + "github.com/cloudwego/hertz/pkg/app/client/loadbalance" + "github.com/cloudwego/hertz/pkg/app/middlewares/client/sd" + "github.com/cloudwego/hertz/pkg/common/config" + "github.com/cloudwego/hertz/pkg/common/hlog" + "github.com/cloudwego/hertz/pkg/protocol" + "github.com/hertz-contrib/registry/nacos" + "github.com/nacos-group/nacos-sdk-go/clients" + "github.com/nacos-group/nacos-sdk-go/common/constant" + "github.com/nacos-group/nacos-sdk-go/vo" +) + +type Message struct { + Message string `json:"message"` + Name string `json:"name"` +} + +func main() { + sc := []constant.ServerConfig{ + *constant.NewServerConfig("127.0.0.1", 8848), + } + cc := constant.ClientConfig{ + NamespaceId: "public", + TimeoutMs: 5000, + NotLoadCacheAtStart: true, + LogDir: "/tmp/nacos/log", + CacheDir: "/tmp/nacos/cache", + LogLevel: "info", + } + nacosCli, err := clients.NewNamingClient( + vo.NacosClientParam{ + ClientConfig: &cc, + ServerConfigs: sc, + }) + if err != nil { + panic(err) + } + r := nacos.NewNacosResolver(nacosCli) + + discoveryWithSD(r) + discoveryWithTag(r) + discoveryWithCustomizedAddr(r) + discoveryWithLoadBalanceOptions(r) + discoveryThenUsePostMethod(r) +} + +func discoveryWithSD(r discovery.Resolver) { + hlog.Info("simply discovery:") + cli, err := client.NewClient() + if err != nil { + panic(err) + } + cli.Use(sd.Discovery(r)) + for i := 0; i < 10; i++ { + status, body, err := cli.Get(context.Background(), nil, "http://hertz.custom-config.demo/ping", config.WithSD(true)) + if err != nil { + hlog.Fatal(err) + } + hlog.Infof("code=%d,body=%s", status, string(body)) + } +} + +func discoveryWithTag(r discovery.Resolver) { + hlog.Info("discovery with tag:") + cli, err := client.NewClient() + if err != nil { + panic(err) + } + cli.Use(sd.Discovery(r)) + for i := 0; i < 10; i++ { + status, body, err := cli.Get(context.Background(), nil, "http://hertz.custom-config.demo/ping", + config.WithSD(true), + config.WithTag("key1", "val1")) + if err != nil { + hlog.Fatal(err) + } + hlog.Infof("code=%d,body=%s", status, string(body)) + } +} + +func discoveryWithCustomizedAddr(r discovery.Resolver) { + hlog.Info("discovery with customizedAddr:") + cli, err := client.NewClient() + if err != nil { + panic(err) + } + + cli.Use(sd.Discovery(r, sd.WithCustomizedAddrs("127.0.0.1:8088"))) + for i := 0; i < 10; i++ { + status, body, err := cli.Get(context.Background(), nil, "http://hertz.custom-config.demo/ping", config.WithSD(true)) + if err != nil { + hlog.Fatal(err) + } + hlog.Infof("code=%d,body=%s", status, string(body)) + } +} + +func discoveryWithLoadBalanceOptions(r discovery.Resolver) { + hlog.Info("discovery with loadBalanceOptions:") + cli, err := client.NewClient() + if err != nil { + panic(err) + } + cli.Use(sd.Discovery(r, sd.WithLoadBalanceOptions(loadbalance.NewWeightedBalancer(), loadbalance.Options{ + RefreshInterval: 5 * time.Second, + ExpireInterval: 15 * time.Second, + }))) + for i := 0; i < 10; i++ { + status, body, err := cli.Get(context.Background(), nil, "http://hertz.custom-config.demo/ping", config.WithSD(true)) + if err != nil { + hlog.Fatal(err) + } + hlog.Infof("code=%d,body=%s", status, string(body)) + } +} + +func discoveryThenUsePostMethod(r discovery.Resolver) { + hlog.Info("discovery and use post method to send request:") + cli, err := client.NewClient() + if err != nil { + panic(err) + } + cli.Use(sd.Discovery(r)) + + // set request config、method、request uri. + req := protocol.AcquireRequest() + req.SetOptions(config.WithSD(true)) + req.SetMethod("POST") + req.SetRequestURI("http://hertz.custom-config.demo/hello") + message := Message{Message: "hello", Name: "a handsome man"} + bytes, _ := json.Marshal(message) + // set body and content type + req.SetBody(bytes) + req.Header.SetContentTypeBytes([]byte("application/json")) + resp := protocol.AcquireResponse() + // send request + err = cli.Do(context.Background(), req, resp) + if err != nil { + hlog.Fatal(err) + } + hlog.Infof("code=%d,body=%s", resp.StatusCode(), string(resp.Body())) +} diff --git a/nacos/examples/custom_config_multiple_server/server/main.go b/nacos/examples/custom_config_multiple_server/server/main.go new file mode 100644 index 0000000..56a858a --- /dev/null +++ b/nacos/examples/custom_config_multiple_server/server/main.go @@ -0,0 +1,126 @@ +// Copyright 2021 CloudWeGo Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package main + +import ( + "context" + + "github.com/cloudwego/hertz/pkg/app" + "github.com/cloudwego/hertz/pkg/app/server" + "github.com/cloudwego/hertz/pkg/app/server/registry" + "github.com/cloudwego/hertz/pkg/common/utils" + "github.com/cloudwego/hertz/pkg/protocol/consts" + "github.com/hertz-contrib/registry/nacos" + "github.com/nacos-group/nacos-sdk-go/clients" + "github.com/nacos-group/nacos-sdk-go/common/constant" + "github.com/nacos-group/nacos-sdk-go/vo" +) + +import ( + "sync" +) + +var ( + wg sync.WaitGroup + server1IP = "127.0.0.1:8088" + server2IP = "127.0.0.1:8089" +) + +type Message struct { + Message string `json:"message"` + Name string `json:"name"` +} + +func main() { + sc := []constant.ServerConfig{ + *constant.NewServerConfig("127.0.0.1", 8848), + } + + cc := constant.ClientConfig{ + NamespaceId: "public", + TimeoutMs: 5000, + NotLoadCacheAtStart: true, + LogDir: "/tmp/nacos/log", + CacheDir: "/tmp/nacos/cache", + LogLevel: "info", + } + + cli, err := clients.NewNamingClient( + vo.NacosClientParam{ + ClientConfig: &cc, + ServerConfigs: sc, + }, + ) + if err != nil { + panic(err) + } + wg.Add(2) + r := nacos.NewNacosRegistry(cli) + go func() { + defer wg.Done() + h := server.Default( + server.WithHostPorts(server1IP), + server.WithRegistry(r, ®istry.Info{ + ServiceName: "hertz.custom-config.demo", + Addr: utils.NewNetAddr("tcp", server1IP), + Weight: 10, + Tags: map[string]string{ + "key1": "val1", + }, + })) + + h.GET("/ping", func(c context.Context, ctx *app.RequestContext) { + ctx.JSON(consts.StatusOK, utils.H{"ping1": "pong1"}) + }) + h.POST("/hello", func(c context.Context, ctx *app.RequestContext) { + message := Message{} + if err := ctx.Bind(&message); err != nil { + ctx.String(consts.StatusBadRequest, err.Error()) + return + } + ctx.JSON(consts.StatusOK, message) + }) + + h.Spin() + }() + + go func() { + defer wg.Done() + h := server.Default( + server.WithHostPorts(server2IP), + server.WithRegistry(r, ®istry.Info{ + ServiceName: "hertz.custom-config.demo", + Addr: utils.NewNetAddr("tcp", server2IP), + Weight: 10, + Tags: map[string]string{ + "key2": "val2", + }, + })) + h.GET("/ping", func(c context.Context, ctx *app.RequestContext) { + ctx.JSON(consts.StatusOK, utils.H{"ping2": "pong2"}) + }) + + h.POST("/hello", func(c context.Context, ctx *app.RequestContext) { + message := Message{} + if err := ctx.Bind(&message); err != nil { + ctx.String(consts.StatusBadRequest, err.Error()) + return + } + ctx.JSON(consts.StatusOK, message) + }) + h.Spin() + }() + wg.Wait() +} diff --git a/nacos/examples/standard_multiple_server/client/main.go b/nacos/examples/standard_multiple_server/client/main.go new file mode 100644 index 0000000..a9c951c --- /dev/null +++ b/nacos/examples/standard_multiple_server/client/main.go @@ -0,0 +1,46 @@ +// Copyright 2021 CloudWeGo Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package main + +import ( + "context" + "log" + + "github.com/cloudwego/hertz/pkg/app/client" + "github.com/cloudwego/hertz/pkg/app/middlewares/client/sd" + "github.com/cloudwego/hertz/pkg/common/config" + "github.com/cloudwego/hertz/pkg/common/hlog" + "github.com/hertz-contrib/registry/nacos" +) + +func main() { + client, err := client.NewClient() + if err != nil { + panic(err) + } + r, err := nacos.NewDefaultNacosResolver() + if err != nil { + log.Fatal(err) + return + } + client.Use(sd.Discovery(r)) + for i := 0; i < 10; i++ { + status, body, err := client.Get(context.Background(), nil, "http://hertz.test.demo/ping", config.WithSD(true)) + if err != nil { + hlog.Fatal(err) + } + hlog.Infof("code=%d,body=%s\n", status, string(body)) + } +} diff --git a/nacos/examples/standard_multiple_server/server/main.go b/nacos/examples/standard_multiple_server/server/main.go new file mode 100644 index 0000000..eee865b --- /dev/null +++ b/nacos/examples/standard_multiple_server/server/main.go @@ -0,0 +1,78 @@ +// Copyright 2021 CloudWeGo Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package main + +import ( + "context" + "log" + "sync" + + "github.com/cloudwego/hertz/pkg/app" + "github.com/cloudwego/hertz/pkg/app/server" + "github.com/cloudwego/hertz/pkg/app/server/registry" + "github.com/cloudwego/hertz/pkg/common/utils" + "github.com/cloudwego/hertz/pkg/protocol/consts" + "github.com/hertz-contrib/registry/nacos" +) + +var ( + wg sync.WaitGroup + server1IP = "127.0.0.1:8088" + server2IP = "127.0.0.1:8089" +) + +func main() { + r, err := nacos.NewDefaultNacosRegistry() + if err != nil { + log.Fatal(err) + return + } + wg.Add(2) + go func() { + defer wg.Done() + h := server.Default( + server.WithHostPorts(server1IP), + server.WithRegistry(r, ®istry.Info{ + ServiceName: "hertz.test.demo", + Addr: utils.NewNetAddr("tcp", server1IP), + Weight: 10, + Tags: nil, + }), + ) + h.GET("/ping", func(c context.Context, ctx *app.RequestContext) { + ctx.JSON(consts.StatusOK, utils.H{"ping1": "pong1"}) + }) + h.Spin() + }() + + go func() { + defer wg.Done() + h := server.Default( + server.WithHostPorts(server2IP), + server.WithRegistry(r, ®istry.Info{ + ServiceName: "hertz.test.demo", + Addr: utils.NewNetAddr("tcp", server2IP), + Weight: 10, + Tags: nil, + }), + ) + h.GET("/ping", func(c context.Context, ctx *app.RequestContext) { + ctx.JSON(consts.StatusOK, utils.H{"ping2": "pong2"}) + }) + h.Spin() + }() + + wg.Wait() +}