官方文档:
client:
```golang
package main
import (
_ "context"
"flag"
"fmt"
"os"
"strconv"
"sync"
"time"
_ "github.com/micro/examples/plugins/transport/grpc/proto"
"github.com/micro/go-micro"
"github.com/micro/go-micro/transport"
"github.com/micro/go-plugins/transport/grpc"
)
var GW sync.WaitGroup
var Scount int
func main() {
fmt.Println(os.Args[1:])
fmt.Println(flag.Arg(1))
fmt.Println("Entry Micro Server count:", os.Args[1])
t1 := time.Now()
count := os.Args[1]
loops, _ := strconv.Atoi(os.Args[2])
int1, _ := strconv.Atoi(count)
GW.Add(int1)
Scount = int1 * loops
for i := 0; i < int1; i++ {
go GoroutineFunc(loops)
}
GW.Wait()
elapsed := time.Since(t1)
fmt.Println("Total count:", int1*loops)
fmt.Println("Success count:", Scount)
fmt.Println("Cysle TPS:", float64(int1*loops)/elapsed.Seconds())
fmt.Println("Taken Time(s) :", elapsed)
fmt.Println("Average Latency time(ms):", elapsed.Seconds()*1000/(float64(int1*loops)))
}
func GoroutineFunc(loops int) {
service := micro.NewService()
service.Init()
tr := grpc.NewTransport()
c, err := tr.Dial("192.168.2.50:8888")
if err != nil {
fmt.Println("Unexpected dial err: %v", err)
}
defer c.Close()
m := transport.Message{
Header: map[string]string{
"X-Content-Type": "application/json",
},
Body: []byte(`{"message": "Hello World"}`),
}
for i := 0; i < loops; i++ {
if err := c.Send(&m); err != nil {
fmt.Println("Unexpected send err: %v", err)
}
var rm transport.Message
if err := c.Recv(&rm); err != nil {
fmt.Println("Unexpected recv err: %v", err)
}
}
fmt.Println("string(rm.Body):", string(rm.Body))
GW.Done()
return
}
```
server:
```golang
package main
import (
"log"
"time"
context "context"
proto "github.com/micro/examples/plugins/transport/grpc/proto"
"github.com/micro/go-micro"
server "github.com/micro/go-micro/server"
"github.com/micro/go-micro/transport"
"github.com/micro/go-plugins/transport/grpc" // 协议 grpc
)
type Say struct{}
func (s *Say) Stream(ctx context.Context, stream server.Stream) error {
return nil
}
func main() {
service := micro.NewService(
micro.Name("go.micro.srv.greeter"),
micro.RegisterTTL(time.Second*30),
micro.RegisterInterval(time.Second*10),
)
service.Init()
tr := grpc.NewTransport()
l, err := tr.Listen(":8888")
if err != nil {
log.Fatal("Unexpected listen err: %v", err)
}
defer l.Close()
fn := func(sock transport.Socket) {
defer sock.Close()
for {
var m transport.Message
if err := sock.Recv(&m); err != nil {
return
}
if err := sock.Send(&m); err != nil {
return
}
}
}
done := make(chan bool)
go func() {
if err := l.Accept(fn); err != nil {
select {
case <-done:
default:
log.Fatal("Unexpected accept err: %v", err)
}
}
}()
// Run server
if err := service.Run(); err != nil {
log.Fatal(err)
}
return
}
```
测试性能截图:
有疑问加站长微信联系(非本文作者)