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 redis registry #24

Merged
merged 9 commits into from
Nov 10, 2022
Merged
Show file tree
Hide file tree
Changes from 8 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
5 changes: 5 additions & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,11 @@ jobs:
image: 'xdockerh/eureka-server:latest'
ports:
- "8761:8761"
redis:
image: redis:latest
ports:
- '6379:6379'

steps:
- uses: actions/checkout@v3

Expand Down
25 changes: 25 additions & 0 deletions licenses/LICENSE-go-redis
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
Copyright (c) 2013 The github.com/go-redis/redis Authors.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
3 changes: 3 additions & 0 deletions redis/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
prepare:
docker pull redis:latest
docker run --name dev-redis -p 6379:6379 -d redis:latest
100 changes: 100 additions & 0 deletions redis/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
# redis (*This is a community driven project*)

Redis as service discovery for Hertz.

## How to use?

### Server

**[example/server/main.go](example/server/main.go)**

```go
package main

import (
"context"
"registry/redis"

"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"
)

func main() {
r := redis.NewRedisRegistry("127.0.0.1:6379")
addr := "127.0.0.1:8888"
h := server.Default(
server.WithHostPorts(addr),
server.WithRegistry(r, &registry.Info{
ServiceName: "hertz.test.demo",
Addr: utils.NewNetAddr("tcp", addr),
Weight: 10,
Tags: nil,
}),
)
h.GET("/ping", func(_ context.Context, ctx *app.RequestContext) {
ctx.JSON(consts.StatusOK, utils.H{"ping": "pong"})
})
h.Spin()
}
```

### Client

**[example/client/main.go](example/client/main.go)**

```go
package main

import (
"context"
"registry/redis"

"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"
)

func main() {
cli, err := client.NewClient()
if err != nil {
panic(err)
}
r := redis.NewRedisResolver("127.0.0.1:6379")
cli.Use(sd.Discovery(r))
for i := 0; i < 10; i++ {
status, body, err := cli.Get(context.Background(), nil, "http://hertz.test.demo/ping", config.WithSD(true))
if err != nil {
hlog.Fatal(err)
}
hlog.Infof("HERTZ: code=%d,body=%s", status, string(body))
}
}
```

## How to run example?

### run docker

```bash
make prepare
```

### run server

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

### run client

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

## Compatibility

Redis client for Go [see](https://github.com/go-redis/redis)
150 changes: 150 additions & 0 deletions redis/common.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
// 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 redis

import (
"context"
"crypto/tls"
"encoding/json"
"fmt"
"net"
"time"

"github.com/cloudwego/hertz/pkg/app/server/registry"
"github.com/go-redis/redis/v8"
)

const (
Redis = "redis"
register = "register"
deregister = "deregister"
hertz = "hertz"
server = "server"
tcp = "tcp"
)

const (
defaultExpireTime = time.Second * 60
defaultTickerTime = time.Second * 30
defaultKeepAliveTime = time.Second * 60
defaultMonitorTime = time.Second * 30
defaultWeight = 10
)

type Option func(opts *redis.Options)

func WithPassword(password string) Option {
return func(opts *redis.Options) {
opts.Password = password
}
}

func WithDB(db int) Option {
return func(opts *redis.Options) {
opts.DB = db
}
}

func WithTLSConfig(t *tls.Config) Option {
return func(opts *redis.Options) {
opts.TLSConfig = t
}
}

func WithDialer(dialer func(ctx context.Context, network, addr string) (net.Conn, error)) Option {
return func(opts *redis.Options) {
opts.Dialer = dialer
}
}

func WithReadTimeout(t time.Duration) Option {
return func(opts *redis.Options) {
opts.ReadTimeout = t
}
}

func WithWriteTimeout(t time.Duration) Option {
return func(opts *redis.Options) {
opts.WriteTimeout = t
}
}

type registryHash struct {
key string
field string
value string
}

type registryInfo struct {
ServiceName string `json:"service_name"`
Addr string `json:"addr"`
Weight int `json:"weight"`
Tags map[string]string `json:"tags"`
}

func validateRegistryInfo(info *registry.Info) error {
if info == nil {
return fmt.Errorf("registry.Info can not be empty")
}
if info.ServiceName == "" {
return fmt.Errorf("registry.Info ServiceName can not be empty")
}
if info.Addr == nil {
return fmt.Errorf("registry.Info Addr can not be empty")
}
return nil
}

func generateKey(serviceName, serviceType string) string {
return fmt.Sprintf("/%s/%s/%s", hertz, serviceName, serviceType)
}

func generateMsg(msgType, serviceName, serviceAddr string) string {
return fmt.Sprintf("%s-%s-%s", msgType, serviceName, serviceAddr)
}

func prepareRegistryHash(info *registry.Info) (*registryHash, error) {
meta, err := json.Marshal(convertInfo(info))
if err != nil {
return nil, err
}
return &registryHash{
key: generateKey(info.ServiceName, server),
field: info.Addr.String(),
value: string(meta),
}, nil
}

func convertInfo(info *registry.Info) *registryInfo {
return &registryInfo{
ServiceName: info.ServiceName,
Addr: info.Addr.String(),
Weight: info.Weight,
Tags: info.Tags,
}
}

func keepAlive(ctx context.Context, hash *registryHash, r *redisRegistry) {
ticker := time.NewTicker(defaultTickerTime)
defer ticker.Stop()
for {
select {
case <-ticker.C:
r.client.Expire(ctx, hash.key, defaultKeepAliveTime)
case <-ctx.Done():
break
}
}
}
41 changes: 41 additions & 0 deletions redis/example/client/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// 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"

"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/redis"
)

func main() {
cli, err := client.NewClient()
if err != nil {
panic(err)
}
r := redis.NewRedisResolver("127.0.0.1:6379")
cli.Use(sd.Discovery(r))
for i := 0; i < 10; i++ {
status, body, err := cli.Get(context.Background(), nil, "http://hertz.test.demo/ping", config.WithSD(true))
if err != nil {
hlog.Fatal(err)
}
hlog.Infof("HERTZ: code=%d,body=%s", status, string(body))
}
}
44 changes: 44 additions & 0 deletions redis/example/server/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// 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"

"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/redis"
)

func main() {
r := redis.NewRedisRegistry("127.0.0.1:6379")
addr := "127.0.0.1:8888"
h := server.Default(
server.WithHostPorts(addr),
server.WithRegistry(r, &registry.Info{
ServiceName: "hertz.test.demo",
Addr: utils.NewNetAddr("tcp", addr),
Weight: 10,
Tags: nil,
}),
)
h.GET("/ping", func(_ context.Context, ctx *app.RequestContext) {
ctx.JSON(consts.StatusOK, utils.H{"ping": "pong"})
})
h.Spin()
}
9 changes: 9 additions & 0 deletions redis/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
module github.com/hertz-contrib/registry/redis

go 1.16

require (
github.com/cloudwego/hertz v0.3.2
github.com/go-redis/redis/v8 v8.11.5
github.com/stretchr/testify v1.7.0
)
Loading