Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add more example #37

Merged
merged 3 commits into from
Apr 23, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 12 additions & 8 deletions servicecomb/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@ func main() {
}
```


### Client

```go
Expand All @@ -64,7 +63,7 @@ import (

func main() {
const scAddr = "127.0.0.1:30100"
// build a servicecomb resolver
// build a servicecomb resolver
r, err := servicecomb.NewDefaultSCResolver([]string{scAddr})
if err != nil {
panic(err)
Expand All @@ -89,10 +88,13 @@ func main() {
## Example

### Run Server
[Server](./example/server/main.go)

[Server](./example/basic/server/main.go)

```shell
go run ./example/server/main.go
go run ./example/basic/server/main.go
```

```log
2022/08/26 17:23:27 INFO: Use Service center v4
2022/08/26 17:23:27 INFO: Use Service center v4
Expand All @@ -103,10 +105,13 @@ go run ./example/server/main.go
```

### Run Client
[Client](./example/client/main.go)

[Client](./example/basic/client/main.go)

```shell
go run ./example/client/main.go
go run ./example/basic/client/main.go
```

```log
2022/08/26 17:24:03 INFO: Use Service center v4
2022/08/26 17:24:03 DEBUG: service center has new revision 9fc77257754eca927c1ff189b083e6c4eb79dbff
Expand All @@ -122,9 +127,8 @@ go run ./example/client/main.go
2022/08/26 17:24:03.416111 main.go:46: [Info] code=200,body={"ping":"pong2"}
```


## Compatibility

Compatible with server (2.0.0 - latest), If you want to use older server version, please modify the version in `Makefile` to test.

maintained by: [Cr](https://github.com/a631807682)
maintained by: [Cr](https://github.com/a631807682)
155 changes: 155 additions & 0 deletions servicecomb/example/custom_config/client/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
// Copyright 2022 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/go-chassis/sc-client"
"github.com/hertz-contrib/registry/servicecomb"
)

type Example struct {
A int `json:"a"`
B int `json:"b"`
}

const scAddr = "127.0.0.1:30100"

func main() {
scClient, err := sc.NewClient(sc.Options{
Endpoints: []string{scAddr},
Timeout: 5 * time.Second,
Compressed: true,
})
if err != nil {
panic(err)
}

r := servicecomb.NewSCResolver(scClient)
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://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://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:8702")))
for i := 0; i < 10; i++ {
status, body, err := cli.Get(context.Background(), nil, "http://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 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://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))

for i := 0; i < 10; i++ {
// set request config、method、request uri.
req := protocol.AcquireRequest()
req.SetOptions(config.WithSD(true))
req.SetMethod("POST")
req.SetRequestURI("http://custom-config-demo/ping")
t := Example{A: i, B: i}
bytes, _ := json.Marshal(t)
// 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()))
}
}
115 changes: 115 additions & 0 deletions servicecomb/example/custom_config/server/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
// Copyright 2022 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"
"sync"
"time"

"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/go-chassis/sc-client"
"github.com/hertz-contrib/registry/servicecomb"
)

var wg sync.WaitGroup

type Example struct {
A int `json:"a"`
B int `json:"b"`
}

const scAddr = "127.0.0.1:30100"

func main() {
// custom config
scClient, err := sc.NewClient(sc.Options{
Endpoints: []string{scAddr},
Timeout: 5 * time.Second,
Compressed: true,
})
if err != nil {
panic(err)
}

r := servicecomb.NewSCRegistry(scClient)

wg.Add(2)
go func() {
defer wg.Done()
addr := "127.0.0.1:8701"
h := server.Default(
server.WithHostPorts(addr),
server.WithRegistry(r, &registry.Info{
ServiceName: "custom-config-demo",
Addr: utils.NewNetAddr("tcp", addr),
Weight: 10,
Tags: map[string]string{
"key1": "val1",
},
}),
)

h.GET("/ping", func(c context.Context, ctx *app.RequestContext) {
ctx.JSON(consts.StatusOK, utils.H{"ping": "pong1"})
})

h.POST("/ping", func(c context.Context, ctx *app.RequestContext) {
e := Example{}
if err := ctx.Bind(&e); err != nil {
ctx.String(consts.StatusBadRequest, err.Error())
return
}
ctx.JSON(consts.StatusOK, e)
})
h.Spin()
}()

go func() {
defer wg.Done()
addr := "127.0.0.1:8702"
h := server.Default(
server.WithHostPorts(addr),
server.WithRegistry(r, &registry.Info{
ServiceName: "custom-config-demo",
Addr: utils.NewNetAddr("tcp", addr),
Weight: 10,
Tags: map[string]string{
"key1": "val1",
},
}),
)

h.GET("/ping", func(c context.Context, ctx *app.RequestContext) {
ctx.JSON(consts.StatusOK, utils.H{"ping": "pong1"})
})

h.POST("/ping", func(c context.Context, ctx *app.RequestContext) {
e := Example{}
if err := ctx.Bind(&e); err != nil {
ctx.String(consts.StatusBadRequest, err.Error())
return
}
ctx.JSON(consts.StatusOK, e)
})
h.Spin()
}()

wg.Wait()
}