Skip to content

Commit 772ba32

Browse files
committed
add concurrent access example
1 parent 2364f94 commit 772ba32

File tree

3 files changed

+118
-0
lines changed

3 files changed

+118
-0
lines changed

examples/golang/example1/httpclient

-7.63 MB
Binary file not shown.
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
package main
2+
3+
import (
4+
"bytes"
5+
"io/ioutil"
6+
"log"
7+
"math/rand"
8+
"net/http"
9+
"strconv"
10+
"sync"
11+
12+
gateway "github.com/rpcx-ecosystem/rpcx-gateway"
13+
14+
"github.com/smallnest/rpcx/codec"
15+
)
16+
17+
type Args struct {
18+
A int
19+
B int
20+
}
21+
22+
type Reply struct {
23+
C int
24+
}
25+
26+
func main() {
27+
cc := &codec.MsgpackCodec{}
28+
29+
args := &Args{
30+
A: 10,
31+
B: 20,
32+
}
33+
34+
data, _ := cc.Encode(args)
35+
36+
var wg sync.WaitGroup
37+
wg.Add(2)
38+
39+
for i := 0; i < 2; i++ {
40+
i := i
41+
42+
go func() {
43+
defer wg.Done()
44+
45+
for j := 0; j < 10; j++ {
46+
req, err := http.NewRequest("POST", "http://127.0.0.1:9981/", bytes.NewReader(data))
47+
if err != nil {
48+
log.Fatal("failed to create request: ", err)
49+
return
50+
}
51+
52+
h := req.Header
53+
h.Set(gateway.XMessageID, strconv.Itoa(rand.Int()))
54+
h.Set(gateway.XMessageType, "0")
55+
h.Set(gateway.XSerializeType, "3")
56+
h.Set(gateway.XServicePath, "Arith")
57+
h.Set(gateway.XServiceMethod, "Mul")
58+
59+
res, err := http.DefaultClient.Do(req)
60+
if err != nil {
61+
log.Fatal("#%d failed to call: ", i, err)
62+
}
63+
defer res.Body.Close()
64+
65+
// handle http response
66+
replyData, err := ioutil.ReadAll(res.Body)
67+
if err != nil {
68+
log.Fatal("#%d failed to read response: ", i, err)
69+
}
70+
71+
reply := &Reply{}
72+
err = cc.Decode(replyData, reply)
73+
if err != nil {
74+
log.Fatal("#%d failed to decode reply: ", i, err)
75+
}
76+
77+
log.Printf("#%d: %d * %d = %d", i, args.A, args.B, reply.C)
78+
}
79+
}()
80+
}
81+
82+
wg.Wait()
83+
}

examples/server/server.go

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package main
2+
3+
import (
4+
"context"
5+
"flag"
6+
"fmt"
7+
8+
example "github.com/rpcx-ecosystem/rpcx-examples3"
9+
"github.com/smallnest/rpcx/server"
10+
)
11+
12+
var (
13+
addr = flag.String("addr", "localhost:8972", "server address")
14+
)
15+
16+
type Arith struct{}
17+
18+
// the second parameter is not a pointer
19+
func (t *Arith) Mul(ctx context.Context, args example.Args, reply *example.Reply) error {
20+
reply.C = args.A * args.B
21+
fmt.Println("C=", reply.C)
22+
return nil
23+
}
24+
25+
func main() {
26+
flag.Parse()
27+
28+
s := server.NewServer()
29+
//s.Register(new(Arith), "")
30+
s.RegisterName("Arith", new(Arith), "")
31+
err := s.Serve("tcp", *addr)
32+
if err != nil {
33+
panic(err)
34+
}
35+
}

0 commit comments

Comments
 (0)