broadcast 广播模式
最后更新于:2022-04-02 02:50:07
[TOC]
## 概述
## 实例
server.go
```
package main
import (
"context"
"flag"
"github.com/smallnest/rpcx/server"
)
var (
addr1 = flag.String("addr1", "localhost:8972", "server1 address")
addr2 = flag.String("addr2", "localhost:9981", "server2 address")
)
type Args struct {
A int
B int
}
type Reply struct {
C int
}
type Arith int
func (t *Arith) Mul(ctx context.Context, args *Args, reply *Reply) error {
reply.C = args.A * args.B * 100
return nil
}
func main() {
flag.Parse()
go createServer1(*addr1, "")
go createServer2(*addr2, "")
select {}
}
func createServer1(addr, meta string) {
s := server.NewServer()
s.RegisterName("Arith", new(Arith), meta)
s.Serve("tcp", addr)
}
func createServer2(addr, meta string) {
s := server.NewServer()
s.RegisterName("Arith", new(Arith), meta)
s.Serve("tcp", addr)
}
```
client.go
```
package main
import (
"context"
"flag"
"log"
"time"
"github.com/smallnest/rpcx/client"
)
var (
addr1 = flag.String("addr1", "tcp@localhost:8972", "server1 address")
addr2 = flag.String("addr2", "tcp@localhost:9981", "server2 address")
)
func main() {
type Args struct {
A int
B int
}
type Reply struct {
C int
}
flag.Parse()
d := client.NewMultipleServersDiscovery([]*client.KVPair{{Key: *addr1}, {Key: *addr2}})
xclient := client.NewXClient("Arith", client.Failover, client.RoundRobin, d, client.DefaultOption)
defer xclient.Close()
args := &Args{
A: 10,
B: 20,
}
for {
reply := &Reply{}
err := xclient.Broadcast(context.Background(), "Mul", args, reply)
if err != nil {
log.Fatalf("failed to call: %v", err)
}
log.Printf("%d * %d = %d", args.A, args.B, reply.C)
time.Sleep(1e9)
}
}
```
';