Skip to content

Commit

Permalink
feat: add nacos example (#34)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
dengWuuu authored Feb 7, 2023
1 parent 7c85e71 commit 7ff71fe
Show file tree
Hide file tree
Showing 4 changed files with 414 additions and 0 deletions.
164 changes: 164 additions & 0 deletions nacos/examples/custom_config_multiple_server/client/main.go
Original file line number Diff line number Diff line change
@@ -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()))
}
126 changes: 126 additions & 0 deletions nacos/examples/custom_config_multiple_server/server/main.go
Original file line number Diff line number Diff line change
@@ -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, &registry.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, &registry.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()
}
46 changes: 46 additions & 0 deletions nacos/examples/standard_multiple_server/client/main.go
Original file line number Diff line number Diff line change
@@ -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))
}
}
Loading

0 comments on commit 7ff71fe

Please sign in to comment.