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 consul example and fix some errors #33

Merged
merged 17 commits into from
Feb 5, 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
14 changes: 9 additions & 5 deletions consul/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ package main

import (
"context"
"fmt"
"log"

"github.com/cloudwego/hertz/pkg/app"
Expand All @@ -26,7 +27,6 @@ import (
"github.com/hertz-contrib/registry/consul"
)


func main() {
// build a consul client
config := consulapi.DefaultConfig()
Expand All @@ -40,7 +40,11 @@ func main() {
r := consul.NewConsulRegister(consulClient)

// run Hertz with the consul register
addr := "127.0.0.1:8888"
localIP, err := consul.GetLocalIPv4Address()
if err != nil {
log.Fatal(err)
}
addr := fmt.Sprintf("%s:8888",localIP)
h := server.Default(
server.WithHostPorts(addr),
server.WithRegistry(r, &registry.Info{
Expand Down Expand Up @@ -136,14 +140,14 @@ func main() {

## Example

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

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

## Compatibility

Compatible with consul from v1.11.x to v1.13.x.

[consul version list](https://releases.hashicorp.com/consul)

maintained by: [Lemonfish](https://github.com/LemonFish873310466)
maintained by: [Lemonfish](https://github.com/LemonFish873310466) / [claude-zq](https://github.com/Claude-Zq)
13 changes: 9 additions & 4 deletions consul/README_CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ package main

import (
"context"
"fmt"
"log"

"github.com/cloudwego/hertz/pkg/app"
Expand All @@ -39,7 +40,11 @@ func main() {
r := consul.NewConsulRegister(consulClient)

// run Hertz with the consul register
addr := "127.0.0.1:8888"
localIP, err := consul.GetLocalIPv4Address()
if err != nil {
log.Fatal(err)
}
addr := fmt.Sprintf("%s:8888",localIP)
h := server.Default(
server.WithHostPorts(addr),
server.WithRegistry(r, &registry.Info{
Expand Down Expand Up @@ -135,14 +140,14 @@ func main() {

## 使用样例

[服务端](example/server/main.go):`example/server/main.go`
[服务端](example/basic/server/main.go):`example/server/main.go`

[客户端](example/client/main.go):`example/client/main.go`
[客户端](example/basic/client/main.go):`example/client/main.go`

## 兼容性

与Consul(**v1.11.x到v1.13.x**)保持兼容。

[consul版本列表](https://releases.hashicorp.com/consul)

维护者: [Lemonfish](https://github.com/LemonFish873310466)
维护者: [Lemonfish](https://github.com/LemonFish873310466) / [claude-zq](https://github.com/Claude-Zq)
28 changes: 25 additions & 3 deletions consul/consul_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ var (
cRegistry registry.Registry
cResolver discovery.Resolver
consulAddr = "127.0.0.1:8500"
localIpAddr = utils.LocalIP()
localIpAddr string
)

func init() {
Expand All @@ -61,6 +61,28 @@ func init() {
return
}
cResolver = NewConsulResolver(cli2)

localIpAddr, err = getLocalIPv4Address()
if err != nil {
log.Fatal(err)
}
}

func getLocalIPv4Address() (string, error) {
addr, err := net.InterfaceAddrs()
if err != nil {
return "", err
}
for _, addr := range addr {
ipNet, isIpNet := addr.(*net.IPNet)
if isIpNet && !ipNet.IP.IsLoopback() {
ipv4 := ipNet.IP.To4()
if ipv4 != nil {
return ipv4.String(), nil
}
}
}
return "", fmt.Errorf("not found ipv4 address")
}

// TestNewConsulResolver tests unit test preparatory work.
Expand All @@ -83,7 +105,7 @@ func TestNewConsulRegister(t *testing.T) {
assert.NotNil(t, consulRegister)
}

// TestNewConsulResolver tests the NewConsulResolver function with check option.
// TestNewConsulRegisterWithCheckOption tests the NewConsulRegister function with check option.
func TestNewConsulRegisterWithCheckOption(t *testing.T) {
config := consulapi.DefaultConfig()
config.Address = consulAddr
Expand All @@ -98,7 +120,7 @@ func TestNewConsulRegisterWithCheckOption(t *testing.T) {
check.Interval = "10s"
check.DeregisterCriticalServiceAfter = "1m"

consulResolver := NewConsulResolver(cli, WithCheck(check))
consulResolver := NewConsulRegister(cli, WithCheck(check))
assert.NotNil(t, consulResolver)
}

Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -17,19 +17,22 @@ package main
import (
"context"
"log"
"net"
"sync"

"github.com/cloudwego/hertz/pkg/app/server/registry"
consulapi "github.com/hashicorp/consul/api"

"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"
consulapi "github.com/hashicorp/consul/api"
"github.com/hertz-contrib/registry/consul"
)

var wg sync.WaitGroup
var (
wg sync.WaitGroup
localIP = "your ip"
)

func main() {
config := consulapi.DefaultConfig()
Expand All @@ -43,7 +46,7 @@ func main() {
wg.Add(2)
go func() {
defer wg.Done()
addr := "127.0.0.1:8888"
addr := net.JoinHostPort(localIP, "8888")
r := consul.NewConsulRegister(consulClient)
h := server.Default(
server.WithHostPorts(addr),
Expand All @@ -62,7 +65,7 @@ func main() {
}()
go func() {
defer wg.Done()
addr := "127.0.0.1:8889"
addr := net.JoinHostPort(localIP, "8889")
r := consul.NewConsulRegister(consulClient)
h := server.Default(
server.WithHostPorts(addr),
Expand Down
157 changes: 157 additions & 0 deletions consul/example/custom-config/client/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
// 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"
"fmt"
"log"
"net"
"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/hashicorp/consul/api"
"github.com/hertz-contrib/registry/consul"
)

var localIP = "your ip"

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

func main() {
Claude-Zq marked this conversation as resolved.
Show resolved Hide resolved
// build a consul client
consulConfig := api.DefaultConfig()
consulConfig.Address = "127.0.0.1:8500"
consulClient, err := api.NewClient(consulConfig)
if err != nil {
log.Fatal(err)
return
}
// build a consul resolver with the consul client
r := consul.NewConsulResolver(consulClient)

discoveryWithSD(r)
discoveryWithTag(r)
discoveryWithCustomizedAddr(r)
discoveryWithLoadBalanceOptions(r)
discoveryThenUsePostMethod(r)
}

func discoveryWithSD(r discovery.Resolver) {
fmt.Println("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) {
fmt.Println("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) {
fmt.Println("discovery with customizedAddr:")
cli, err := client.NewClient()
if err != nil {
panic(err)
}

cli.Use(sd.Discovery(r, sd.WithCustomizedAddrs(net.JoinHostPort(localIP, "5001"))))
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) {
fmt.Println("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) {
fmt.Println("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()))
}
}
Loading