Skip to content

Commit 236b72b

Browse files
committed
docs: update readme
1 parent af79119 commit 236b72b

File tree

13 files changed

+198
-61
lines changed

13 files changed

+198
-61
lines changed

pkg/gin/middleware/README.md

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ Common gin middleware libraries, including:
1818

1919
### Logging middleware
2020

21-
You can set the maximum length for printing, add a request id field, ignore print path, customize [zap](go.uber.org/zap) log.
21+
You can set the maximum length for printing, add a request id field, ignore print path, customize [zap](https://github.com/uber-go/zap) log.
2222

2323
```go
2424
import (
@@ -126,6 +126,12 @@ func NewRouter() *gin.Engine {
126126
r.Use(middleware.CircuitBreaker(
127127
//middleware.WithValidCode(http.StatusRequestTimeout), // add error code 408 for circuit breaker
128128
//middleware.WithDegradeHandler(handler), // add custom degrade handler
129+
//middleware.WithBreakerOption(
130+
//circuitbreaker.WithSuccess(75), // default 60
131+
//circuitbreaker.WithRequest(200), // default 100
132+
//circuitbreaker.WithBucket(20), // default 10
133+
//circuitbreaker.WithWindow(time.Second*5), // default 3s
134+
//),
129135
))
130136

131137
// ......

pkg/gin/middleware/breaker.go

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ func (o *circuitBreakerOptions) apply(opts ...CircuitBreakerOption) {
4343
}
4444

4545
// WithGroup with circuit breaker group.
46-
// NOTE: implements generics circuitbreaker.CircuitBreaker
46+
// Deprecated: use WithBreakerOption instead
4747
func WithGroup(g *group.Group) CircuitBreakerOption {
4848
return func(o *circuitBreakerOptions) {
4949
if g != nil {
@@ -52,6 +52,17 @@ func WithGroup(g *group.Group) CircuitBreakerOption {
5252
}
5353
}
5454

55+
// WithBreakerOption set the circuit breaker options.
56+
func WithBreakerOption(opts ...circuitbreaker.Option) CircuitBreakerOption {
57+
return func(o *circuitBreakerOptions) {
58+
if len(opts) > 0 {
59+
o.group = group.NewGroup(func() interface{} {
60+
return circuitbreaker.NewBreaker(opts...)
61+
})
62+
}
63+
}
64+
}
65+
5566
// WithValidCode http code to mark failed
5667
func WithValidCode(code ...int) CircuitBreakerOption {
5768
return func(o *circuitBreakerOptions) {

pkg/gin/middleware/breaker_test.go

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,16 @@ func runCircuitBreakerHTTPServer() string {
2626

2727
gin.SetMode(gin.ReleaseMode)
2828
r := gin.New()
29-
r.Use(CircuitBreaker(WithGroup(group.NewGroup(func() interface{} {
30-
return circuitbreaker.NewBreaker()
31-
})),
29+
r.Use(CircuitBreaker(
30+
WithGroup(group.NewGroup(func() interface{} {
31+
return circuitbreaker.NewBreaker()
32+
})),
33+
WithBreakerOption(
34+
circuitbreaker.WithSuccess(75), // default 60
35+
circuitbreaker.WithRequest(200), // default 100
36+
circuitbreaker.WithBucket(20), // default 10
37+
circuitbreaker.WithWindow(time.Second*5), // default 3s
38+
),
3239
WithValidCode(http.StatusForbidden),
3340
WithDegradeHandler(degradeHandler),
3441
))

pkg/grpc/client/README.md

Lines changed: 29 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,34 @@
55
### Example of use
66

77
```go
8-
import "github.com/go-dev-frame/sponge/pkg/grpc/client"
8+
package main
99

10-
conn, err := client.NewClient(context.Background(), "127.0.0.1:8282",
11-
//client.WithServiceDiscover(builder),
12-
//client.WithLoadBalance(),
13-
//client.WithSecure(credentials),
14-
//client.WithUnaryInterceptor(unaryInterceptors...),
15-
//client.WithStreamInterceptor(streamInterceptors...),
16-
)
17-
```
10+
import (
11+
"context"
12+
"fmt"
13+
"github.com/go-dev-frame/sponge/pkg/grpc/client"
14+
pb "google.golang.org/grpc/examples/helloworld/helloworld"
15+
)
16+
17+
func main() {
18+
conn, err := client.NewClient("127.0.0.1:8282",
19+
//client.WithServiceDiscover(getDiscovery(), false),
20+
//client.WithLoadBalance(),
21+
//client.WithSecure(credentials),
22+
//client.WithUnaryInterceptor(unaryInterceptors...),
23+
//client.WithStreamInterceptor(streamInterceptors...),
24+
)
25+
if err != nil {
26+
panic(err)
27+
}
1828

19-
Examples of practical use https://github.com/zhufuyi/grpc_examples/blob/main/usage/client/main.go
29+
greeterClient := pb.NewGreeterClient(conn)
30+
reply, err := greeterClient.SayHello(context.Background(), &pb.HelloRequest{Name: "Alice"})
31+
if err != nil {
32+
panic(err)
33+
}
34+
fmt.Printf("Greeting: %s\n", reply.GetMessage())
35+
36+
conn.Close()
37+
}
38+
```

pkg/grpc/client/client.go

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,19 @@ import (
88
"google.golang.org/grpc/credentials"
99
"google.golang.org/grpc/credentials/insecure"
1010
"google.golang.org/grpc/resolver"
11+
12+
"github.com/go-dev-frame/sponge/pkg/servicerd/discovery"
13+
"github.com/go-dev-frame/sponge/pkg/servicerd/registry"
1114
)
1215

1316
// Option client option func
1417
type Option func(*options)
1518

1619
type options struct {
17-
builders []resolver.Builder
20+
builders []resolver.Builder
21+
iDiscovery registry.Discovery
22+
isInsecure bool
23+
1824
isLoadBalance bool
1925
credentials credentials.TransportCredentials
2026
unaryInterceptors []grpc.UnaryClientInterceptor
@@ -33,9 +39,17 @@ func (o *options) apply(opts ...Option) {
3339
}
3440

3541
// WithServiceDiscover set service discover
36-
func WithServiceDiscover(builders ...resolver.Builder) Option {
42+
func WithServiceDiscover(d registry.Discovery, isInsecure bool) Option {
3743
return func(o *options) {
38-
o.builders = builders
44+
o.iDiscovery = d
45+
o.isInsecure = isInsecure
46+
}
47+
}
48+
49+
// WithServiceDiscoverBuilder set service discover builder
50+
func WithServiceDiscoverBuilder(builder ...resolver.Builder) Option {
51+
return func(o *options) {
52+
o.builders = builder
3953
}
4054
}
4155

@@ -83,7 +97,15 @@ func NewClient(endpoint string, opts ...Option) (*grpc.ClientConn, error) {
8397

8498
// service discovery
8599
if len(o.builders) > 0 {
86-
dialOptions = append(dialOptions, grpc.WithResolvers(o.builders...))
100+
dialOptions = append(dialOptions, grpc.WithResolvers(o.builders...)) // higher priority
101+
} else {
102+
if o.iDiscovery != nil {
103+
dialOptions = append(dialOptions, grpc.WithResolvers(
104+
discovery.NewBuilder(
105+
o.iDiscovery,
106+
discovery.WithInsecure(o.isInsecure),
107+
)))
108+
}
87109
}
88110

89111
// load balance option

pkg/grpc/client/client_test.go

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,20 @@ import (
88
"google.golang.org/grpc"
99
"google.golang.org/grpc/credentials/insecure"
1010
"google.golang.org/grpc/resolver"
11+
12+
"github.com/go-dev-frame/sponge/pkg/servicerd/registry"
1113
)
1214

15+
func getDiscovery() registry.Discovery {
16+
//endpoint = "discovery:///" + grpcClientCfg.Name // format: discovery:///serverName
17+
//cli, err := consulcli.Init(cfg.Consul.Addr, consulcli.WithWaitTime(time.Second*5))
18+
//if err != nil {
19+
// panic(fmt.Sprintf("consulcli.Init error: %v, addr: %s", err, cfg.Consul.Addr))
20+
//}
21+
//return consul.New(cli)
22+
return nil
23+
}
24+
1325
type builder struct{}
1426

1527
func (b *builder) Build(target resolver.Target, cc resolver.ClientConn, opts resolver.BuildOptions) (resolver.Resolver, error) {
@@ -34,7 +46,8 @@ var streamInterceptors = []grpc.StreamClientInterceptor{
3446

3547
func TestNewClient(t *testing.T) {
3648
conn, err := NewClient("127.0.0.1:50082",
37-
WithServiceDiscover(new(builder)),
49+
WithServiceDiscover(getDiscovery(), false),
50+
WithServiceDiscoverBuilder(new(builder)),
3851
WithLoadBalance(),
3952
WithSecure(insecure.NewCredentials()),
4053
WithUnaryInterceptor(unaryInterceptors...),

pkg/grpc/interceptor/README.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -211,6 +211,12 @@ func setDialOptions() []grpc.DialOption {
211211
interceptor.UnaryServerCircuitBreaker(
212212
//interceptor.WithValidCode(codes.DeadlineExceeded), // add error code for circuit breaker
213213
//interceptor.WithUnaryServerDegradeHandler(handler), // add custom degrade handler
214+
//interceptor.WithBreakerOption(
215+
//circuitbreaker.WithSuccess(75), // default 60
216+
//circuitbreaker.WithRequest(200), // default 100
217+
//circuitbreaker.WithBucket(20), // default 10
218+
//circuitbreaker.WithWindow(time.Second*5), // default 3s
219+
//),
214220
),
215221
)
216222
options = append(options, option)

pkg/grpc/interceptor/breaker.go

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ func (o *circuitBreakerOptions) apply(opts ...CircuitBreakerOption) {
4747
}
4848

4949
// WithGroup with circuit breaker group.
50-
// NOTE: implements generics circuitbreaker.CircuitBreaker
50+
// Deprecated: use WithBreakerOption instead
5151
func WithGroup(g *group.Group) CircuitBreakerOption {
5252
return func(o *circuitBreakerOptions) {
5353
if g != nil {
@@ -56,6 +56,17 @@ func WithGroup(g *group.Group) CircuitBreakerOption {
5656
}
5757
}
5858

59+
// WithBreakerOption set the circuit breaker options.
60+
func WithBreakerOption(opts ...circuitbreaker.Option) CircuitBreakerOption {
61+
return func(o *circuitBreakerOptions) {
62+
if len(opts) > 0 {
63+
o.group = group.NewGroup(func() interface{} {
64+
return circuitbreaker.NewBreaker(opts...)
65+
})
66+
}
67+
}
68+
}
69+
5970
// WithValidCode rpc code to mark failed
6071
func WithValidCode(code ...codes.Code) CircuitBreakerOption {
6172
return func(o *circuitBreakerOptions) {

pkg/grpc/interceptor/breaker_test.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package interceptor
33
import (
44
"context"
55
"testing"
6+
"time"
67

78
"github.com/stretchr/testify/assert"
89
"google.golang.org/grpc"
@@ -18,6 +19,12 @@ func TestUnaryClientCircuitBreaker(t *testing.T) {
1819
WithGroup(group.NewGroup(func() interface{} {
1920
return circuitbreaker.NewBreaker()
2021
})),
22+
WithBreakerOption(
23+
circuitbreaker.WithSuccess(75), // default 60
24+
circuitbreaker.WithRequest(200), // default 100
25+
circuitbreaker.WithBucket(20), // default 10
26+
circuitbreaker.WithWindow(time.Second*5), // default 3s
27+
),
2128
WithValidCode(codes.PermissionDenied),
2229
)
2330

pkg/grpc/server/README.md

Lines changed: 41 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -5,22 +5,45 @@
55
### Example of use
66

77
```go
8-
import "github.com/go-dev-frame/sponge/pkg/grpc/server"
9-
10-
port := 8282
11-
registerFn := func(s *grpc.Server) {
12-
pb.RegisterGreeterServer(s, &greeterServer{})
13-
}
14-
15-
server.Run(port, registerFn,
16-
//server.WithSecure(credentials),
17-
//server.WithUnaryInterceptor(unaryInterceptors...),
18-
//server.WithStreamInterceptor(streamInterceptors...),
19-
//server.WithServiceRegister(func() {}),
20-
//server.WithStatConnections(metrics.WithConnectionsLogger(logger.Get()), metrics.WithConnectionsGauge()), // show connections or set prometheus metrics
21-
)
22-
23-
select{}
24-
```
8+
package main
9+
10+
import (
11+
"context"
12+
"fmt"
13+
"github.com/go-dev-frame/sponge/pkg/grpc/server"
14+
"google.golang.org/grpc"
15+
pb "google.golang.org/grpc/examples/helloworld/helloworld"
16+
)
17+
18+
type greeterServer struct {
19+
pb.UnimplementedGreeterServer
20+
}
21+
22+
func (s *greeterServer) SayHello(_ context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
23+
fmt.Printf("Received: %v\n", in.GetName())
24+
return &pb.HelloReply{Message: "Hello " + in.GetName()}, nil
25+
}
2526

26-
Examples of practical use https://github.com/zhufuyi/grpc_examples/blob/main/usage/server/main.go
27+
func main() {
28+
port := 8282
29+
registerFn := func(s *grpc.Server) {
30+
pb.RegisterGreeterServer(s, &greeterServer{})
31+
// Register other services here
32+
}
33+
34+
fmt.Printf("Starting server on port %d\n", port)
35+
srv, err := server.Run(port, registerFn,
36+
//server.WithSecure(credentials),
37+
//server.WithUnaryInterceptor(unaryInterceptors...),
38+
//server.WithStreamInterceptor(streamInterceptors...),
39+
//server.WithServiceRegister(srFn), // register service address to Consul/Etcd/Zookeeper...
40+
//server.WithStatConnections(metrics.WithConnectionsLogger(logger.Get()), metrics.WithConnectionsGauge()),
41+
)
42+
if err != nil {
43+
panic(err)
44+
}
45+
defer srv.Stop()
46+
47+
select {}
48+
}
49+
```

0 commit comments

Comments
 (0)