From c951a7b4858ad6cb44f12881aaeee9569106c6bf Mon Sep 17 00:00:00 2001 From: Sage <1010309281@qq.com> Date: Fri, 24 Sep 2021 08:10:17 +0000 Subject: [PATCH 01/12] =?UTF-8?q?=E6=96=B0=E5=A2=9E=20grpc=20client?= =?UTF-8?q?=EF=BC=8C=E5=BE=85=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/v1/grpcserver/client_grpc.go | 36 ++++++++++++++++++++++++++++++++ src/v1/grpcserver/server_grpc.go | 1 - 2 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 src/v1/grpcserver/client_grpc.go diff --git a/src/v1/grpcserver/client_grpc.go b/src/v1/grpcserver/client_grpc.go new file mode 100644 index 0000000..90088b8 --- /dev/null +++ b/src/v1/grpcserver/client_grpc.go @@ -0,0 +1,36 @@ +package grpcserver + + +func NewRemoteConn(options IOptions) (*grpc.ClientConn, error) { + address := options.GetAddress() + // Set up a connection to the server. + ctx, cancel := context.WithTimeout(context.Background(), time.Duration(options.GetTimeout())*time.Second) + defer cancel() + + defer func() { + if err := recover(); err != nil { + panic(fmt.Errorf("[%s]%s", options.GetName(), err)) + } + }() + balanceName := "round_robin" + + //使用服务发现 + switch options.GetDiscovery() { + case "etcd": + d, err := etcdv3.NewServiceDiscovery(options.GetDiscoveryAddr(), 5) + if err != nil { + //panic(err) + return nil, err + } + resolver.Register(d) + address = fmt.Sprintf("%s://8.8.8.8/%s", d.Scheme(), options.GetName()) + b := &grpclb.WeightBalance{} + + balancer.Register(base.NewBalancerBuilder(b.Name(), b, base.Config{HealthCheck: true}), ) + balanceName = b.Name() + } + + serviceConfig := grpc.WithDefaultServiceConfig(fmt.Sprintf("{\"loadBalancingConfig\":[{\"%s\":{}}]}", balanceName)) + + return grpc.DialContext(ctx, address, grpc.WithInsecure(), grpc.WithBlock(), serviceConfig) +} diff --git a/src/v1/grpcserver/server_grpc.go b/src/v1/grpcserver/server_grpc.go index ac25f9e..637ec94 100644 --- a/src/v1/grpcserver/server_grpc.go +++ b/src/v1/grpcserver/server_grpc.go @@ -9,7 +9,6 @@ type GRPCServer struct { HandlerFunc HandlerFunc serviceRegister IServiceRegister - RegisterAddr string } -- Gitee From fb19bee6a2717d5b084b6cece8bfef2696c2b2ef Mon Sep 17 00:00:00 2001 From: Sage <1010309281@qq.com> Date: Fri, 24 Sep 2021 20:26:57 +0800 Subject: [PATCH 02/12] =?UTF-8?q?=E4=BC=98=E5=8C=96=20grpc?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../client_grpc.go => clients/grpc/client.go} | 16 +++- src/v1/clients/grpc/option.go | 51 +++++++++++ src/v1/grpcserver/server_dis_etcd.go | 31 ++++--- src/v1/grpcserver/server_grpc.go | 85 ++++++++++--------- ...ervice_discovery.go => server_grpc_dis.go} | 0 .../{servier_reg.go => server_grpc_reg.go} | 2 +- 6 files changed, 128 insertions(+), 57 deletions(-) rename src/v1/{grpcserver/client_grpc.go => clients/grpc/client.go} (74%) create mode 100644 src/v1/clients/grpc/option.go rename src/v1/grpcserver/{service_discovery.go => server_grpc_dis.go} (100%) rename src/v1/grpcserver/{servier_reg.go => server_grpc_reg.go} (64%) diff --git a/src/v1/grpcserver/client_grpc.go b/src/v1/clients/grpc/client.go similarity index 74% rename from src/v1/grpcserver/client_grpc.go rename to src/v1/clients/grpc/client.go index 90088b8..602b6c2 100644 --- a/src/v1/grpcserver/client_grpc.go +++ b/src/v1/clients/grpc/client.go @@ -1,5 +1,15 @@ -package grpcserver +package grpc +import ( + "context" + "fmt" + v1etcd "gitee.com/scottq/go-framework/src/v1/clients/etcd" + "google.golang.org/grpc" + "google.golang.org/grpc/balancer" + "google.golang.org/grpc/balancer/base" + "google.golang.org/grpc/resolver" + "time" +) func NewRemoteConn(options IOptions) (*grpc.ClientConn, error) { address := options.GetAddress() @@ -17,14 +27,14 @@ func NewRemoteConn(options IOptions) (*grpc.ClientConn, error) { //使用服务发现 switch options.GetDiscovery() { case "etcd": - d, err := etcdv3.NewServiceDiscovery(options.GetDiscoveryAddr(), 5) + d, err := v1etcd.NewServiceDiscovery(options.GetDiscoveryAddr(), 5) if err != nil { //panic(err) return nil, err } resolver.Register(d) address = fmt.Sprintf("%s://8.8.8.8/%s", d.Scheme(), options.GetName()) - b := &grpclb.WeightBalance{} + b := &WeightBalance{} balancer.Register(base.NewBalancerBuilder(b.Name(), b, base.Config{HealthCheck: true}), ) balanceName = b.Name() diff --git a/src/v1/clients/grpc/option.go b/src/v1/clients/grpc/option.go new file mode 100644 index 0000000..c1f3134 --- /dev/null +++ b/src/v1/clients/grpc/option.go @@ -0,0 +1,51 @@ +package grpc + +type IOptions interface { + GetTimeout() int64 + GetAddress() string + GetName() string + + GetDiscovery() string + GetDiscoveryAddr() string +} + +type RemoteOptions struct { + SrName string + SrAddress string + Timeout int64 + RemoteType string + + //服务发现client和client地址 + DiscoveryClient string + DiscoveryAddr string +} + +const defaultTimeout = 3 + +func (op *RemoteOptions) GetTimeout() int64 { + if op.Timeout <= 0 { + return defaultTimeout + } + return op.Timeout +} +func (op *RemoteOptions) GetRemoteType() string { + return op.RemoteType +} +func (op *RemoteOptions) GetAddress() string { + return op.SrAddress +} +func (op *RemoteOptions) GetName() string { + return op.SrName +} + +func (op *RemoteOptions) GetDiscovery() string { + return op.DiscoveryClient +} +func (op *RemoteOptions) GetDiscoveryAddr() string { + return op.DiscoveryAddr +} + +func (op *RemoteOptions) SetDiscovery(client string, discoveryAddr string) { + op.DiscoveryClient = client + op.DiscoveryAddr = discoveryAddr +} diff --git a/src/v1/grpcserver/server_dis_etcd.go b/src/v1/grpcserver/server_dis_etcd.go index 7e1b1cf..31e3c15 100644 --- a/src/v1/grpcserver/server_dis_etcd.go +++ b/src/v1/grpcserver/server_dis_etcd.go @@ -1,21 +1,24 @@ package grpcserver -type EtcdRegisterFinder struct{ - etcdAddr string -} +import ( + v1etcd "gitee.com/scottq/go-framework/src/v1/clients/etcd" +) -func NewEtcdRegisterFinder(etcdAddr string,)(IServiceRegister,error){ +type EtcdRegisterFinder struct { + etcdAddr string +} - return &EtcdRegisterFinder{ - etcdAddr:etcdAddr, - } +func NewEtcdRegisterFinder(etcdAddr string, ) (IServiceRegister, error) { + return &EtcdRegisterFinder{ + etcdAddr: etcdAddr, + }, nil } -func (r *EtcdRegisterFinder) Register(name string,addr string)error{ - sr := etcdv3.RegisterService( - r.etcdAddr, - name, - addr, 5) +func (r *EtcdRegisterFinder) Register(name string, addr string) error { + sr := v1etcd.RegisterService( + r.etcdAddr, + name, + addr, 5) go sr.ListenLease() - return nil -} \ No newline at end of file + return nil +} diff --git a/src/v1/grpcserver/server_grpc.go b/src/v1/grpcserver/server_grpc.go index 637ec94..290fbbc 100644 --- a/src/v1/grpcserver/server_grpc.go +++ b/src/v1/grpcserver/server_grpc.go @@ -1,51 +1,59 @@ package grpcserver +import ( + "fmt" + "gitee.com/scottq/go-framework/src/utils" + "google.golang.org/grpc" + "log" + "net" +) + type HandlerFunc = func(*grpc.Server) type GRPCServer struct { - name string - listenAdd string - s *grpc.Server + name string + listenAddr string + s *grpc.Server HandlerFunc HandlerFunc - serviceRegister IServiceRegister -} - - -func NewGRPCServer(name string, addr string, )(*GRPCServer, error){ + serviceRegister IServiceRegister + RequestIp string + RequestPort string +} - return &GRPCServer{ - name:name, - listenAdd:addr, - s:grpc.NewServer(), - },nil +func NewGRPCServer(name string, addr string, ) (*GRPCServer, error) { + return &GRPCServer{ + name: name, + listenAddr: addr, + s: grpc.NewServer(), + }, nil } -func (server *GRPCServer) AddServiceRegister(r IServiceRegister) { - h.serviceRegister=r +func (svr *GRPCServer) AddServiceRegister(r IServiceRegister) { + svr.serviceRegister = r } -func (server *GRPCServer) Run() error { - err := h.registerService() +func (svr *GRPCServer) Run() error { + err := svr.registerService() if err != nil { return err } - return h.run() + return svr.run() } -func (server *GRPCServer) run() error { - lis, err := net.Listen("tcp", h.listenAdd) +func (svr *GRPCServer) run() error { + lis, err := net.Listen("tcp", svr.listenAddr) if err != nil { log.Fatalf("failed to listen: %v", err) } - - if h.RegisterFunc != nil { - h.RegisterFunc(server.s) + + if svr.HandlerFunc != nil { + svr.HandlerFunc(svr.s) } - fmt.Printf("[%s]rpc running at %s\n", h.AppName, h.RpcPort) - if err := s.Serve(lis); err != nil { + fmt.Printf("[%s]rpc running at %s\n", svr.name, svr.listenAddr) + if err := svr.s.Serve(lis); err != nil { log.Fatalf("failed to serve: %v", err) return err } @@ -53,22 +61,21 @@ func (server *GRPCServer) run() error { return nil } - -func (server *GRPCServer) registerService() error { +func (svr *GRPCServer) registerService() error { var err error - rpcAddr := h.RegisterAddr - if etcdAddr == "" { - return fmt.Errorf("sr register addr is empty") - } - if rpcAddr == "" { + RequestIp := svr.RequestIp + RequestPort := svr.RequestPort - rpcAddr, err = utils.GetLocalIP() - if err != nil { - return err - } + if RequestIp == "" { + RequestIp, err = utils.GetLocalIP() + if err != nil { + return err } - if h.registerService!=nil{ - registerService.Register(h.AppName,rpcAddr) - } + } + + if svr.serviceRegister != nil { + return svr.serviceRegister.Register(svr.name, RequestIp+":"+RequestPort) + } + return nil } diff --git a/src/v1/grpcserver/service_discovery.go b/src/v1/grpcserver/server_grpc_dis.go similarity index 100% rename from src/v1/grpcserver/service_discovery.go rename to src/v1/grpcserver/server_grpc_dis.go diff --git a/src/v1/grpcserver/servier_reg.go b/src/v1/grpcserver/server_grpc_reg.go similarity index 64% rename from src/v1/grpcserver/servier_reg.go rename to src/v1/grpcserver/server_grpc_reg.go index 5fac5e2..3d25d27 100644 --- a/src/v1/grpcserver/servier_reg.go +++ b/src/v1/grpcserver/server_grpc_reg.go @@ -3,5 +3,5 @@ package grpcserver //服务注册者 接口 type IServiceRegister interface{ - Register(name string,addr string) + Register(name string,addr string) error } -- Gitee From ac175ccc42ee5e34a1d020e9773d8d328e71b5dd Mon Sep 17 00:00:00 2001 From: Sage <1010309281@qq.com> Date: Mon, 27 Sep 2021 01:19:29 +0000 Subject: [PATCH 03/12] =?UTF-8?q?=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/v1/clients/grpc/client.go | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/v1/clients/grpc/client.go b/src/v1/clients/grpc/client.go index 602b6c2..7481004 100644 --- a/src/v1/clients/grpc/client.go +++ b/src/v1/clients/grpc/client.go @@ -44,3 +44,17 @@ func NewRemoteConn(options IOptions) (*grpc.ClientConn, error) { return grpc.DialContext(ctx, address, grpc.WithInsecure(), grpc.WithBlock(), serviceConfig) } + +func OptDiscovery(){ + + balancer.Register(base.NewBalancerBuilder(b.Name(), b, base.Config{HealthCheck: true}), ) + + this.balanceName = b.Name() +} + + +func GetConn(){ + + serviceConfig := grpc.WithDefaultServiceConfig(fmt.Sprintf("{\"loadBalancingConfig\":[{\"%s\":{}}]}", balanceName)) + return grpc.DialContext(ctx, address, grpc.WithInsecure(), grpc.WithBlock(), serviceConfig) +} \ No newline at end of file -- Gitee From 9a42411d36c2ce5e14e1ecb714b8610cdd79316b Mon Sep 17 00:00:00 2001 From: Sage <1010309281@qq.com> Date: Tue, 28 Sep 2021 20:48:57 +0800 Subject: [PATCH 04/12] =?UTF-8?q?=E6=96=B0=E5=A2=9E=20grpc=20client?= =?UTF-8?q?=E5=92=8Cserver?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- examples/grpc/client_grpc.go | 30 +++++++++ examples/grpc/server_grpc.go | 26 ++++++++ src/v1/clients/etcd/driver.go | 1 + src/v1/clients/grpc/client.go | 61 +++++++++++++------ src/v1/clients/grpc/option.go | 50 --------------- src/v1/grpcserver/server_grpc.go | 3 +- ...er_dis_etcd.go => server_grpc_dis_etcd.go} | 2 +- 7 files changed, 102 insertions(+), 71 deletions(-) create mode 100644 examples/grpc/client_grpc.go create mode 100644 examples/grpc/server_grpc.go rename src/v1/grpcserver/{server_dis_etcd.go => server_grpc_dis_etcd.go} (83%) diff --git a/examples/grpc/client_grpc.go b/examples/grpc/client_grpc.go new file mode 100644 index 0000000..295c7ec --- /dev/null +++ b/examples/grpc/client_grpc.go @@ -0,0 +1,30 @@ +package main + +import ( + "fmt" + v1rpcclient "gitee.com/scottq/go-framework/src/v1/clients/grpc" + v1log "gitee.com/scottq/go-framework/src/v1/log" + "os" + "path/filepath" +) + +func main() { + + logPath := fmt.Sprintf("./runtime/logs/%s.log", filepath.Base(os.Args[0])) + logger := v1log.NewZapLog("example", logPath, nil) + + opts := []v1rpcclient.RemoteOption{} + + if false { + opts = append(opts, v1rpcclient.OpsEtcdDiscovery("admin", "127.0.0.1:2379")) + } + + c, err := v1rpcclient.NewRemoteConn("127.0.0.1:40001", opts..., ) + if err != nil { + logger.Errorf("new remote conn err:%s", err) + return + } + + info := c.GetState() + logger.Info(info.String()) +} diff --git a/examples/grpc/server_grpc.go b/examples/grpc/server_grpc.go new file mode 100644 index 0000000..b86295b --- /dev/null +++ b/examples/grpc/server_grpc.go @@ -0,0 +1,26 @@ +package main + +import ( + "fmt" + v1rpc "gitee.com/scottq/go-framework/src/v1/grpcserver" + v1log "gitee.com/scottq/go-framework/src/v1/log" + "os" + "path/filepath" +) + +func main() { + logPath := fmt.Sprintf("./runtime/logs/%s.log", filepath.Base(os.Args[0])) + logger := v1log.NewZapLog( "example", logPath, nil) + + server, err := v1rpc.NewGRPCServer("", ":40001") + if err != nil { + logger.Error("run server error:%s" + err.Error()) + return + } + if false { + etcd, _ := v1rpc.NewEtcdSrvRegister("0.0.0.0:2379") + server.AddServiceRegister(etcd) + } + + server.Run() +} diff --git a/src/v1/clients/etcd/driver.go b/src/v1/clients/etcd/driver.go index 81b3e81..6bd4af3 100644 --- a/src/v1/clients/etcd/driver.go +++ b/src/v1/clients/etcd/driver.go @@ -30,3 +30,4 @@ func NewEtcdV3Wrapper(endpoints string, dialTimeout int64, timeout int64) (*Etcd timeout: timeout, }, nil } + diff --git a/src/v1/clients/grpc/client.go b/src/v1/clients/grpc/client.go index 602b6c2..74d63f7 100644 --- a/src/v1/clients/grpc/client.go +++ b/src/v1/clients/grpc/client.go @@ -11,36 +11,61 @@ import ( "time" ) -func NewRemoteConn(options IOptions) (*grpc.ClientConn, error) { - address := options.GetAddress() - // Set up a connection to the server. - ctx, cancel := context.WithTimeout(context.Background(), time.Duration(options.GetTimeout())*time.Second) - defer cancel() +type RemoteOption func(*RemoteConn) error + +type RemoteConn struct { + addr string + balanceName string + timeout int64 +} + +func NewRemoteConn(addr string, options ...RemoteOption) (*grpc.ClientConn, error) { defer func() { if err := recover(); err != nil { - panic(fmt.Errorf("[%s]%s", options.GetName(), err)) + panic(fmt.Errorf("%s", err)) } }() - balanceName := "round_robin" + rConn := &RemoteConn{ + addr: addr, + balanceName: "round_robin", + timeout: 10, + } - //使用服务发现 - switch options.GetDiscovery() { - case "etcd": - d, err := v1etcd.NewServiceDiscovery(options.GetDiscoveryAddr(), 5) + for _, opt := range options { + err := opt(rConn) if err != nil { - //panic(err) return nil, err } + } + + return rConn.getClient() +} + +func (conn *RemoteConn) getClient() (*grpc.ClientConn, error) { + + ctx, cancel := context.WithTimeout(context.Background(), time.Duration(conn.timeout)*time.Second) + defer cancel() + + serviceConfig := grpc.WithDefaultServiceConfig(fmt.Sprintf("{\"loadBalancingConfig\":[{\"%s\":{}}]}", conn.balanceName)) + + return grpc.DialContext(ctx, conn.addr, grpc.WithInsecure(), grpc.WithBlock(), serviceConfig) +} + +func OpsEtcdDiscovery(name, addr string) RemoteOption { + + return func(conn *RemoteConn) error { + d, err := v1etcd.NewServiceDiscovery(addr, 5) + if err != nil { + return err + } resolver.Register(d) - address = fmt.Sprintf("%s://8.8.8.8/%s", d.Scheme(), options.GetName()) b := &WeightBalance{} balancer.Register(base.NewBalancerBuilder(b.Name(), b, base.Config{HealthCheck: true}), ) - balanceName = b.Name() - } - serviceConfig := grpc.WithDefaultServiceConfig(fmt.Sprintf("{\"loadBalancingConfig\":[{\"%s\":{}}]}", balanceName)) - - return grpc.DialContext(ctx, address, grpc.WithInsecure(), grpc.WithBlock(), serviceConfig) + conn.addr = fmt.Sprintf("%s://8.8.8.8/%s", d.Scheme(), name) + conn.balanceName = b.Name() + return nil + } } diff --git a/src/v1/clients/grpc/option.go b/src/v1/clients/grpc/option.go index c1f3134..21e034e 100644 --- a/src/v1/clients/grpc/option.go +++ b/src/v1/clients/grpc/option.go @@ -1,51 +1 @@ package grpc - -type IOptions interface { - GetTimeout() int64 - GetAddress() string - GetName() string - - GetDiscovery() string - GetDiscoveryAddr() string -} - -type RemoteOptions struct { - SrName string - SrAddress string - Timeout int64 - RemoteType string - - //服务发现client和client地址 - DiscoveryClient string - DiscoveryAddr string -} - -const defaultTimeout = 3 - -func (op *RemoteOptions) GetTimeout() int64 { - if op.Timeout <= 0 { - return defaultTimeout - } - return op.Timeout -} -func (op *RemoteOptions) GetRemoteType() string { - return op.RemoteType -} -func (op *RemoteOptions) GetAddress() string { - return op.SrAddress -} -func (op *RemoteOptions) GetName() string { - return op.SrName -} - -func (op *RemoteOptions) GetDiscovery() string { - return op.DiscoveryClient -} -func (op *RemoteOptions) GetDiscoveryAddr() string { - return op.DiscoveryAddr -} - -func (op *RemoteOptions) SetDiscovery(client string, discoveryAddr string) { - op.DiscoveryClient = client - op.DiscoveryAddr = discoveryAddr -} diff --git a/src/v1/grpcserver/server_grpc.go b/src/v1/grpcserver/server_grpc.go index 290fbbc..e3b0611 100644 --- a/src/v1/grpcserver/server_grpc.go +++ b/src/v1/grpcserver/server_grpc.go @@ -1,7 +1,6 @@ package grpcserver import ( - "fmt" "gitee.com/scottq/go-framework/src/utils" "google.golang.org/grpc" "log" @@ -52,7 +51,7 @@ func (svr *GRPCServer) run() error { svr.HandlerFunc(svr.s) } - fmt.Printf("[%s]rpc running at %s\n", svr.name, svr.listenAddr) + log.Printf("[%s]rpc running at %s\n", svr.name, svr.listenAddr) if err := svr.s.Serve(lis); err != nil { log.Fatalf("failed to serve: %v", err) return err diff --git a/src/v1/grpcserver/server_dis_etcd.go b/src/v1/grpcserver/server_grpc_dis_etcd.go similarity index 83% rename from src/v1/grpcserver/server_dis_etcd.go rename to src/v1/grpcserver/server_grpc_dis_etcd.go index 31e3c15..004592c 100644 --- a/src/v1/grpcserver/server_dis_etcd.go +++ b/src/v1/grpcserver/server_grpc_dis_etcd.go @@ -8,7 +8,7 @@ type EtcdRegisterFinder struct { etcdAddr string } -func NewEtcdRegisterFinder(etcdAddr string, ) (IServiceRegister, error) { +func NewEtcdSrvRegister(etcdAddr string, ) (IServiceRegister, error) { return &EtcdRegisterFinder{ etcdAddr: etcdAddr, }, nil -- Gitee From a735b7450a0ac84ad2dad71d8ca7de87aeb2adb4 Mon Sep 17 00:00:00 2001 From: Sage <1010309281@qq.com> Date: Tue, 28 Sep 2021 20:50:13 +0800 Subject: [PATCH 05/12] =?UTF-8?q?=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- examples/grpc/client_grpc.go | 2 +- src/v1/clients/etcd/{driver.go => client.go} | 0 src/v1/clients/grpc/client.go | 15 +-------------- 3 files changed, 2 insertions(+), 15 deletions(-) rename src/v1/clients/etcd/{driver.go => client.go} (100%) diff --git a/examples/grpc/client_grpc.go b/examples/grpc/client_grpc.go index 295c7ec..e8687b1 100644 --- a/examples/grpc/client_grpc.go +++ b/examples/grpc/client_grpc.go @@ -16,7 +16,7 @@ func main() { opts := []v1rpcclient.RemoteOption{} if false { - opts = append(opts, v1rpcclient.OpsEtcdDiscovery("admin", "127.0.0.1:2379")) + opts = append(opts, v1rpcclient.OptEtcdDiscovery("admin", "127.0.0.1:2379")) } c, err := v1rpcclient.NewRemoteConn("127.0.0.1:40001", opts..., ) diff --git a/src/v1/clients/etcd/driver.go b/src/v1/clients/etcd/client.go similarity index 100% rename from src/v1/clients/etcd/driver.go rename to src/v1/clients/etcd/client.go diff --git a/src/v1/clients/grpc/client.go b/src/v1/clients/grpc/client.go index fddfaf7..21e751f 100644 --- a/src/v1/clients/grpc/client.go +++ b/src/v1/clients/grpc/client.go @@ -52,7 +52,7 @@ func (conn *RemoteConn) getClient() (*grpc.ClientConn, error) { return grpc.DialContext(ctx, conn.addr, grpc.WithInsecure(), grpc.WithBlock(), serviceConfig) } -func OpsEtcdDiscovery(name, addr string) RemoteOption { +func OptEtcdDiscovery(name, addr string) RemoteOption { return func(conn *RemoteConn) error { d, err := v1etcd.NewServiceDiscovery(addr, 5) @@ -70,16 +70,3 @@ func OpsEtcdDiscovery(name, addr string) RemoteOption { } } -func OptDiscovery(){ - - balancer.Register(base.NewBalancerBuilder(b.Name(), b, base.Config{HealthCheck: true}), ) - - this.balanceName = b.Name() -} - - -func GetConn(){ - - serviceConfig := grpc.WithDefaultServiceConfig(fmt.Sprintf("{\"loadBalancingConfig\":[{\"%s\":{}}]}", balanceName)) - return grpc.DialContext(ctx, address, grpc.WithInsecure(), grpc.WithBlock(), serviceConfig) -} \ No newline at end of file -- Gitee From 4de052935c7e0c069a3cf8eb027dcdb11124b017 Mon Sep 17 00:00:00 2001 From: Sage <1010309281@qq.com> Date: Wed, 29 Sep 2021 03:04:13 +0000 Subject: [PATCH 06/12] =?UTF-8?q?=E6=96=B0=E5=A2=9E=20protos=E7=9B=B8?= =?UTF-8?q?=E5=85=B3=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- grpcProtos/compile_protocol.sh | 19 +++++++++ grpcProtos/protos/demoReq.proto | 45 +++++++++++++++++++++ grpcProtos/protos/pb_structs/demo.proto | 25 ++++++++++++ grpcProtos/protos/pb_structs/req_resp.proto | 29 +++++++++++++ 4 files changed, 118 insertions(+) create mode 100644 grpcProtos/compile_protocol.sh create mode 100644 grpcProtos/protos/demoReq.proto create mode 100644 grpcProtos/protos/pb_structs/demo.proto create mode 100644 grpcProtos/protos/pb_structs/req_resp.proto diff --git a/grpcProtos/compile_protocol.sh b/grpcProtos/compile_protocol.sh new file mode 100644 index 0000000..def960d --- /dev/null +++ b/grpcProtos/compile_protocol.sh @@ -0,0 +1,19 @@ +#!/bin/bash + +modName="gitee.com/scottq/go-framework/grpcProtos/pb/pb_structs" + +protoc --proto_path=./protos/pb_structs/ \ + --go_out=. --go-grpc_out=. \ + ./protos/pb_structs/*.proto + +protoc --proto_path=./protos/ --go_out=. \ + --go_opt=Mpb_structs/demo.proto=${modName} \ + --go_opt=Mpb_structs/admin.proto=${modName} \ + --go_opt=Mpb_structs/error.proto=${modName} \ + --go-grpc_opt=Mpb_structs/demo.proto=${modName} \ + --go-grpc_opt=Mpb_structs/admin.proto=${modName} \ + --go-grpc_opt=Mpb_structs/error.proto=${modName} \ + --go-grpc_out=. \ + ./protos/*.proto + + diff --git a/grpcProtos/protos/demoReq.proto b/grpcProtos/protos/demoReq.proto new file mode 100644 index 0000000..c2fbb0a --- /dev/null +++ b/grpcProtos/protos/demoReq.proto @@ -0,0 +1,45 @@ +// Copyright 2015 gRPC 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. + +syntax = "proto3"; + +option go_package = "/pb"; +import "pb_structs/demo.proto"; +import "pb_structs/req_resp.proto"; +package pb; + +// The greeting service definition. +service UserSr { + // Sends a greeting + rpc CheckAuth (CheckAuthRequest) returns (pb_structs.RespStc) {} + rpc AddLog (AdminLogRequest) returns (AdminLogResponse) {} +} + +message CheckAuthRequest{ + pb_structs.Authorization authorization = 1; + pb_structs.AdminLog admin_log = 2; +} + +message CheckAuthResponse{ + string message=1; +} + +message AddLogRequest{ + pb_structs.Authorization authorization = 1; + pb_structs.AdminLog admin_log = 2; +} + +message AddLogResponse{ + string message=1; +} \ No newline at end of file diff --git a/grpcProtos/protos/pb_structs/demo.proto b/grpcProtos/protos/pb_structs/demo.proto new file mode 100644 index 0000000..bc26786 --- /dev/null +++ b/grpcProtos/protos/pb_structs/demo.proto @@ -0,0 +1,25 @@ +// Copyright 2015 gRPC 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. + +syntax = "proto3"; + +option go_package = "pb/pb_structs"; +package pb_structs; + +// The response message containing the greetings +message User { + string nickanme = 1; + string account = 2; + int uid = 3; +} \ No newline at end of file diff --git a/grpcProtos/protos/pb_structs/req_resp.proto b/grpcProtos/protos/pb_structs/req_resp.proto new file mode 100644 index 0000000..295a443 --- /dev/null +++ b/grpcProtos/protos/pb_structs/req_resp.proto @@ -0,0 +1,29 @@ +// Copyright 2015 gRPC 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. + +syntax = "proto3"; + +option go_package = "pb/pb_structs"; +package pb_structs; + +// The response message containing the greetings +message ReqStc { + string request_id = 1; +} + +message RespStc { + string code = 1; + string message = 2; + string data = 3; +} \ No newline at end of file -- Gitee From 0733dc16baf475db176f371224d8075da0a07c63 Mon Sep 17 00:00:00 2001 From: Sage <1010309281@qq.com> Date: Wed, 29 Sep 2021 03:31:48 +0000 Subject: [PATCH 07/12] =?UTF-8?q?=E6=96=B0=E5=A2=9E=20=E6=B5=8B=E8=AF=95se?= =?UTF-8?q?rver?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- examples/grpc/sr.go | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 examples/grpc/sr.go diff --git a/examples/grpc/sr.go b/examples/grpc/sr.go new file mode 100644 index 0000000..fe90ce4 --- /dev/null +++ b/examples/grpc/sr.go @@ -0,0 +1,25 @@ +package grpc + + +type DemoServer struct { + pb.UnimplementedDemoSrServer +} + +func NewDemoServer(conf *config.SrConfig) *AdminServer { + RunApp := bootstrap.NewApp(conf) + + app = RunApp + logger = app.Logger + + return &AdminServer{ + App: RunApp, + } +} + +func (s *DemoServer) CheckAuth(authorization *pb_structs.CheckAuthRequest) *models.Admin { + token := authorization.GetToken() + + admin, _, _ := s.ParseAuthorization(token) + + return admin +} -- Gitee From 03c59495352887fdf679ea8964fe9100dda8daea Mon Sep 17 00:00:00 2001 From: Sage <1010309281@qq.com> Date: Wed, 29 Sep 2021 09:09:47 +0000 Subject: [PATCH 08/12] =?UTF-8?q?=E6=96=B0=E5=A2=9E=20coMag?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/v1/comag/comag.go | 11 ++++++++ src/v1/comag/comag_failallfail.go | 47 +++++++++++++++++++++++++++++++ src/v1/comag/comag_test.go | 45 +++++++++++++++++++++++++++++ 3 files changed, 103 insertions(+) create mode 100644 src/v1/comag/comag.go create mode 100644 src/v1/comag/comag_failallfail.go create mode 100644 src/v1/comag/comag_test.go diff --git a/src/v1/comag/comag.go b/src/v1/comag/comag.go new file mode 100644 index 0000000..e11da67 --- /dev/null +++ b/src/v1/comag/comag.go @@ -0,0 +1,11 @@ +package comag + +type CoFunc func(context.Context) + +func debugPrint(msg string, params ...interface{}) { + if len(params) <= 0 { + fmt.Println(msg) + return + } + fmt.Printf(msg+"\n", params...) +} diff --git a/src/v1/comag/comag_failallfail.go b/src/v1/comag/comag_failallfail.go new file mode 100644 index 0000000..bb27d64 --- /dev/null +++ b/src/v1/comag/comag_failallfail.go @@ -0,0 +1,47 @@ +package comag + +type CoFunc func(context.Context) + + +//CoMag 一次失败全部失败 +type FailAllFailCoMag struct { + coArr []CoFunc + wg sync.WaitGroup +} + +func NewFailAllFailCoMag() *FailAllFailCoMag { + return &FailAllFailCoMag{ + coArr: []CoFunc{}, + } +} + +func (mg *FailAllFailCoMag) Add(f CoFunc) { + mg.coArr = append(mg.coArr, f) +} + +func (mg *FailAllFailCoMag) Run() { + ctx, cancel := context.WithCancel(context.Background()) + errCh := make(chan error) + ctx = context.WithValue(ctx, "error", errCh) + for _, f := range mg.coArr { + do:=f + mg.wg.Add(1) + go func() { + do(ctx) + mg.wg.Done() + }() + } + + //监听 err ch + go func() { + for { + select { + case err := <-errCh: + debugPrint("happen err: %s",err.Error()) + cancel() + } + } + }() + + mg.wg.Wait() +} diff --git a/src/v1/comag/comag_test.go b/src/v1/comag/comag_test.go new file mode 100644 index 0000000..8d37af3 --- /dev/null +++ b/src/v1/comag/comag_test.go @@ -0,0 +1,45 @@ +package comag + +func TestCoMag(){ + mg := NewFailAllFailCoMag() + + mg.Add(inputCo) + mg.Add(outputCo) + mg.Run() + + debugPrint("end") + +} + +func inputCo(ctx context.Context) { + errCh := ctx.Value("error").(chan error) + + for i := 1; i <= 100; i++ { + select { + case <-ctx.Done(): + debugPrint("input Done by ctx: %s", ctx.Err()) + return + default: + if i > 10 { + errCh <- fmt.Errorf("input error") + return + } + debugPrint("input:%d", i) + time.Sleep(time.Second) + } + } +} + +func outputCo(ctx context.Context) { + for i := 1; i <= 100; i++ { + select { + case <-ctx.Done(): + debugPrint("out Done by ctx: %s", ctx.Err()) + return + default: + debugPrint("out:%d", i) + time.Sleep(time.Second) + } + } + debugPrint("out Done") +} -- Gitee From 46b3d4fde4905adbbc45b633d7b96c08282452c2 Mon Sep 17 00:00:00 2001 From: Sage <1010309281@qq.com> Date: Wed, 29 Sep 2021 09:36:11 +0000 Subject: [PATCH 09/12] =?UTF-8?q?=E4=BF=AE=E6=94=B9=20log=E6=8E=A5?= =?UTF-8?q?=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/v1/log/log.go | 43 ++++++++++++++++------- src/v1/log/log_default.go | 74 +++++++++++++++++---------------------- src/v1/log/log_zap.go | 73 ++++++++++++++++---------------------- 3 files changed, 92 insertions(+), 98 deletions(-) diff --git a/src/v1/log/log.go b/src/v1/log/log.go index 4b21237..110dcb5 100644 --- a/src/v1/log/log.go +++ b/src/v1/log/log.go @@ -27,19 +27,12 @@ var LogLevelMap = map[int]string{ const DefaultLogPath = "./runtime/logs/daily.log" type ILog interface { - Debug(log string) error - Info(log string) error - Warn(log string) error - Error(log string) error - Panic(log string) error - Fatal(log string) error - - Debugf(log string, params ...interface{}) error - Infof(log string, params ...interface{}) error - Warnf(log string, params ...interface{}) error - Errorf(log string, params ...interface{}) error - Panicf(log string, params ...interface{}) error - Fatalf(log string, params ...interface{}) error + Debug(log string, params ...interface{}) error + Info(log string, params ...interface{}) error + Warn(log string, params ...interface{}) error + Error(log string, params ...interface{}) error + Panic(log string, params ...interface{}) error + Fatal(log string, params ...interface{}) error } //fast use log @@ -80,6 +73,10 @@ func (ink *InvokeLog) Debug(log string, params ...interface{}) error { if ink.logger == nil { return nil } + if len(params)<=0{ + returnink.logger.Debug(log) + return + } return ink.logger.Debug(fmt.Sprintf(log, params...)) } @@ -88,6 +85,10 @@ func (ink *InvokeLog) Info(log string, params ...interface{}) error { if ink.logger == nil { return nil } + if len(params)<=0{ + returnink.logger.Info(log) + return + } return ink.logger.Info(fmt.Sprintf(log, params...)) } @@ -96,6 +97,10 @@ func (ink *InvokeLog) Warn(log string, params ...interface{}) error { if ink.logger == nil { return nil } + if len(params)<=0{ + returnink.logger.Warn(log) + return + } return ink.logger.Warn(fmt.Sprintf(log, params...)) } @@ -103,6 +108,10 @@ func (ink *InvokeLog) Error(log string, params ...interface{}) error { if ink.logger == nil { return nil } + if len(params)<=0{ + returnink.logger.Error(log) + return + } return ink.logger.Error(fmt.Sprintf(log, params...)) } @@ -111,6 +120,10 @@ func (ink *InvokeLog) Panic(log string, params ...interface{}) error { if ink.logger == nil { return nil } + if len(params)<=0{ + returnink.logger.Panic(log) + return + } return ink.logger.Panic(fmt.Sprintf(log, params...)) } @@ -118,6 +131,10 @@ func (ink *InvokeLog) Fatal(log string, params ...interface{}) error { if ink.logger == nil { return nil } + if len(params)<=0{ + returnink.logger.Fatal(log) + return + } return ink.logger.Fatal(fmt.Sprintf(log, params...)) } diff --git a/src/v1/log/log_default.go b/src/v1/log/log_default.go index e8dc254..af30c51 100644 --- a/src/v1/log/log_default.go +++ b/src/v1/log/log_default.go @@ -101,56 +101,46 @@ func (logger *MyLogger) LogPath() string { return fmt.Sprintf("%s-%s.log", p[:len(p)-len(".log")], t) } -func (logger *MyLogger) Trace(s string) error { - return logger.logItem(TraceLog, s) -} - -func (logger *MyLogger) Debug(s string) error { - return logger.logItem(DebugLog, s) -} - -func (logger *MyLogger) Info(s string) error { - return logger.logItem(InfoLog, s) -} - -func (logger *MyLogger) Warn(s string) error { - return logger.logItem(WarnLog, s) -} - -func (logger *MyLogger) Error(s string) error { - return logger.logItem(ErrorLog, s) -} - -func (logger *MyLogger) Panic(s string) error { - return logger.logItem(PanicLog, s) -} - -func (logger *MyLogger) Fatal(s string) error { - return logger.logItem(FatalLog, s) -} - -func (logger *MyLogger) Debugf(format string, s ...interface{}) error { - return logger.Debug(fmt.Sprintf(format, s...)) +func (logger *MyLogger) Debug(format string, params ...interface{}) error { + if len(params)<=0{ + return logger.logItem(DebugLog, format) + } + return logger.Debug(fmt.Sprintf(format, params...)) } -func (logger *MyLogger) Infof(format string, s ...interface{}) error { - return logger.Info(fmt.Sprintf(format, s...)) +func (logger *MyLogger) Info(format string, params ...interface{}) error { + if len(params)<=0{ + return logger.logItem(InfoLog, format) + } + return logger.Info(fmt.Sprintf(format, params...)) } -func (logger *MyLogger) Warnf(format string, s ...interface{}) error { - return logger.Warn(fmt.Sprintf(format, s...)) +func (logger *MyLogger) Warn(format string, params ...interface{}) error { + if len(params)<=0{ + return logger.logItem(WarnLog, format) + } + return logger.Warn(fmt.Sprintf(format, params...)) } -func (logger *MyLogger) Errorf(format string, s ...interface{}) error { - return logger.Error(fmt.Sprintf(format, s...)) +func (logger *MyLogger) Error(format string, params ...interface{}) error { + if len(params)<=0{ + return logger.logItem(ErrorLog, format) + } + return logger.Error(fmt.Sprintf(format, params...)) } -func (logger *MyLogger) Fatalf(format string, s ...interface{}) error { - return logger.Fatal(fmt.Sprintf(format, s...)) +func (logger *MyLogger) Fatal(format string, params ...interface{}) error { + if len(params)<=0{ + return logger.logItem(FatalLog, format) + } + return logger.Fatal(fmt.Sprintf(format, params...)) } -func (logger *MyLogger) Panicf(format string, s ...interface{}) error { - return logger.Panic(fmt.Sprintf(format, s...)) +func (logger *MyLogger) Panic(format string, params ...interface{}) error { + if len(params)<=0{ + return logger.logItem(PanicLog, format) + } + return logger.Panic(fmt.Sprintf(format, params...)) } func (logger *MyLogger) logItem(level int, s string) error { @@ -158,8 +148,8 @@ func (logger *MyLogger) logItem(level int, s string) error { return logger.logger.Output(3, sl) } -func (logger *MyLogger) logItemf(level int, format string, s ...interface{}) error { - sl := fmt.Sprintf("%s\n%d\n", fmt.Sprintf(format, s...), level) +func (logger *MyLogger) logItemf(level int, format string, params ...interface{}) error { + sl := fmt.Sprintf("%s\n%d\n", fmt.Sprintf(format, params...), level) return logger.logger.Output(3, sl) } diff --git a/src/v1/log/log_zap.go b/src/v1/log/log_zap.go index 63e082b..27ceb84 100644 --- a/src/v1/log/log_zap.go +++ b/src/v1/log/log_zap.go @@ -82,57 +82,44 @@ func NewZapLog(name string, logPath string, config *ZapLogConfig) ILog { } } -func (l *DefaultZapLog) Debug(msg string) error { - l.zapLog.Debug(msg) - return nil -} - -func (l *DefaultZapLog) Info(msg string) error { - l.zapLog.Info(msg) - return nil -} - -func (l *DefaultZapLog) Warn(msg string) error { - l.zapLog.Warn(msg) - return nil -} - -func (l *DefaultZapLog) Error(msg string) error { - l.zapLog.Error(msg) - return nil -} - -func (l *DefaultZapLog) Panic(msg string) error { - l.zapLog.Panic(msg) - return nil -} - -func (l *DefaultZapLog) Fatal(msg string) error { - l.zapLog.Fatal(msg) - return nil -} - - -func (l *DefaultZapLog) Debugf(format string, s ...interface{}) error { - return l.Debug(fmt.Sprintf(format, s...)) +func (l *DefaultZapLog) Debug(format string, params ...interface{}) error { + if len(params)<=0{ + return l.zapLog.Debug(format) + } + return l.Debug(fmt.Sprintf(format, params...)) } -func (l *DefaultZapLog) Infof(format string, s ...interface{}) error { - return l.Info(fmt.Sprintf(format, s...)) +func (l *DefaultZapLog) Info(format string, params ...interface{}) error { + if len(params)<=0{ + return l.zapLog.Info(format) + } + return l.Info(fmt.Sprintf(format, params...)) } -func (l *DefaultZapLog) Warnf(format string, s ...interface{}) error { - return l.Warn(fmt.Sprintf(format, s...)) +func (l *DefaultZapLog) Warn(format string, params ...interface{}) error { + if len(params)<=0{ + return l.zapLog.Warn(format) + } + return l.Warn(fmt.Sprintf(format, params...)) } -func (l *DefaultZapLog) Errorf(format string, s ...interface{}) error { - return l.Error(fmt.Sprintf(format, s...)) +func (l *DefaultZapLog) Error(format string, params ...interface{}) error { + if len(params)<=0{ + return l.zapLog.Error(format) + } + return l.Error(fmt.Sprintf(format, params...)) } -func (l *DefaultZapLog) Fatalf(format string, s ...interface{}) error { - return l.Fatal(fmt.Sprintf(format, s...)) +func (l *DefaultZapLog) Fatal(format string, params ...interface{}) error { + if len(params)<=0{ + return l.zapLog.Fatal(format) + } + return l.Fatal(fmt.Sprintf(format, params...)) } -func (l *DefaultZapLog) Panicf(format string, s ...interface{}) error { - return l.Panic(fmt.Sprintf(format, s...)) +func (l *DefaultZapLog) Panic(format string, params ...interface{}) error { + if len(params)<=0{ + return l.zapLog.Panic(format) + } + return l.Panic(fmt.Sprintf(format, params...)) } -- Gitee From 8567bf7dbc2b752778b4b1ba33ef23943a454c51 Mon Sep 17 00:00:00 2001 From: Sage <1010309281@qq.com> Date: Wed, 29 Sep 2021 20:31:53 +0800 Subject: [PATCH 10/12] =?UTF-8?q?=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- examples/grpc/sr.go | 25 -- examples/handler/run_optim_lock.go | 9 +- examples/{grpc => run_grpc}/client_grpc.go | 45 ++- examples/{grpc => run_grpc}/server_grpc.go | 28 +- examples/run_rpc/run_rpcserver.go | 28 -- go.mod | 1 + grpcProtos/pb/demoReq.pb.go | 397 ++++++++++++++++++++ grpcProtos/pb/demoReq_grpc.pb.go | 139 +++++++ grpcProtos/pb/pb_structs/demo.pb.go | 176 +++++++++ grpcProtos/pb/pb_structs/req_resp.pb.go | 238 ++++++++++++ grpcProtos/protos/demoReq.proto | 19 +- grpcProtos/protos/pb_structs/demo.proto | 2 +- grpcProtos/protos/pb_structs/req_resp.proto | 2 +- src/v1/comag/comag.go | 5 + src/v1/comag/comag_failallfail.go | 6 +- src/v1/comag/comag_test.go | 9 +- src/v1/log/log.go | 18 +- src/v1/log/log_zap.go | 30 +- 18 files changed, 1075 insertions(+), 102 deletions(-) delete mode 100644 examples/grpc/sr.go rename examples/{grpc => run_grpc}/client_grpc.go (35%) rename examples/{grpc => run_grpc}/server_grpc.go (45%) delete mode 100644 examples/run_rpc/run_rpcserver.go create mode 100644 grpcProtos/pb/demoReq.pb.go create mode 100644 grpcProtos/pb/demoReq_grpc.pb.go create mode 100644 grpcProtos/pb/pb_structs/demo.pb.go create mode 100644 grpcProtos/pb/pb_structs/req_resp.pb.go diff --git a/examples/grpc/sr.go b/examples/grpc/sr.go deleted file mode 100644 index fe90ce4..0000000 --- a/examples/grpc/sr.go +++ /dev/null @@ -1,25 +0,0 @@ -package grpc - - -type DemoServer struct { - pb.UnimplementedDemoSrServer -} - -func NewDemoServer(conf *config.SrConfig) *AdminServer { - RunApp := bootstrap.NewApp(conf) - - app = RunApp - logger = app.Logger - - return &AdminServer{ - App: RunApp, - } -} - -func (s *DemoServer) CheckAuth(authorization *pb_structs.CheckAuthRequest) *models.Admin { - token := authorization.GetToken() - - admin, _, _ := s.ParseAuthorization(token) - - return admin -} diff --git a/examples/handler/run_optim_lock.go b/examples/handler/run_optim_lock.go index 39e3b68..47049f3 100644 --- a/examples/handler/run_optim_lock.go +++ b/examples/handler/run_optim_lock.go @@ -1,11 +1,6 @@ package main -import ( - "gitee.com/scottq/go-framework/src/v1/handler" - "time" -) - -func main(){ - optLock,err:=handler.NewOptimisticLock(db,time.Second*10) +func main() { + //optLock,err:=handler.NewOptimisticLock(db,time.Second*10) } diff --git a/examples/grpc/client_grpc.go b/examples/run_grpc/client_grpc.go similarity index 35% rename from examples/grpc/client_grpc.go rename to examples/run_grpc/client_grpc.go index e8687b1..384ed24 100644 --- a/examples/grpc/client_grpc.go +++ b/examples/run_grpc/client_grpc.go @@ -1,9 +1,12 @@ package main import ( + "context" "fmt" + "gitee.com/scottq/go-framework/grpcProtos/pb" v1rpcclient "gitee.com/scottq/go-framework/src/v1/clients/grpc" v1log "gitee.com/scottq/go-framework/src/v1/log" + "google.golang.org/grpc" "os" "path/filepath" ) @@ -19,12 +22,48 @@ func main() { opts = append(opts, v1rpcclient.OptEtcdDiscovery("admin", "127.0.0.1:2379")) } - c, err := v1rpcclient.NewRemoteConn("127.0.0.1:40001", opts..., ) + conn, err := v1rpcclient.NewRemoteConn("127.0.0.1:40001", opts..., ) if err != nil { - logger.Errorf("new remote conn err:%s", err) + logger.Error("new remote conn err:%s", err) return } - info := c.GetState() + info := conn.GetState() logger.Info(info.String()) + + c := NewRemoteClient(conn) + + resp, err := c.CheckAuth("12334") + if err != nil { + logger.Error("fail:%s", err) + return + } + logger.Info("resp:%v", resp) +} + +type RemoteClient struct { + remoteSr pb.UserSrClient +} + +func NewRemoteClient(conn *grpc.ClientConn) *RemoteClient { + c := pb.NewUserSrClient(conn) + return &RemoteClient{ + remoteSr: c, + } +} + +func (sr *RemoteClient) CheckAuth(token string) (map[string]interface{}, error) { + authorization := &pb.CheckAuthRequest{Token: token} + + admin, err := sr.remoteSr.CheckAuth(context.Background(), authorization) + if err != nil { + return nil, err + } + if admin == nil { + return nil, nil + } + + return map[string]interface{}{ + "message": admin.Message, + }, nil } diff --git a/examples/grpc/server_grpc.go b/examples/run_grpc/server_grpc.go similarity index 45% rename from examples/grpc/server_grpc.go rename to examples/run_grpc/server_grpc.go index b86295b..b41c221 100644 --- a/examples/grpc/server_grpc.go +++ b/examples/run_grpc/server_grpc.go @@ -1,22 +1,29 @@ package main import ( + "context" "fmt" + "gitee.com/scottq/go-framework/grpcProtos/pb" v1rpc "gitee.com/scottq/go-framework/src/v1/grpcserver" v1log "gitee.com/scottq/go-framework/src/v1/log" + "google.golang.org/grpc" "os" "path/filepath" ) func main() { logPath := fmt.Sprintf("./runtime/logs/%s.log", filepath.Base(os.Args[0])) - logger := v1log.NewZapLog( "example", logPath, nil) + logger := v1log.NewZapLog("example", logPath, nil) server, err := v1rpc.NewGRPCServer("", ":40001") if err != nil { logger.Error("run server error:%s" + err.Error()) return } + server.HandlerFunc = func(server *grpc.Server) { + s := NewDemoServer() + pb.RegisterUserSrServer(server, s) + } if false { etcd, _ := v1rpc.NewEtcdSrvRegister("0.0.0.0:2379") server.AddServiceRegister(etcd) @@ -24,3 +31,22 @@ func main() { server.Run() } + +type DemoServer struct { + pb.UnimplementedUserSrServer +} + +func NewDemoServer() *DemoServer { + return &DemoServer{ + + } +} + +func (s *DemoServer) CheckAuth(ctx context.Context, req *pb.CheckAuthRequest) (*pb.CheckAuthResponse, error) { + token := req.GetToken() + + return &pb.CheckAuthResponse{ + Code: 1, + Message: "auth fail " + token, + }, nil +} diff --git a/examples/run_rpc/run_rpcserver.go b/examples/run_rpc/run_rpcserver.go deleted file mode 100644 index ef44c10..0000000 --- a/examples/run_rpc/run_rpcserver.go +++ /dev/null @@ -1,28 +0,0 @@ -package main - -import ( - "fmt" - v1log "gitee.com/scottq/go-framework/src/v1/log" - v1rpc "gitee.com/scottq/go-framework/src/v1/rpcserver" - "google.golang.org/grpc" - "os" - "path/filepath" -) - -func main() { - name := "example" - logPath := fmt.Sprintf("./runtime/logs/%s.log", filepath.Base(os.Args[0])) - - logger := v1log.NewZapLog(name, logPath, nil) - httpServer, err := v1rpc.NewGRPCServer("", ":40001", func(server *grpc.Server) { - - }) - if err != nil { - logger.Error("run http server error:%s" + err.Error()) - return - } - //添加logger - httpServer.AddLogger(logger) - - httpServer.Run() -} diff --git a/go.mod b/go.mod index ada7d6a..3e5686a 100644 --- a/go.mod +++ b/go.mod @@ -12,6 +12,7 @@ require ( go.uber.org/zap v1.17.0 golang.org/x/time v0.0.0-20210723032227-1f47c861a9ac google.golang.org/grpc v1.40.0 + google.golang.org/protobuf v1.26.0 gopkg.in/natefinch/lumberjack.v2 v2.0.0 // indirect gopkg.in/yaml.v2 v2.3.0 gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b diff --git a/grpcProtos/pb/demoReq.pb.go b/grpcProtos/pb/demoReq.pb.go new file mode 100644 index 0000000..fc0235f --- /dev/null +++ b/grpcProtos/pb/demoReq.pb.go @@ -0,0 +1,397 @@ +// Copyright 2015 gRPC 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. + +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.26.0 +// protoc v3.15.8 +// source: demoReq.proto + +package pb + +import ( + pb_structs "gitee.com/scottq/go-framework/grpcProtos/pb/pb_structs" + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +type CheckAuthRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Token string `protobuf:"bytes,1,opt,name=token,proto3" json:"token,omitempty"` +} + +func (x *CheckAuthRequest) Reset() { + *x = CheckAuthRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_demoReq_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *CheckAuthRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*CheckAuthRequest) ProtoMessage() {} + +func (x *CheckAuthRequest) ProtoReflect() protoreflect.Message { + mi := &file_demoReq_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use CheckAuthRequest.ProtoReflect.Descriptor instead. +func (*CheckAuthRequest) Descriptor() ([]byte, []int) { + return file_demoReq_proto_rawDescGZIP(), []int{0} +} + +func (x *CheckAuthRequest) GetToken() string { + if x != nil { + return x.Token + } + return "" +} + +type CheckAuthResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Code int64 `protobuf:"varint,1,opt,name=code,proto3" json:"code,omitempty"` + Message string `protobuf:"bytes,2,opt,name=message,proto3" json:"message,omitempty"` + User *pb_structs.User `protobuf:"bytes,3,opt,name=user,proto3" json:"user,omitempty"` +} + +func (x *CheckAuthResponse) Reset() { + *x = CheckAuthResponse{} + if protoimpl.UnsafeEnabled { + mi := &file_demoReq_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *CheckAuthResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*CheckAuthResponse) ProtoMessage() {} + +func (x *CheckAuthResponse) ProtoReflect() protoreflect.Message { + mi := &file_demoReq_proto_msgTypes[1] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use CheckAuthResponse.ProtoReflect.Descriptor instead. +func (*CheckAuthResponse) Descriptor() ([]byte, []int) { + return file_demoReq_proto_rawDescGZIP(), []int{1} +} + +func (x *CheckAuthResponse) GetCode() int64 { + if x != nil { + return x.Code + } + return 0 +} + +func (x *CheckAuthResponse) GetMessage() string { + if x != nil { + return x.Message + } + return "" +} + +func (x *CheckAuthResponse) GetUser() *pb_structs.User { + if x != nil { + return x.User + } + return nil +} + +type AddLogRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Token string `protobuf:"bytes,1,opt,name=token,proto3" json:"token,omitempty"` + Log string `protobuf:"bytes,2,opt,name=log,proto3" json:"log,omitempty"` +} + +func (x *AddLogRequest) Reset() { + *x = AddLogRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_demoReq_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *AddLogRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*AddLogRequest) ProtoMessage() {} + +func (x *AddLogRequest) ProtoReflect() protoreflect.Message { + mi := &file_demoReq_proto_msgTypes[2] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use AddLogRequest.ProtoReflect.Descriptor instead. +func (*AddLogRequest) Descriptor() ([]byte, []int) { + return file_demoReq_proto_rawDescGZIP(), []int{2} +} + +func (x *AddLogRequest) GetToken() string { + if x != nil { + return x.Token + } + return "" +} + +func (x *AddLogRequest) GetLog() string { + if x != nil { + return x.Log + } + return "" +} + +type AddLogResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Code int64 `protobuf:"varint,1,opt,name=code,proto3" json:"code,omitempty"` + Message string `protobuf:"bytes,2,opt,name=message,proto3" json:"message,omitempty"` +} + +func (x *AddLogResponse) Reset() { + *x = AddLogResponse{} + if protoimpl.UnsafeEnabled { + mi := &file_demoReq_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *AddLogResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*AddLogResponse) ProtoMessage() {} + +func (x *AddLogResponse) ProtoReflect() protoreflect.Message { + mi := &file_demoReq_proto_msgTypes[3] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use AddLogResponse.ProtoReflect.Descriptor instead. +func (*AddLogResponse) Descriptor() ([]byte, []int) { + return file_demoReq_proto_rawDescGZIP(), []int{3} +} + +func (x *AddLogResponse) GetCode() int64 { + if x != nil { + return x.Code + } + return 0 +} + +func (x *AddLogResponse) GetMessage() string { + if x != nil { + return x.Message + } + return "" +} + +var File_demoReq_proto protoreflect.FileDescriptor + +var file_demoReq_proto_rawDesc = []byte{ + 0x0a, 0x0d, 0x64, 0x65, 0x6d, 0x6f, 0x52, 0x65, 0x71, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, + 0x02, 0x70, 0x62, 0x1a, 0x15, 0x70, 0x62, 0x5f, 0x73, 0x74, 0x72, 0x75, 0x63, 0x74, 0x73, 0x2f, + 0x64, 0x65, 0x6d, 0x6f, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x28, 0x0a, 0x10, 0x43, 0x68, + 0x65, 0x63, 0x6b, 0x41, 0x75, 0x74, 0x68, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x14, + 0x0a, 0x05, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x74, + 0x6f, 0x6b, 0x65, 0x6e, 0x22, 0x67, 0x0a, 0x11, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x41, 0x75, 0x74, + 0x68, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x12, 0x0a, 0x04, 0x63, 0x6f, 0x64, + 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x04, 0x63, 0x6f, 0x64, 0x65, 0x12, 0x18, 0x0a, + 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, + 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x12, 0x24, 0x0a, 0x04, 0x75, 0x73, 0x65, 0x72, 0x18, + 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x10, 0x2e, 0x70, 0x62, 0x5f, 0x73, 0x74, 0x72, 0x75, 0x63, + 0x74, 0x73, 0x2e, 0x55, 0x73, 0x65, 0x72, 0x52, 0x04, 0x75, 0x73, 0x65, 0x72, 0x22, 0x37, 0x0a, + 0x0d, 0x41, 0x64, 0x64, 0x4c, 0x6f, 0x67, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x14, + 0x0a, 0x05, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x74, + 0x6f, 0x6b, 0x65, 0x6e, 0x12, 0x10, 0x0a, 0x03, 0x6c, 0x6f, 0x67, 0x18, 0x02, 0x20, 0x01, 0x28, + 0x09, 0x52, 0x03, 0x6c, 0x6f, 0x67, 0x22, 0x3e, 0x0a, 0x0e, 0x41, 0x64, 0x64, 0x4c, 0x6f, 0x67, + 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x12, 0x0a, 0x04, 0x63, 0x6f, 0x64, 0x65, + 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x04, 0x63, 0x6f, 0x64, 0x65, 0x12, 0x18, 0x0a, 0x07, + 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x6d, + 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x32, 0x77, 0x0a, 0x06, 0x55, 0x73, 0x65, 0x72, 0x53, 0x72, + 0x12, 0x3a, 0x0a, 0x09, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x41, 0x75, 0x74, 0x68, 0x12, 0x14, 0x2e, + 0x70, 0x62, 0x2e, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x41, 0x75, 0x74, 0x68, 0x52, 0x65, 0x71, 0x75, + 0x65, 0x73, 0x74, 0x1a, 0x15, 0x2e, 0x70, 0x62, 0x2e, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x41, 0x75, + 0x74, 0x68, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x12, 0x31, 0x0a, 0x06, + 0x41, 0x64, 0x64, 0x4c, 0x6f, 0x67, 0x12, 0x11, 0x2e, 0x70, 0x62, 0x2e, 0x41, 0x64, 0x64, 0x4c, + 0x6f, 0x67, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x12, 0x2e, 0x70, 0x62, 0x2e, 0x41, + 0x64, 0x64, 0x4c, 0x6f, 0x67, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x42, + 0x05, 0x5a, 0x03, 0x2f, 0x70, 0x62, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, +} + +var ( + file_demoReq_proto_rawDescOnce sync.Once + file_demoReq_proto_rawDescData = file_demoReq_proto_rawDesc +) + +func file_demoReq_proto_rawDescGZIP() []byte { + file_demoReq_proto_rawDescOnce.Do(func() { + file_demoReq_proto_rawDescData = protoimpl.X.CompressGZIP(file_demoReq_proto_rawDescData) + }) + return file_demoReq_proto_rawDescData +} + +var file_demoReq_proto_msgTypes = make([]protoimpl.MessageInfo, 4) +var file_demoReq_proto_goTypes = []interface{}{ + (*CheckAuthRequest)(nil), // 0: pb.CheckAuthRequest + (*CheckAuthResponse)(nil), // 1: pb.CheckAuthResponse + (*AddLogRequest)(nil), // 2: pb.AddLogRequest + (*AddLogResponse)(nil), // 3: pb.AddLogResponse + (*pb_structs.User)(nil), // 4: pb_structs.User +} +var file_demoReq_proto_depIdxs = []int32{ + 4, // 0: pb.CheckAuthResponse.user:type_name -> pb_structs.User + 0, // 1: pb.UserSr.CheckAuth:input_type -> pb.CheckAuthRequest + 2, // 2: pb.UserSr.AddLog:input_type -> pb.AddLogRequest + 1, // 3: pb.UserSr.CheckAuth:output_type -> pb.CheckAuthResponse + 3, // 4: pb.UserSr.AddLog:output_type -> pb.AddLogResponse + 3, // [3:5] is the sub-list for method output_type + 1, // [1:3] is the sub-list for method input_type + 1, // [1:1] is the sub-list for extension type_name + 1, // [1:1] is the sub-list for extension extendee + 0, // [0:1] is the sub-list for field type_name +} + +func init() { file_demoReq_proto_init() } +func file_demoReq_proto_init() { + if File_demoReq_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_demoReq_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*CheckAuthRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_demoReq_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*CheckAuthResponse); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_demoReq_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*AddLogRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_demoReq_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*AddLogResponse); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_demoReq_proto_rawDesc, + NumEnums: 0, + NumMessages: 4, + NumExtensions: 0, + NumServices: 1, + }, + GoTypes: file_demoReq_proto_goTypes, + DependencyIndexes: file_demoReq_proto_depIdxs, + MessageInfos: file_demoReq_proto_msgTypes, + }.Build() + File_demoReq_proto = out.File + file_demoReq_proto_rawDesc = nil + file_demoReq_proto_goTypes = nil + file_demoReq_proto_depIdxs = nil +} diff --git a/grpcProtos/pb/demoReq_grpc.pb.go b/grpcProtos/pb/demoReq_grpc.pb.go new file mode 100644 index 0000000..547a45b --- /dev/null +++ b/grpcProtos/pb/demoReq_grpc.pb.go @@ -0,0 +1,139 @@ +// Code generated by protoc-gen-go-grpc. DO NOT EDIT. + +package pb + +import ( + context "context" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" +) + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +// Requires gRPC-Go v1.32.0 or later. +const _ = grpc.SupportPackageIsVersion7 + +// UserSrClient is the client API for UserSr service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. +type UserSrClient interface { + // Sends a greeting + CheckAuth(ctx context.Context, in *CheckAuthRequest, opts ...grpc.CallOption) (*CheckAuthResponse, error) + AddLog(ctx context.Context, in *AddLogRequest, opts ...grpc.CallOption) (*AddLogResponse, error) +} + +type userSrClient struct { + cc grpc.ClientConnInterface +} + +func NewUserSrClient(cc grpc.ClientConnInterface) UserSrClient { + return &userSrClient{cc} +} + +func (c *userSrClient) CheckAuth(ctx context.Context, in *CheckAuthRequest, opts ...grpc.CallOption) (*CheckAuthResponse, error) { + out := new(CheckAuthResponse) + err := c.cc.Invoke(ctx, "/pb.UserSr/CheckAuth", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *userSrClient) AddLog(ctx context.Context, in *AddLogRequest, opts ...grpc.CallOption) (*AddLogResponse, error) { + out := new(AddLogResponse) + err := c.cc.Invoke(ctx, "/pb.UserSr/AddLog", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +// UserSrServer is the server API for UserSr service. +// All implementations must embed UnimplementedUserSrServer +// for forward compatibility +type UserSrServer interface { + // Sends a greeting + CheckAuth(context.Context, *CheckAuthRequest) (*CheckAuthResponse, error) + AddLog(context.Context, *AddLogRequest) (*AddLogResponse, error) + mustEmbedUnimplementedUserSrServer() +} + +// UnimplementedUserSrServer must be embedded to have forward compatible implementations. +type UnimplementedUserSrServer struct { +} + +func (UnimplementedUserSrServer) CheckAuth(context.Context, *CheckAuthRequest) (*CheckAuthResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method CheckAuth not implemented") +} +func (UnimplementedUserSrServer) AddLog(context.Context, *AddLogRequest) (*AddLogResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method AddLog not implemented") +} +func (UnimplementedUserSrServer) mustEmbedUnimplementedUserSrServer() {} + +// UnsafeUserSrServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to UserSrServer will +// result in compilation errors. +type UnsafeUserSrServer interface { + mustEmbedUnimplementedUserSrServer() +} + +func RegisterUserSrServer(s grpc.ServiceRegistrar, srv UserSrServer) { + s.RegisterService(&UserSr_ServiceDesc, srv) +} + +func _UserSr_CheckAuth_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(CheckAuthRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(UserSrServer).CheckAuth(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/pb.UserSr/CheckAuth", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(UserSrServer).CheckAuth(ctx, req.(*CheckAuthRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _UserSr_AddLog_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(AddLogRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(UserSrServer).AddLog(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/pb.UserSr/AddLog", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(UserSrServer).AddLog(ctx, req.(*AddLogRequest)) + } + return interceptor(ctx, in, info, handler) +} + +// UserSr_ServiceDesc is the grpc.ServiceDesc for UserSr service. +// It's only intended for direct use with grpc.RegisterService, +// and not to be introspected or modified (even as a copy) +var UserSr_ServiceDesc = grpc.ServiceDesc{ + ServiceName: "pb.UserSr", + HandlerType: (*UserSrServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "CheckAuth", + Handler: _UserSr_CheckAuth_Handler, + }, + { + MethodName: "AddLog", + Handler: _UserSr_AddLog_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "demoReq.proto", +} diff --git a/grpcProtos/pb/pb_structs/demo.pb.go b/grpcProtos/pb/pb_structs/demo.pb.go new file mode 100644 index 0000000..5782c8c --- /dev/null +++ b/grpcProtos/pb/pb_structs/demo.pb.go @@ -0,0 +1,176 @@ +// Copyright 2015 gRPC 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. + +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.26.0 +// protoc v3.15.8 +// source: demo.proto + +package pb_structs + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +// The response message containing the greetings +type User struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Nickanme string `protobuf:"bytes,1,opt,name=nickanme,proto3" json:"nickanme,omitempty"` + Account string `protobuf:"bytes,2,opt,name=account,proto3" json:"account,omitempty"` + Uid int64 `protobuf:"varint,3,opt,name=uid,proto3" json:"uid,omitempty"` +} + +func (x *User) Reset() { + *x = User{} + if protoimpl.UnsafeEnabled { + mi := &file_demo_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *User) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*User) ProtoMessage() {} + +func (x *User) ProtoReflect() protoreflect.Message { + mi := &file_demo_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use User.ProtoReflect.Descriptor instead. +func (*User) Descriptor() ([]byte, []int) { + return file_demo_proto_rawDescGZIP(), []int{0} +} + +func (x *User) GetNickanme() string { + if x != nil { + return x.Nickanme + } + return "" +} + +func (x *User) GetAccount() string { + if x != nil { + return x.Account + } + return "" +} + +func (x *User) GetUid() int64 { + if x != nil { + return x.Uid + } + return 0 +} + +var File_demo_proto protoreflect.FileDescriptor + +var file_demo_proto_rawDesc = []byte{ + 0x0a, 0x0a, 0x64, 0x65, 0x6d, 0x6f, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x0a, 0x70, 0x62, + 0x5f, 0x73, 0x74, 0x72, 0x75, 0x63, 0x74, 0x73, 0x22, 0x4e, 0x0a, 0x04, 0x55, 0x73, 0x65, 0x72, + 0x12, 0x1a, 0x0a, 0x08, 0x6e, 0x69, 0x63, 0x6b, 0x61, 0x6e, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, + 0x28, 0x09, 0x52, 0x08, 0x6e, 0x69, 0x63, 0x6b, 0x61, 0x6e, 0x6d, 0x65, 0x12, 0x18, 0x0a, 0x07, + 0x61, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x61, + 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x10, 0x0a, 0x03, 0x75, 0x69, 0x64, 0x18, 0x03, 0x20, + 0x01, 0x28, 0x03, 0x52, 0x03, 0x75, 0x69, 0x64, 0x42, 0x0f, 0x5a, 0x0d, 0x70, 0x62, 0x2f, 0x70, + 0x62, 0x5f, 0x73, 0x74, 0x72, 0x75, 0x63, 0x74, 0x73, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, + 0x33, +} + +var ( + file_demo_proto_rawDescOnce sync.Once + file_demo_proto_rawDescData = file_demo_proto_rawDesc +) + +func file_demo_proto_rawDescGZIP() []byte { + file_demo_proto_rawDescOnce.Do(func() { + file_demo_proto_rawDescData = protoimpl.X.CompressGZIP(file_demo_proto_rawDescData) + }) + return file_demo_proto_rawDescData +} + +var file_demo_proto_msgTypes = make([]protoimpl.MessageInfo, 1) +var file_demo_proto_goTypes = []interface{}{ + (*User)(nil), // 0: pb_structs.User +} +var file_demo_proto_depIdxs = []int32{ + 0, // [0:0] is the sub-list for method output_type + 0, // [0:0] is the sub-list for method input_type + 0, // [0:0] is the sub-list for extension type_name + 0, // [0:0] is the sub-list for extension extendee + 0, // [0:0] is the sub-list for field type_name +} + +func init() { file_demo_proto_init() } +func file_demo_proto_init() { + if File_demo_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_demo_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*User); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_demo_proto_rawDesc, + NumEnums: 0, + NumMessages: 1, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_demo_proto_goTypes, + DependencyIndexes: file_demo_proto_depIdxs, + MessageInfos: file_demo_proto_msgTypes, + }.Build() + File_demo_proto = out.File + file_demo_proto_rawDesc = nil + file_demo_proto_goTypes = nil + file_demo_proto_depIdxs = nil +} diff --git a/grpcProtos/pb/pb_structs/req_resp.pb.go b/grpcProtos/pb/pb_structs/req_resp.pb.go new file mode 100644 index 0000000..ff83994 --- /dev/null +++ b/grpcProtos/pb/pb_structs/req_resp.pb.go @@ -0,0 +1,238 @@ +// Copyright 2015 gRPC 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. + +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.26.0 +// protoc v3.15.8 +// source: req_resp.proto + +package pb_structs + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +// The response message containing the greetings +type ReqStc struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + RequestId string `protobuf:"bytes,1,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` +} + +func (x *ReqStc) Reset() { + *x = ReqStc{} + if protoimpl.UnsafeEnabled { + mi := &file_req_resp_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *ReqStc) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ReqStc) ProtoMessage() {} + +func (x *ReqStc) ProtoReflect() protoreflect.Message { + mi := &file_req_resp_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ReqStc.ProtoReflect.Descriptor instead. +func (*ReqStc) Descriptor() ([]byte, []int) { + return file_req_resp_proto_rawDescGZIP(), []int{0} +} + +func (x *ReqStc) GetRequestId() string { + if x != nil { + return x.RequestId + } + return "" +} + +type RespStc struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Code int64 `protobuf:"varint,1,opt,name=code,proto3" json:"code,omitempty"` + Message string `protobuf:"bytes,2,opt,name=message,proto3" json:"message,omitempty"` + Data string `protobuf:"bytes,3,opt,name=data,proto3" json:"data,omitempty"` +} + +func (x *RespStc) Reset() { + *x = RespStc{} + if protoimpl.UnsafeEnabled { + mi := &file_req_resp_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *RespStc) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*RespStc) ProtoMessage() {} + +func (x *RespStc) ProtoReflect() protoreflect.Message { + mi := &file_req_resp_proto_msgTypes[1] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use RespStc.ProtoReflect.Descriptor instead. +func (*RespStc) Descriptor() ([]byte, []int) { + return file_req_resp_proto_rawDescGZIP(), []int{1} +} + +func (x *RespStc) GetCode() int64 { + if x != nil { + return x.Code + } + return 0 +} + +func (x *RespStc) GetMessage() string { + if x != nil { + return x.Message + } + return "" +} + +func (x *RespStc) GetData() string { + if x != nil { + return x.Data + } + return "" +} + +var File_req_resp_proto protoreflect.FileDescriptor + +var file_req_resp_proto_rawDesc = []byte{ + 0x0a, 0x0e, 0x72, 0x65, 0x71, 0x5f, 0x72, 0x65, 0x73, 0x70, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, + 0x12, 0x0a, 0x70, 0x62, 0x5f, 0x73, 0x74, 0x72, 0x75, 0x63, 0x74, 0x73, 0x22, 0x27, 0x0a, 0x06, + 0x52, 0x65, 0x71, 0x53, 0x74, 0x63, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, + 0x74, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x72, 0x65, 0x71, 0x75, + 0x65, 0x73, 0x74, 0x49, 0x64, 0x22, 0x4b, 0x0a, 0x07, 0x52, 0x65, 0x73, 0x70, 0x53, 0x74, 0x63, + 0x12, 0x12, 0x0a, 0x04, 0x63, 0x6f, 0x64, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x04, + 0x63, 0x6f, 0x64, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, + 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x12, 0x12, + 0x0a, 0x04, 0x64, 0x61, 0x74, 0x61, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x64, 0x61, + 0x74, 0x61, 0x42, 0x0f, 0x5a, 0x0d, 0x70, 0x62, 0x2f, 0x70, 0x62, 0x5f, 0x73, 0x74, 0x72, 0x75, + 0x63, 0x74, 0x73, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, +} + +var ( + file_req_resp_proto_rawDescOnce sync.Once + file_req_resp_proto_rawDescData = file_req_resp_proto_rawDesc +) + +func file_req_resp_proto_rawDescGZIP() []byte { + file_req_resp_proto_rawDescOnce.Do(func() { + file_req_resp_proto_rawDescData = protoimpl.X.CompressGZIP(file_req_resp_proto_rawDescData) + }) + return file_req_resp_proto_rawDescData +} + +var file_req_resp_proto_msgTypes = make([]protoimpl.MessageInfo, 2) +var file_req_resp_proto_goTypes = []interface{}{ + (*ReqStc)(nil), // 0: pb_structs.ReqStc + (*RespStc)(nil), // 1: pb_structs.RespStc +} +var file_req_resp_proto_depIdxs = []int32{ + 0, // [0:0] is the sub-list for method output_type + 0, // [0:0] is the sub-list for method input_type + 0, // [0:0] is the sub-list for extension type_name + 0, // [0:0] is the sub-list for extension extendee + 0, // [0:0] is the sub-list for field type_name +} + +func init() { file_req_resp_proto_init() } +func file_req_resp_proto_init() { + if File_req_resp_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_req_resp_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*ReqStc); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_req_resp_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*RespStc); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_req_resp_proto_rawDesc, + NumEnums: 0, + NumMessages: 2, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_req_resp_proto_goTypes, + DependencyIndexes: file_req_resp_proto_depIdxs, + MessageInfos: file_req_resp_proto_msgTypes, + }.Build() + File_req_resp_proto = out.File + file_req_resp_proto_rawDesc = nil + file_req_resp_proto_goTypes = nil + file_req_resp_proto_depIdxs = nil +} diff --git a/grpcProtos/protos/demoReq.proto b/grpcProtos/protos/demoReq.proto index c2fbb0a..95ea249 100644 --- a/grpcProtos/protos/demoReq.proto +++ b/grpcProtos/protos/demoReq.proto @@ -16,30 +16,31 @@ syntax = "proto3"; option go_package = "/pb"; import "pb_structs/demo.proto"; -import "pb_structs/req_resp.proto"; package pb; // The greeting service definition. service UserSr { // Sends a greeting - rpc CheckAuth (CheckAuthRequest) returns (pb_structs.RespStc) {} - rpc AddLog (AdminLogRequest) returns (AdminLogResponse) {} + rpc CheckAuth (CheckAuthRequest) returns (CheckAuthResponse) {} + rpc AddLog (AddLogRequest) returns (AddLogResponse) {} } message CheckAuthRequest{ - pb_structs.Authorization authorization = 1; - pb_structs.AdminLog admin_log = 2; + string token = 1; } message CheckAuthResponse{ - string message=1; + int64 code=1; + string message=2; + pb_structs.User user = 3; } message AddLogRequest{ - pb_structs.Authorization authorization = 1; - pb_structs.AdminLog admin_log = 2; + string token = 1; + string log = 2; } message AddLogResponse{ - string message=1; + int64 code=1; + string message=2; } \ No newline at end of file diff --git a/grpcProtos/protos/pb_structs/demo.proto b/grpcProtos/protos/pb_structs/demo.proto index bc26786..6b51089 100644 --- a/grpcProtos/protos/pb_structs/demo.proto +++ b/grpcProtos/protos/pb_structs/demo.proto @@ -21,5 +21,5 @@ package pb_structs; message User { string nickanme = 1; string account = 2; - int uid = 3; + int64 uid = 3; } \ No newline at end of file diff --git a/grpcProtos/protos/pb_structs/req_resp.proto b/grpcProtos/protos/pb_structs/req_resp.proto index 295a443..6a1e8b4 100644 --- a/grpcProtos/protos/pb_structs/req_resp.proto +++ b/grpcProtos/protos/pb_structs/req_resp.proto @@ -23,7 +23,7 @@ message ReqStc { } message RespStc { - string code = 1; + int64 code = 1; string message = 2; string data = 3; } \ No newline at end of file diff --git a/src/v1/comag/comag.go b/src/v1/comag/comag.go index e11da67..9326f1f 100644 --- a/src/v1/comag/comag.go +++ b/src/v1/comag/comag.go @@ -1,5 +1,10 @@ package comag +import ( + "fmt" + "golang.org/x/net/context" +) + type CoFunc func(context.Context) func debugPrint(msg string, params ...interface{}) { diff --git a/src/v1/comag/comag_failallfail.go b/src/v1/comag/comag_failallfail.go index bb27d64..88f3ed4 100644 --- a/src/v1/comag/comag_failallfail.go +++ b/src/v1/comag/comag_failallfail.go @@ -1,7 +1,9 @@ package comag -type CoFunc func(context.Context) - +import ( + "context" + "sync" +) //CoMag 一次失败全部失败 type FailAllFailCoMag struct { diff --git a/src/v1/comag/comag_test.go b/src/v1/comag/comag_test.go index 8d37af3..a0f132a 100644 --- a/src/v1/comag/comag_test.go +++ b/src/v1/comag/comag_test.go @@ -1,6 +1,13 @@ package comag -func TestCoMag(){ +import ( + "context" + "fmt" + "testing" + "time" +) + +func Test_CoMag(t *testing.T){ mg := NewFailAllFailCoMag() mg.Add(inputCo) diff --git a/src/v1/log/log.go b/src/v1/log/log.go index 110dcb5..4e9d851 100644 --- a/src/v1/log/log.go +++ b/src/v1/log/log.go @@ -74,8 +74,7 @@ func (ink *InvokeLog) Debug(log string, params ...interface{}) error { return nil } if len(params)<=0{ - returnink.logger.Debug(log) - return + return ink.logger.Debug(log) } return ink.logger.Debug(fmt.Sprintf(log, params...)) @@ -86,8 +85,7 @@ func (ink *InvokeLog) Info(log string, params ...interface{}) error { return nil } if len(params)<=0{ - returnink.logger.Info(log) - return + return ink.logger.Info(log) } return ink.logger.Info(fmt.Sprintf(log, params...)) @@ -98,8 +96,7 @@ func (ink *InvokeLog) Warn(log string, params ...interface{}) error { return nil } if len(params)<=0{ - returnink.logger.Warn(log) - return + return ink.logger.Warn(log) } return ink.logger.Warn(fmt.Sprintf(log, params...)) @@ -109,8 +106,7 @@ func (ink *InvokeLog) Error(log string, params ...interface{}) error { return nil } if len(params)<=0{ - returnink.logger.Error(log) - return + return ink.logger.Error(log) } return ink.logger.Error(fmt.Sprintf(log, params...)) @@ -121,8 +117,7 @@ func (ink *InvokeLog) Panic(log string, params ...interface{}) error { return nil } if len(params)<=0{ - returnink.logger.Panic(log) - return + return ink.logger.Panic(log) } return ink.logger.Panic(fmt.Sprintf(log, params...)) @@ -132,8 +127,7 @@ func (ink *InvokeLog) Fatal(log string, params ...interface{}) error { return nil } if len(params)<=0{ - returnink.logger.Fatal(log) - return + return ink.logger.Fatal(log) } return ink.logger.Fatal(fmt.Sprintf(log, params...)) diff --git a/src/v1/log/log_zap.go b/src/v1/log/log_zap.go index 27ceb84..a1dcdf4 100644 --- a/src/v1/log/log_zap.go +++ b/src/v1/log/log_zap.go @@ -83,43 +83,49 @@ func NewZapLog(name string, logPath string, config *ZapLogConfig) ILog { } func (l *DefaultZapLog) Debug(format string, params ...interface{}) error { - if len(params)<=0{ - return l.zapLog.Debug(format) + if len(params) <= 0 { + l.zapLog.Debug(format) + return nil } return l.Debug(fmt.Sprintf(format, params...)) } func (l *DefaultZapLog) Info(format string, params ...interface{}) error { - if len(params)<=0{ - return l.zapLog.Info(format) + if len(params) <= 0 { + l.zapLog.Info(format) + return nil } return l.Info(fmt.Sprintf(format, params...)) } func (l *DefaultZapLog) Warn(format string, params ...interface{}) error { - if len(params)<=0{ - return l.zapLog.Warn(format) + if len(params) <= 0 { + l.zapLog.Warn(format) + return nil } return l.Warn(fmt.Sprintf(format, params...)) } func (l *DefaultZapLog) Error(format string, params ...interface{}) error { - if len(params)<=0{ - return l.zapLog.Error(format) + if len(params) <= 0 { + l.zapLog.Error(format) + return nil } return l.Error(fmt.Sprintf(format, params...)) } func (l *DefaultZapLog) Fatal(format string, params ...interface{}) error { - if len(params)<=0{ - return l.zapLog.Fatal(format) + if len(params) <= 0 { + l.zapLog.Fatal(format) + return nil } return l.Fatal(fmt.Sprintf(format, params...)) } func (l *DefaultZapLog) Panic(format string, params ...interface{}) error { - if len(params)<=0{ - return l.zapLog.Panic(format) + if len(params) <= 0 { + l.zapLog.Panic(format) + return nil } return l.Panic(fmt.Sprintf(format, params...)) } -- Gitee From 48f131afd8aef8a69d76216edfc77bdbbaaf274c Mon Sep 17 00:00:00 2001 From: Sage <1010309281@qq.com> Date: Fri, 1 Oct 2021 09:42:02 +0800 Subject: [PATCH 11/12] =?UTF-8?q?=E4=BC=98=E5=8C=96=20lop=20interface?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- examples/run_grpc/client_grpc.go | 8 +-- src/v1/log/log.go | 100 +++++++++++++++++-------------- src/v1/log/log_default.go | 69 +++++++++++++-------- src/v1/log/log_zap.go | 42 +++++++------ 4 files changed, 125 insertions(+), 94 deletions(-) diff --git a/examples/run_grpc/client_grpc.go b/examples/run_grpc/client_grpc.go index 384ed24..6a9abd8 100644 --- a/examples/run_grpc/client_grpc.go +++ b/examples/run_grpc/client_grpc.go @@ -4,7 +4,7 @@ import ( "context" "fmt" "gitee.com/scottq/go-framework/grpcProtos/pb" - v1rpcclient "gitee.com/scottq/go-framework/src/v1/clients/grpc" + v1clientrpc "gitee.com/scottq/go-framework/src/v1/clients/grpc" v1log "gitee.com/scottq/go-framework/src/v1/log" "google.golang.org/grpc" "os" @@ -16,13 +16,13 @@ func main() { logPath := fmt.Sprintf("./runtime/logs/%s.log", filepath.Base(os.Args[0])) logger := v1log.NewZapLog("example", logPath, nil) - opts := []v1rpcclient.RemoteOption{} + opts := []v1clientrpc.RemoteOption{} if false { - opts = append(opts, v1rpcclient.OptEtcdDiscovery("admin", "127.0.0.1:2379")) + opts = append(opts, v1clientrpc.OptEtcdDiscovery("admin", "127.0.0.1:2379")) } - conn, err := v1rpcclient.NewRemoteConn("127.0.0.1:40001", opts..., ) + conn, err := v1clientrpc.NewRemoteConn("127.0.0.1:40001", opts..., ) if err != nil { logger.Error("new remote conn err:%s", err) return diff --git a/src/v1/log/log.go b/src/v1/log/log.go index 4e9d851..cc12780 100644 --- a/src/v1/log/log.go +++ b/src/v1/log/log.go @@ -27,12 +27,12 @@ var LogLevelMap = map[int]string{ const DefaultLogPath = "./runtime/logs/daily.log" type ILog interface { - Debug(log string, params ...interface{}) error - Info(log string, params ...interface{}) error - Warn(log string, params ...interface{}) error - Error(log string, params ...interface{}) error - Panic(log string, params ...interface{}) error - Fatal(log string, params ...interface{}) error + Debug(log string, params ...interface{}) + Info(log string, params ...interface{}) + Warn(log string, params ...interface{}) + Error(log string, params ...interface{}) + Panic(log string, params ...interface{}) + Fatal(log string, params ...interface{}) } //fast use log @@ -48,87 +48,95 @@ func (ink *InvokeLog) Log(level int8, msg string) { if ink.logger == nil { return } - var err error switch level { case DebugLog: - err = ink.logger.Debug(msg) + ink.logger.Debug(msg) case WarnLog: - err = ink.logger.Warn(msg) + ink.logger.Warn(msg) case InfoLog: - err = ink.logger.Info(msg) + ink.logger.Info(msg) case ErrorLog: - err = ink.logger.Error(msg) + ink.logger.Error(msg) case FatalLog: - err = ink.logger.Fatal(msg) + ink.logger.Fatal(msg) case PanicLog: - err = ink.logger.Panic(msg) + ink.logger.Panic(msg) } - if err != nil { - panic(err) - } } -func (ink *InvokeLog) Debug(log string, params ...interface{}) error { +func (ink *InvokeLog) Debug(log string, params ...interface{}) { if ink.logger == nil { - return nil + return } - if len(params)<=0{ - return ink.logger.Debug(log) + if len(params) <= 0 { + ink.logger.Debug(log) + return } - return ink.logger.Debug(fmt.Sprintf(log, params...)) + ink.logger.Debug(fmt.Sprintf(log, params...)) + return } -func (ink *InvokeLog) Info(log string, params ...interface{}) error { +func (ink *InvokeLog) Info(log string, params ...interface{}) { if ink.logger == nil { - return nil + return } - if len(params)<=0{ - return ink.logger.Info(log) + if len(params) <= 0 { + ink.logger.Info(log) + return } - return ink.logger.Info(fmt.Sprintf(log, params...)) + ink.logger.Info(fmt.Sprintf(log, params...)) + return } -func (ink *InvokeLog) Warn(log string, params ...interface{}) error { +func (ink *InvokeLog) Warn(log string, params ...interface{}) { if ink.logger == nil { - return nil + return } - if len(params)<=0{ - return ink.logger.Warn(log) + if len(params) <= 0 { + ink.logger.Warn(log) + return } - return ink.logger.Warn(fmt.Sprintf(log, params...)) + ink.logger.Warn(fmt.Sprintf(log, params...)) + return } -func (ink *InvokeLog) Error(log string, params ...interface{}) error { +func (ink *InvokeLog) Error(log string, params ...interface{}) { if ink.logger == nil { - return nil + return } - if len(params)<=0{ - return ink.logger.Error(log) + if len(params) <= 0 { + ink.logger.Error(log) + return } - return ink.logger.Error(fmt.Sprintf(log, params...)) + ink.logger.Error(fmt.Sprintf(log, params...)) + return } -func (ink *InvokeLog) Panic(log string, params ...interface{}) error { +func (ink *InvokeLog) Panic(log string, params ...interface{}) { if ink.logger == nil { - return nil + return } - if len(params)<=0{ - return ink.logger.Panic(log) + if len(params) <= 0 { + ink.logger.Panic(log) + return } - return ink.logger.Panic(fmt.Sprintf(log, params...)) + ink.logger.Panic(fmt.Sprintf(log, params...)) + return } -func (ink *InvokeLog) Fatal(log string, params ...interface{}) error { +func (ink *InvokeLog) Fatal(log string, params ...interface{}) { if ink.logger == nil { - return nil + return } - if len(params)<=0{ - return ink.logger.Fatal(log) + if len(params) <= 0 { + ink.logger.Fatal(log) + return } - return ink.logger.Fatal(fmt.Sprintf(log, params...)) + ink.logger.Fatal(fmt.Sprintf(log, params...)) + return } diff --git a/src/v1/log/log_default.go b/src/v1/log/log_default.go index af30c51..2c100e8 100644 --- a/src/v1/log/log_default.go +++ b/src/v1/log/log_default.go @@ -101,51 +101,68 @@ func (logger *MyLogger) LogPath() string { return fmt.Sprintf("%s-%s.log", p[:len(p)-len(".log")], t) } -func (logger *MyLogger) Debug(format string, params ...interface{}) error { - if len(params)<=0{ - return logger.logItem(DebugLog, format) +func (logger *MyLogger) Debug(format string, params ...interface{}) { + if len(params) <= 0 { + logger.logItem(DebugLog, format) + return } - return logger.Debug(fmt.Sprintf(format, params...)) + logger.Debug(fmt.Sprintf(format, params...)) + return } -func (logger *MyLogger) Info(format string, params ...interface{}) error { - if len(params)<=0{ - return logger.logItem(InfoLog, format) +func (logger *MyLogger) Info(format string, params ...interface{}) { + if len(params) <= 0 { + logger.logItem(InfoLog, format) + return } - return logger.Info(fmt.Sprintf(format, params...)) + logger.Info(fmt.Sprintf(format, params...)) + return } -func (logger *MyLogger) Warn(format string, params ...interface{}) error { - if len(params)<=0{ - return logger.logItem(WarnLog, format) +func (logger *MyLogger) Warn(format string, params ...interface{}) { + if len(params) <= 0 { + logger.logItem(WarnLog, format) + return } - return logger.Warn(fmt.Sprintf(format, params...)) + logger.Warn(fmt.Sprintf(format, params...)) + return } -func (logger *MyLogger) Error(format string, params ...interface{}) error { - if len(params)<=0{ - return logger.logItem(ErrorLog, format) +func (logger *MyLogger) Error(format string, params ...interface{}) { + if len(params) <= 0 { + logger.logItem(ErrorLog, format) + return } - return logger.Error(fmt.Sprintf(format, params...)) + logger.Error(fmt.Sprintf(format, params...)) + return } -func (logger *MyLogger) Fatal(format string, params ...interface{}) error { - if len(params)<=0{ - return logger.logItem(FatalLog, format) +func (logger *MyLogger) Fatal(format string, params ...interface{}) { + if len(params) <= 0 { + logger.logItem(FatalLog, format) + return } - return logger.Fatal(fmt.Sprintf(format, params...)) + logger.Fatal(fmt.Sprintf(format, params...)) + return } -func (logger *MyLogger) Panic(format string, params ...interface{}) error { - if len(params)<=0{ - return logger.logItem(PanicLog, format) +func (logger *MyLogger) Panic(format string, params ...interface{}) { + if len(params) <= 0 { + logger.logItem(PanicLog, format) + return } - return logger.Panic(fmt.Sprintf(format, params...)) + logger.Panic(fmt.Sprintf(format, params...)) + return } -func (logger *MyLogger) logItem(level int, s string) error { +func (logger *MyLogger) logItem(level int, s string) { sl := fmt.Sprintf("%s\n%d\n", s, level) - return logger.logger.Output(3, sl) + err := logger.logger.Output(3, sl) + if err != nil { + panic(err) + return + } + return } func (logger *MyLogger) logItemf(level int, format string, params ...interface{}) error { diff --git a/src/v1/log/log_zap.go b/src/v1/log/log_zap.go index a1dcdf4..bee8e50 100644 --- a/src/v1/log/log_zap.go +++ b/src/v1/log/log_zap.go @@ -82,50 +82,56 @@ func NewZapLog(name string, logPath string, config *ZapLogConfig) ILog { } } -func (l *DefaultZapLog) Debug(format string, params ...interface{}) error { +func (l *DefaultZapLog) Debug(format string, params ...interface{}) { if len(params) <= 0 { l.zapLog.Debug(format) - return nil + return } - return l.Debug(fmt.Sprintf(format, params...)) + l.Debug(fmt.Sprintf(format, params...)) + return } -func (l *DefaultZapLog) Info(format string, params ...interface{}) error { +func (l *DefaultZapLog) Info(format string, params ...interface{}) { if len(params) <= 0 { l.zapLog.Info(format) - return nil + return } - return l.Info(fmt.Sprintf(format, params...)) + l.Info(fmt.Sprintf(format, params...)) + return } -func (l *DefaultZapLog) Warn(format string, params ...interface{}) error { +func (l *DefaultZapLog) Warn(format string, params ...interface{}) { if len(params) <= 0 { l.zapLog.Warn(format) - return nil + return } - return l.Warn(fmt.Sprintf(format, params...)) + l.Warn(fmt.Sprintf(format, params...)) + return } -func (l *DefaultZapLog) Error(format string, params ...interface{}) error { +func (l *DefaultZapLog) Error(format string, params ...interface{}) { if len(params) <= 0 { l.zapLog.Error(format) - return nil + return } - return l.Error(fmt.Sprintf(format, params...)) + l.Error(fmt.Sprintf(format, params...)) + return } -func (l *DefaultZapLog) Fatal(format string, params ...interface{}) error { +func (l *DefaultZapLog) Fatal(format string, params ...interface{}) { if len(params) <= 0 { l.zapLog.Fatal(format) - return nil + return } - return l.Fatal(fmt.Sprintf(format, params...)) + l.Fatal(fmt.Sprintf(format, params...)) + return } -func (l *DefaultZapLog) Panic(format string, params ...interface{}) error { +func (l *DefaultZapLog) Panic(format string, params ...interface{}) { if len(params) <= 0 { l.zapLog.Panic(format) - return nil + return } - return l.Panic(fmt.Sprintf(format, params...)) + l.Panic(fmt.Sprintf(format, params...)) + return } -- Gitee From 73b4023e7a5198064980d17f490bc86c4ab0176b Mon Sep 17 00:00:00 2001 From: Sage <1010309281@qq.com> Date: Fri, 1 Oct 2021 09:45:42 +0800 Subject: [PATCH 12/12] =?UTF-8?q?=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- go.mod | 1 + src/v1/comag/comag.go | 34 ++++++++++++++++++++++++++++++ src/v1/comag/comag_test.go | 42 +++----------------------------------- 3 files changed, 38 insertions(+), 39 deletions(-) diff --git a/go.mod b/go.mod index 3e5686a..916aa18 100644 --- a/go.mod +++ b/go.mod @@ -10,6 +10,7 @@ require ( github.com/satori/go.uuid v1.2.0 go.etcd.io/etcd/client/v3 v3.5.0 go.uber.org/zap v1.17.0 + golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4 golang.org/x/time v0.0.0-20210723032227-1f47c861a9ac google.golang.org/grpc v1.40.0 google.golang.org/protobuf v1.26.0 diff --git a/src/v1/comag/comag.go b/src/v1/comag/comag.go index 9326f1f..f5de5b6 100644 --- a/src/v1/comag/comag.go +++ b/src/v1/comag/comag.go @@ -3,6 +3,7 @@ package comag import ( "fmt" "golang.org/x/net/context" + "time" ) type CoFunc func(context.Context) @@ -14,3 +15,36 @@ func debugPrint(msg string, params ...interface{}) { } fmt.Printf(msg+"\n", params...) } + +func DemoCoA(ctx context.Context) { + errCh := ctx.Value("error").(chan error) + + for i := 1; i <= 100; i++ { + select { + case <-ctx.Done(): + debugPrint("input Done by ctx: %s", ctx.Err()) + return + default: + if i > 10 { + errCh <- fmt.Errorf("input error") + return + } + debugPrint("input:%d", i) + time.Sleep(time.Second) + } + } +} + +func DemoCoB(ctx context.Context) { + for i := 1; i <= 100; i++ { + select { + case <-ctx.Done(): + debugPrint("out Done by ctx: %s", ctx.Err()) + return + default: + debugPrint("out:%d", i) + time.Sleep(time.Second) + } + } + debugPrint("out Done") +} diff --git a/src/v1/comag/comag_test.go b/src/v1/comag/comag_test.go index a0f132a..9112970 100644 --- a/src/v1/comag/comag_test.go +++ b/src/v1/comag/comag_test.go @@ -1,52 +1,16 @@ package comag import ( - "context" - "fmt" "testing" - "time" ) -func Test_CoMag(t *testing.T){ +func Test_FailAllFailCoMag(t *testing.T){ mg := NewFailAllFailCoMag() - mg.Add(inputCo) - mg.Add(outputCo) + mg.Add(DemoCoA) + mg.Add(DemoCoB) mg.Run() debugPrint("end") } - -func inputCo(ctx context.Context) { - errCh := ctx.Value("error").(chan error) - - for i := 1; i <= 100; i++ { - select { - case <-ctx.Done(): - debugPrint("input Done by ctx: %s", ctx.Err()) - return - default: - if i > 10 { - errCh <- fmt.Errorf("input error") - return - } - debugPrint("input:%d", i) - time.Sleep(time.Second) - } - } -} - -func outputCo(ctx context.Context) { - for i := 1; i <= 100; i++ { - select { - case <-ctx.Done(): - debugPrint("out Done by ctx: %s", ctx.Err()) - return - default: - debugPrint("out:%d", i) - time.Sleep(time.Second) - } - } - debugPrint("out Done") -} -- Gitee