package main
import (
"context"
"fmt"
"google.golang.org/grpc/credentials/insecure"
"time"
"google.golang.org/grpc/codes"
grpc_retry "github.com/grpc-ecosystem/go-grpc-middleware/retry"
"google.golang.org/grpc"
"test/proto"
)
func main() {
//stream
interceptor := func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
start := time.Now()
err := invoker(ctx, method, req, reply, cc, opts...)
fmt.Printf("耗时:%s\n", time.Since(start))
return err
}
var opts []grpc.DialOption
opts = append(opts, grpc.WithTransportCredentials(insecure.NewCredentials()))
retryOpts := []grpc_retry.CallOption{
grpc_retry.WithMax(3),
grpc_retry.WithPerRetryTimeout(1 * time.Second),
grpc_retry.WithCodes(codes.Unknown, codes.DeadlineExceeded, codes.Unavailable),
}
opts = append(opts, grpc.WithUnaryInterceptor(interceptor))
//这个请求应该多长时间超时, 这个重试应该几次、当服务器返回什么状态码的时候重试
opts = append(opts, grpc.WithUnaryInterceptor(grpc_retry.UnaryClientInterceptor(retryOpts...)))
conn, err := grpc.Dial("127.0.0.1:50051", opts...)
if err != nil {
panic(err)
}
defer conn.Close()
c := proto.NewGreeterClient(conn)
r, err := c.SayHello(context.Background(), &proto.HelloRequest{Name: "bobby"})
if err != nil {
panic(err)
}
fmt.Println(r.Message)
}
package main
import (
"context"
"fmt"
"net"
"time"
"google.golang.org/grpc"
"test/proto"
)
type Server struct{}
func (s *Server) SayHello(ctx context.Context, request *proto.HelloRequest) (*proto.HelloReply,
error) {
time.Sleep(2 * time.Second)
return &proto.HelloReply{
Message: "hello " + request.Name,
}, nil
}
func main() {
interceptor := func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
fmt.Println("接收到了一个新的请求")
res, err := handler(ctx, req)
fmt.Println("请求已经完成")
return res, err
}
opt := grpc.UnaryInterceptor(interceptor)
g := grpc.NewServer(opt)
proto.RegisterGreeterServer(g, &Server{})
lis, err := net.Listen("tcp", "0.0.0.0:50051")
if err != nil {
panic("failed to listen:" + err.Error())
}
err = g.Serve(lis)
if err != nil {
panic("failed to start grpc:" + err.Error())
}
}
select * from table_xxx where id = 'xxx' for update;
update table_xxx set name=#name#,version=version+1 where version=#version#
update table_xxx set avai_amount = avai_amount-#subAmount# where avai_amount-#subAmount# >= 0
update table_xxx set name=#name#,version=version+1 where id=#id# and version=#version#
update table_xxx set avai_amount = avai_amount-#subAmount# where id=#id# and avai_amount-#subAmount# >= 0