├── .gitignore
├── .idea
├── .gitignore
├── inspectionProfiles
│ └── Project_Default.xml
├── misc.xml
├── modules.xml
├── vcs.xml
└── workspace.xml
├── README.md
├── go.mod
├── go.sum
├── grpc-demo.iml
├── img
├── .DS_Store
├── book.png
├── book_douban.png
└── wechat.png
├── load_balance_demo
├── Echo.pb.go
├── Echo.proto
├── client
│ └── main.go
└── server
│ └── main.go
├── order
├── OrderInfo.pb.go
├── OrderInfo.proto
├── client
│ └── main.go
└── server
│ └── main.go
├── order_advance_1
├── OrderInfo.pb.go
├── OrderInfo.proto
├── client
│ ├── interceptor.go
│ └── main.go
└── server
│ ├── interceptor.go
│ └── main.go
├── order_advance_2
├── Echo.pb.go
├── Echo.proto
├── OrderInfo.pb.go
├── OrderInfo.proto
├── client
│ └── main.go
└── server
│ ├── echo.go
│ ├── greeter.go
│ ├── main.go
│ └── order.go
├── product
├── ProductInfo.pb.go
├── ProductInfo.proto
├── client
│ └── main.go
└── server
│ └── main.go
└── secure-demo
├── ProductInfo.pb.go
├── ProductInfo.proto
├── certs
├── ca.crt
├── client.crt
├── client.key
├── server.crt
├── server.key
└── server.pem
├── client
└── main.go
└── server
└── main.go
/.gitignore:
--------------------------------------------------------------------------------
1 | ./.idea
2 | ./grpc-demo.iml
3 |
--------------------------------------------------------------------------------
/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 | # Datasource local storage ignored files
5 | /dataSources/
6 | /dataSources.local.xml
7 | # Editor-based HTTP Client requests
8 | /httpRequests/
9 |
--------------------------------------------------------------------------------
/.idea/inspectionProfiles/Project_Default.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/workspace.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 |
110 |
111 |
112 |
113 |
114 |
115 |
116 |
117 |
118 |
119 |
120 |
121 | 1616598967245
122 |
123 |
124 | 1616598967245
125 |
126 |
127 |
128 |
129 | 1616689449393
130 |
131 |
132 |
133 | 1616689449393
134 |
135 |
136 |
137 |
138 |
139 |
140 |
141 |
142 |
143 |
150 |
151 |
152 |
153 |
154 |
155 |
156 |
157 |
158 | true
159 |
160 |
163 |
164 |
165 |
166 |
167 |
168 |
169 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # grpc-demo
2 |
3 | 本项目是学习 gRPC 的一些代码示例。
4 |
5 | 以下是我写的几篇基础入门的文章,根据文章中的来,简单了解 gRPC 并且上手开发是没有任何问题的,希望对你有所帮助:
6 |
7 | [最简单的 gRPC 教程—1 初识 gRPC](https://zhuanlan.zhihu.com/p/359968500)
8 |
9 | [最简单的 gRPC 教程—2 通信模式](https://zhuanlan.zhihu.com/p/360355222)
10 |
11 | [最简单的 gRPC 教程—3 拦截器、截止、取消](https://zhuanlan.zhihu.com/p/361913816)
12 |
13 | [最简单的 gRPC 教程—4 多路复用、元数据、负载均衡](https://zhuanlan.zhihu.com/p/364325400)
14 |
15 | 后续的几篇正在更新中。。。
16 |
17 | ***
18 |
19 | 学习 gRPC 的书籍:
20 |
21 | 推荐这本《gRPC 与云原生应用开发》:
22 |
23 | 
24 |
25 | 如果没有实体书,可在公众号领取电子书,中文和英文的都有:
26 |
27 | 
28 |
29 | 领取方式:关注公众号【roseduan写字的地方】,或扫描下面的二维码,回复 **gRPC** 即可。
30 |
31 | 
32 |
33 |
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module grpc-demo
2 |
3 | go 1.14
4 |
5 | require (
6 | github.com/gofrs/uuid v4.0.0+incompatible
7 | github.com/golang/protobuf v1.5.2
8 | google.golang.org/grpc v1.37.0
9 | google.golang.org/protobuf v1.26.0
10 | )
11 |
--------------------------------------------------------------------------------
/go.sum:
--------------------------------------------------------------------------------
1 | cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
2 | github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
3 | github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
4 | github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
5 | github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk=
6 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
7 | github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
8 | github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
9 | github.com/envoyproxy/go-control-plane v0.9.9-0.20210217033140-668b12f5399d/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk=
10 | github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
11 | github.com/gofrs/uuid v4.0.0+incompatible h1:1SD/1F5pU8p29ybwgQSwpQk+mwdRrXCYuPhW6m+TnJw=
12 | github.com/gofrs/uuid v4.0.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM=
13 | github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
14 | github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
15 | github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
16 | github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
17 | github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=
18 | github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA=
19 | github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs=
20 | github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w=
21 | github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0=
22 | github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8=
23 | github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
24 | github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
25 | github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw=
26 | github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
27 | github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
28 | github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
29 | github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
30 | github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
31 | github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
32 | github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
33 | github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
34 | github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
35 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
36 | github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
37 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
38 | github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
39 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
40 | golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
41 | golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
42 | golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
43 | golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
44 | golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
45 | golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
46 | golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
47 | golang.org/x/net v0.0.0-20190311183353-d8887717615a h1:oWX7TPOiFAMXLq8o0ikBYfCJVlRHBcsciT5bXOrH628=
48 | golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
49 | golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
50 | golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
51 | golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
52 | golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
53 | golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
54 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a h1:1BGLXjeY4akVXGgbC9HugT3Jv3hCI0z56oJR5vAMgBU=
55 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
56 | golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=
57 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
58 | golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
59 | golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
60 | golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
61 | golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
62 | golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
63 | golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
64 | google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
65 | google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
66 | google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
67 | google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
68 | google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013 h1:+kGHl1aib/qcwaRi1CbqBZ1rk19r85MNUf8HaBghugY=
69 | google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo=
70 | google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
71 | google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg=
72 | google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY=
73 | google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk=
74 | google.golang.org/grpc v1.37.0 h1:uSZWeQJX5j11bIQ4AJoj+McDBo29cY1MCoC1wO3ts+c=
75 | google.golang.org/grpc v1.37.0/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM=
76 | google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
77 | google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
78 | google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=
79 | google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE=
80 | google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo=
81 | google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
82 | google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
83 | google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
84 | google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c=
85 | google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
86 | google.golang.org/protobuf v1.26.0 h1:bxAC2xTBsZGibn2RTntX0oH50xLsqy1OxA9tTL3p/lk=
87 | google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
88 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
89 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
90 | honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
91 | honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
92 |
--------------------------------------------------------------------------------
/grpc-demo.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/img/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/roseduan/grpc-demo/27e058b74d8d1de94c0d37c51d1a418d84dff42f/img/.DS_Store
--------------------------------------------------------------------------------
/img/book.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/roseduan/grpc-demo/27e058b74d8d1de94c0d37c51d1a418d84dff42f/img/book.png
--------------------------------------------------------------------------------
/img/book_douban.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/roseduan/grpc-demo/27e058b74d8d1de94c0d37c51d1a418d84dff42f/img/book_douban.png
--------------------------------------------------------------------------------
/img/wechat.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/roseduan/grpc-demo/27e058b74d8d1de94c0d37c51d1a418d84dff42f/img/wechat.png
--------------------------------------------------------------------------------
/load_balance_demo/Echo.pb.go:
--------------------------------------------------------------------------------
1 | // Code generated by protoc-gen-go. DO NOT EDIT.
2 | // versions:
3 | // protoc-gen-go v1.25.0
4 | // protoc v3.13.0
5 | // source: Echo.proto
6 |
7 | package load_balance_demo
8 |
9 | import (
10 | context "context"
11 | proto "github.com/golang/protobuf/proto"
12 | wrappers "github.com/golang/protobuf/ptypes/wrappers"
13 | grpc "google.golang.org/grpc"
14 | codes "google.golang.org/grpc/codes"
15 | status "google.golang.org/grpc/status"
16 | protoreflect "google.golang.org/protobuf/reflect/protoreflect"
17 | protoimpl "google.golang.org/protobuf/runtime/protoimpl"
18 | reflect "reflect"
19 | )
20 |
21 | const (
22 | // Verify that this generated code is sufficiently up-to-date.
23 | _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
24 | // Verify that runtime/protoimpl is sufficiently up-to-date.
25 | _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
26 | )
27 |
28 | // This is a compile-time assertion that a sufficiently up-to-date version
29 | // of the legacy proto package is being used.
30 | const _ = proto.ProtoPackageIsVersion4
31 |
32 | var File_Echo_proto protoreflect.FileDescriptor
33 |
34 | var file_Echo_proto_rawDesc = []byte{
35 | 0x0a, 0x0a, 0x45, 0x63, 0x68, 0x6f, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x11, 0x6c, 0x6f,
36 | 0x61, 0x64, 0x5f, 0x62, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x5f, 0x64, 0x65, 0x6d, 0x6f, 0x1a,
37 | 0x1e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66,
38 | 0x2f, 0x77, 0x72, 0x61, 0x70, 0x70, 0x65, 0x72, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x32,
39 | 0x55, 0x0a, 0x0b, 0x45, 0x63, 0x68, 0x6f, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x46,
40 | 0x0a, 0x08, 0x53, 0x61, 0x79, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x12, 0x1c, 0x2e, 0x67, 0x6f, 0x6f,
41 | 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72,
42 | 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x1a, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c,
43 | 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e,
44 | 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
45 | }
46 |
47 | var file_Echo_proto_goTypes = []interface{}{
48 | (*wrappers.StringValue)(nil), // 0: google.protobuf.StringValue
49 | }
50 | var file_Echo_proto_depIdxs = []int32{
51 | 0, // 0: load_balance_demo.EchoService.SayHello:input_type -> google.protobuf.StringValue
52 | 0, // 1: load_balance_demo.EchoService.SayHello:output_type -> google.protobuf.StringValue
53 | 1, // [1:2] is the sub-list for method output_type
54 | 0, // [0:1] is the sub-list for method input_type
55 | 0, // [0:0] is the sub-list for extension type_name
56 | 0, // [0:0] is the sub-list for extension extendee
57 | 0, // [0:0] is the sub-list for field type_name
58 | }
59 |
60 | func init() { file_Echo_proto_init() }
61 | func file_Echo_proto_init() {
62 | if File_Echo_proto != nil {
63 | return
64 | }
65 | type x struct{}
66 | out := protoimpl.TypeBuilder{
67 | File: protoimpl.DescBuilder{
68 | GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
69 | RawDescriptor: file_Echo_proto_rawDesc,
70 | NumEnums: 0,
71 | NumMessages: 0,
72 | NumExtensions: 0,
73 | NumServices: 1,
74 | },
75 | GoTypes: file_Echo_proto_goTypes,
76 | DependencyIndexes: file_Echo_proto_depIdxs,
77 | }.Build()
78 | File_Echo_proto = out.File
79 | file_Echo_proto_rawDesc = nil
80 | file_Echo_proto_goTypes = nil
81 | file_Echo_proto_depIdxs = nil
82 | }
83 |
84 | // Reference imports to suppress errors if they are not otherwise used.
85 | var _ context.Context
86 | var _ grpc.ClientConnInterface
87 |
88 | // This is a compile-time assertion to ensure that this generated file
89 | // is compatible with the grpc package it is being compiled against.
90 | const _ = grpc.SupportPackageIsVersion6
91 |
92 | // EchoServiceClient is the client API for EchoService service.
93 | //
94 | // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
95 | type EchoServiceClient interface {
96 | SayHello(ctx context.Context, in *wrappers.StringValue, opts ...grpc.CallOption) (*wrappers.StringValue, error)
97 | }
98 |
99 | type echoServiceClient struct {
100 | cc grpc.ClientConnInterface
101 | }
102 |
103 | func NewEchoServiceClient(cc grpc.ClientConnInterface) EchoServiceClient {
104 | return &echoServiceClient{cc}
105 | }
106 |
107 | func (c *echoServiceClient) SayHello(ctx context.Context, in *wrappers.StringValue, opts ...grpc.CallOption) (*wrappers.StringValue, error) {
108 | out := new(wrappers.StringValue)
109 | err := c.cc.Invoke(ctx, "/load_balance_demo.EchoService/SayHello", in, out, opts...)
110 | if err != nil {
111 | return nil, err
112 | }
113 | return out, nil
114 | }
115 |
116 | // EchoServiceServer is the server API for EchoService service.
117 | type EchoServiceServer interface {
118 | SayHello(context.Context, *wrappers.StringValue) (*wrappers.StringValue, error)
119 | }
120 |
121 | // UnimplementedEchoServiceServer can be embedded to have forward compatible implementations.
122 | type UnimplementedEchoServiceServer struct {
123 | }
124 |
125 | func (*UnimplementedEchoServiceServer) SayHello(context.Context, *wrappers.StringValue) (*wrappers.StringValue, error) {
126 | return nil, status.Errorf(codes.Unimplemented, "method SayHello not implemented")
127 | }
128 |
129 | func RegisterEchoServiceServer(s *grpc.Server, srv EchoServiceServer) {
130 | s.RegisterService(&_EchoService_serviceDesc, srv)
131 | }
132 |
133 | func _EchoService_SayHello_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
134 | in := new(wrappers.StringValue)
135 | if err := dec(in); err != nil {
136 | return nil, err
137 | }
138 | if interceptor == nil {
139 | return srv.(EchoServiceServer).SayHello(ctx, in)
140 | }
141 | info := &grpc.UnaryServerInfo{
142 | Server: srv,
143 | FullMethod: "/load_balance_demo.EchoService/SayHello",
144 | }
145 | handler := func(ctx context.Context, req interface{}) (interface{}, error) {
146 | return srv.(EchoServiceServer).SayHello(ctx, req.(*wrappers.StringValue))
147 | }
148 | return interceptor(ctx, in, info, handler)
149 | }
150 |
151 | var _EchoService_serviceDesc = grpc.ServiceDesc{
152 | ServiceName: "load_balance_demo.EchoService",
153 | HandlerType: (*EchoServiceServer)(nil),
154 | Methods: []grpc.MethodDesc{
155 | {
156 | MethodName: "SayHello",
157 | Handler: _EchoService_SayHello_Handler,
158 | },
159 | },
160 | Streams: []grpc.StreamDesc{},
161 | Metadata: "Echo.proto",
162 | }
163 |
--------------------------------------------------------------------------------
/load_balance_demo/Echo.proto:
--------------------------------------------------------------------------------
1 | syntax = "proto3";
2 | package load_balance_demo;
3 |
4 | import "google/protobuf/wrappers.proto";
5 |
6 | service EchoService {
7 | rpc SayHello(google.protobuf.StringValue) returns(google.protobuf.StringValue);
8 | }
9 |
--------------------------------------------------------------------------------
/load_balance_demo/client/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "context"
5 | "fmt"
6 | "github.com/golang/protobuf/ptypes/wrappers"
7 | "google.golang.org/grpc"
8 | "google.golang.org/grpc/resolver"
9 | "grpc-demo/load_balance_demo"
10 | "log"
11 | "time"
12 | )
13 |
14 | var addrs = []string{"localhost:50051", "localhost:50052"}
15 |
16 | const (
17 | exampleScheme = "example"
18 | exampleServiceName = "lb.example.com"
19 | )
20 |
21 | func main() {
22 | conn, _ := grpc.Dial(
23 | fmt.Sprintf("%s:///%s", exampleScheme, exampleServiceName),
24 | grpc.WithBalancerName(grpc.PickFirstBalancerName),
25 | grpc.WithInsecure(),
26 | )
27 | defer conn.Close()
28 |
29 | makeRPCs(conn, 10)
30 | }
31 |
32 | func makeRPCs(cc *grpc.ClientConn, n int) {
33 | client := load_balance_demo.NewEchoServiceClient(cc)
34 | for i := 0; i < n; i++ {
35 | callUnaryEcho(client, "test for load balance")
36 | }
37 | }
38 |
39 | func callUnaryEcho(c load_balance_demo.EchoServiceClient, message string) {
40 | ctx, cancel := context.WithTimeout(context.Background(), time.Second)
41 | defer cancel()
42 |
43 | r, err := c.SayHello(ctx, &wrappers.StringValue{Value: message})
44 | if err != nil {
45 | log.Fatalf("could not greet: %v", err)
46 | }
47 | fmt.Println(r.Value)
48 | }
49 |
50 | type exampleResolverBuilder struct{}
51 |
52 | type exampleResolver struct {
53 | target resolver.Target
54 | cc resolver.ClientConn
55 | addrsStore map[string][]string
56 | }
57 |
58 | func (*exampleResolverBuilder) Build(target resolver.Target, cc resolver.ClientConn, opts resolver.BuildOptions) (resolver.Resolver, error) {
59 | r := &exampleResolver{
60 | target: target,
61 | cc: cc,
62 | addrsStore: map[string][]string{
63 | exampleServiceName: addrs,
64 | },
65 | }
66 |
67 | r.start()
68 | return r, nil
69 | }
70 |
71 | func (*exampleResolverBuilder) Scheme() string { return exampleScheme }
72 |
73 | func (r *exampleResolver) start() {
74 | addrStrs := r.addrsStore[r.target.Endpoint]
75 | addrs := make([]resolver.Address, len(addrStrs))
76 | for i, s := range addrStrs {
77 | addrs[i] = resolver.Address{Addr: s}
78 | }
79 | r.cc.UpdateState(resolver.State{Addresses: addrs})
80 | }
81 |
82 | func (*exampleResolver) ResolveNow(o resolver.ResolveNowOptions) {}
83 | func (*exampleResolver) Close() {}
84 |
85 | func init() {
86 | resolver.Register(&exampleResolverBuilder{})
87 | }
88 |
--------------------------------------------------------------------------------
/load_balance_demo/server/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "context"
5 | "github.com/golang/protobuf/ptypes/wrappers"
6 | "google.golang.org/grpc"
7 | "grpc-demo/load_balance_demo"
8 | "log"
9 | "net"
10 | "sync"
11 | )
12 |
13 | var addrs = []string{":50051", ":50052"}
14 |
15 | type Server struct {
16 | addr string
17 | }
18 |
19 | func (s *Server) SayHello(ctx context.Context, req *wrappers.StringValue) (resp *wrappers.StringValue, err error) {
20 | resp = &wrappers.StringValue{}
21 | log.Println("the server port is ", s.addr)
22 | return
23 | }
24 |
25 | func startServer(addr string) {
26 | listener, err := net.Listen("tcp", addr)
27 | if err != nil {
28 | log.Println("tcp listen err.", err)
29 | return
30 | }
31 | s := grpc.NewServer()
32 | load_balance_demo.RegisterEchoServiceServer(s, &Server{addr})
33 | log.Printf("serving on %s\n", addr)
34 | if err := s.Serve(listener); err == nil {
35 | log.Fatalf("failed to serve: %v", err)
36 | }
37 | }
38 |
39 | func main() {
40 | var wg sync.WaitGroup
41 | for _, addr := range addrs {
42 | wg.Add(1)
43 | go func(val string) {
44 | defer wg.Done()
45 | startServer(val)
46 | }(addr)
47 | }
48 | wg.Wait()
49 | }
50 |
--------------------------------------------------------------------------------
/order/OrderInfo.pb.go:
--------------------------------------------------------------------------------
1 | // Code generated by protoc-gen-go. DO NOT EDIT.
2 | // versions:
3 | // protoc-gen-go v1.25.0
4 | // protoc v3.13.0
5 | // source: OrderInfo.proto
6 |
7 | package order
8 |
9 | import (
10 | context "context"
11 | proto "github.com/golang/protobuf/proto"
12 | wrappers "github.com/golang/protobuf/ptypes/wrappers"
13 | grpc "google.golang.org/grpc"
14 | codes "google.golang.org/grpc/codes"
15 | status "google.golang.org/grpc/status"
16 | protoreflect "google.golang.org/protobuf/reflect/protoreflect"
17 | protoimpl "google.golang.org/protobuf/runtime/protoimpl"
18 | reflect "reflect"
19 | sync "sync"
20 | )
21 |
22 | const (
23 | // Verify that this generated code is sufficiently up-to-date.
24 | _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
25 | // Verify that runtime/protoimpl is sufficiently up-to-date.
26 | _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
27 | )
28 |
29 | // This is a compile-time assertion that a sufficiently up-to-date version
30 | // of the legacy proto package is being used.
31 | const _ = proto.ProtoPackageIsVersion4
32 |
33 | type Order struct {
34 | state protoimpl.MessageState
35 | sizeCache protoimpl.SizeCache
36 | unknownFields protoimpl.UnknownFields
37 |
38 | //订单id
39 | Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
40 | //订单详情
41 | Items []string `protobuf:"bytes,2,rep,name=items,proto3" json:"items,omitempty"`
42 | //订单描述
43 | Description string `protobuf:"bytes,3,opt,name=description,proto3" json:"description,omitempty"`
44 | //订单价格
45 | Price float32 `protobuf:"fixed32,4,opt,name=price,proto3" json:"price,omitempty"`
46 | //订单目的地
47 | Destination string `protobuf:"bytes,5,opt,name=destination,proto3" json:"destination,omitempty"`
48 | }
49 |
50 | func (x *Order) Reset() {
51 | *x = Order{}
52 | if protoimpl.UnsafeEnabled {
53 | mi := &file_OrderInfo_proto_msgTypes[0]
54 | ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
55 | ms.StoreMessageInfo(mi)
56 | }
57 | }
58 |
59 | func (x *Order) String() string {
60 | return protoimpl.X.MessageStringOf(x)
61 | }
62 |
63 | func (*Order) ProtoMessage() {}
64 |
65 | func (x *Order) ProtoReflect() protoreflect.Message {
66 | mi := &file_OrderInfo_proto_msgTypes[0]
67 | if protoimpl.UnsafeEnabled && x != nil {
68 | ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
69 | if ms.LoadMessageInfo() == nil {
70 | ms.StoreMessageInfo(mi)
71 | }
72 | return ms
73 | }
74 | return mi.MessageOf(x)
75 | }
76 |
77 | // Deprecated: Use Order.ProtoReflect.Descriptor instead.
78 | func (*Order) Descriptor() ([]byte, []int) {
79 | return file_OrderInfo_proto_rawDescGZIP(), []int{0}
80 | }
81 |
82 | func (x *Order) GetId() string {
83 | if x != nil {
84 | return x.Id
85 | }
86 | return ""
87 | }
88 |
89 | func (x *Order) GetItems() []string {
90 | if x != nil {
91 | return x.Items
92 | }
93 | return nil
94 | }
95 |
96 | func (x *Order) GetDescription() string {
97 | if x != nil {
98 | return x.Description
99 | }
100 | return ""
101 | }
102 |
103 | func (x *Order) GetPrice() float32 {
104 | if x != nil {
105 | return x.Price
106 | }
107 | return 0
108 | }
109 |
110 | func (x *Order) GetDestination() string {
111 | if x != nil {
112 | return x.Destination
113 | }
114 | return ""
115 | }
116 |
117 | type CombinedShipment struct {
118 | state protoimpl.MessageState
119 | sizeCache protoimpl.SizeCache
120 | unknownFields protoimpl.UnknownFields
121 |
122 | Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
123 | Status string `protobuf:"bytes,2,opt,name=status,proto3" json:"status,omitempty"`
124 | OrderList []*Order `protobuf:"bytes,3,rep,name=orderList,proto3" json:"orderList,omitempty"`
125 | }
126 |
127 | func (x *CombinedShipment) Reset() {
128 | *x = CombinedShipment{}
129 | if protoimpl.UnsafeEnabled {
130 | mi := &file_OrderInfo_proto_msgTypes[1]
131 | ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
132 | ms.StoreMessageInfo(mi)
133 | }
134 | }
135 |
136 | func (x *CombinedShipment) String() string {
137 | return protoimpl.X.MessageStringOf(x)
138 | }
139 |
140 | func (*CombinedShipment) ProtoMessage() {}
141 |
142 | func (x *CombinedShipment) ProtoReflect() protoreflect.Message {
143 | mi := &file_OrderInfo_proto_msgTypes[1]
144 | if protoimpl.UnsafeEnabled && x != nil {
145 | ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
146 | if ms.LoadMessageInfo() == nil {
147 | ms.StoreMessageInfo(mi)
148 | }
149 | return ms
150 | }
151 | return mi.MessageOf(x)
152 | }
153 |
154 | // Deprecated: Use CombinedShipment.ProtoReflect.Descriptor instead.
155 | func (*CombinedShipment) Descriptor() ([]byte, []int) {
156 | return file_OrderInfo_proto_rawDescGZIP(), []int{1}
157 | }
158 |
159 | func (x *CombinedShipment) GetId() string {
160 | if x != nil {
161 | return x.Id
162 | }
163 | return ""
164 | }
165 |
166 | func (x *CombinedShipment) GetStatus() string {
167 | if x != nil {
168 | return x.Status
169 | }
170 | return ""
171 | }
172 |
173 | func (x *CombinedShipment) GetOrderList() []*Order {
174 | if x != nil {
175 | return x.OrderList
176 | }
177 | return nil
178 | }
179 |
180 | var File_OrderInfo_proto protoreflect.FileDescriptor
181 |
182 | var file_OrderInfo_proto_rawDesc = []byte{
183 | 0x0a, 0x0f, 0x4f, 0x72, 0x64, 0x65, 0x72, 0x49, 0x6e, 0x66, 0x6f, 0x2e, 0x70, 0x72, 0x6f, 0x74,
184 | 0x6f, 0x12, 0x05, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x1a, 0x1e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65,
185 | 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x77, 0x72, 0x61, 0x70, 0x70, 0x65,
186 | 0x72, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x87, 0x01, 0x0a, 0x05, 0x4f, 0x72, 0x64,
187 | 0x65, 0x72, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x02,
188 | 0x69, 0x64, 0x12, 0x14, 0x0a, 0x05, 0x69, 0x74, 0x65, 0x6d, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28,
189 | 0x09, 0x52, 0x05, 0x69, 0x74, 0x65, 0x6d, 0x73, 0x12, 0x20, 0x0a, 0x0b, 0x64, 0x65, 0x73, 0x63,
190 | 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x64,
191 | 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x14, 0x0a, 0x05, 0x70, 0x72,
192 | 0x69, 0x63, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x02, 0x52, 0x05, 0x70, 0x72, 0x69, 0x63, 0x65,
193 | 0x12, 0x20, 0x0a, 0x0b, 0x64, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18,
194 | 0x05, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x64, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x61, 0x74, 0x69,
195 | 0x6f, 0x6e, 0x22, 0x66, 0x0a, 0x10, 0x43, 0x6f, 0x6d, 0x62, 0x69, 0x6e, 0x65, 0x64, 0x53, 0x68,
196 | 0x69, 0x70, 0x6d, 0x65, 0x6e, 0x74, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01,
197 | 0x28, 0x09, 0x52, 0x02, 0x69, 0x64, 0x12, 0x16, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73,
198 | 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x2a,
199 | 0x0a, 0x09, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x4c, 0x69, 0x73, 0x74, 0x18, 0x03, 0x20, 0x03, 0x28,
200 | 0x0b, 0x32, 0x0c, 0x2e, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x2e, 0x4f, 0x72, 0x64, 0x65, 0x72, 0x52,
201 | 0x09, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x4c, 0x69, 0x73, 0x74, 0x32, 0xc6, 0x02, 0x0a, 0x0f, 0x4f,
202 | 0x72, 0x64, 0x65, 0x72, 0x4d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x12, 0x36,
203 | 0x0a, 0x08, 0x67, 0x65, 0x74, 0x4f, 0x72, 0x64, 0x65, 0x72, 0x12, 0x1c, 0x2e, 0x67, 0x6f, 0x6f,
204 | 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72,
205 | 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x1a, 0x0c, 0x2e, 0x6f, 0x72, 0x64, 0x65, 0x72,
206 | 0x2e, 0x4f, 0x72, 0x64, 0x65, 0x72, 0x12, 0x36, 0x0a, 0x08, 0x61, 0x64, 0x64, 0x4f, 0x72, 0x64,
207 | 0x65, 0x72, 0x12, 0x0c, 0x2e, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x2e, 0x4f, 0x72, 0x64, 0x65, 0x72,
208 | 0x1a, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62,
209 | 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x3b,
210 | 0x0a, 0x0b, 0x73, 0x65, 0x61, 0x72, 0x63, 0x68, 0x4f, 0x72, 0x64, 0x65, 0x72, 0x12, 0x1c, 0x2e,
211 | 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e,
212 | 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x1a, 0x0c, 0x2e, 0x6f, 0x72,
213 | 0x64, 0x65, 0x72, 0x2e, 0x4f, 0x72, 0x64, 0x65, 0x72, 0x30, 0x01, 0x12, 0x3b, 0x0a, 0x0b, 0x75,
214 | 0x70, 0x64, 0x61, 0x74, 0x65, 0x4f, 0x72, 0x64, 0x65, 0x72, 0x12, 0x0c, 0x2e, 0x6f, 0x72, 0x64,
215 | 0x65, 0x72, 0x2e, 0x4f, 0x72, 0x64, 0x65, 0x72, 0x1a, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c,
216 | 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e,
217 | 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x28, 0x01, 0x12, 0x49, 0x0a, 0x0c, 0x70, 0x72, 0x6f, 0x63,
218 | 0x65, 0x73, 0x73, 0x4f, 0x72, 0x64, 0x65, 0x72, 0x12, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c,
219 | 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e,
220 | 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x1a, 0x17, 0x2e, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x2e, 0x43,
221 | 0x6f, 0x6d, 0x62, 0x69, 0x6e, 0x65, 0x64, 0x53, 0x68, 0x69, 0x70, 0x6d, 0x65, 0x6e, 0x74, 0x28,
222 | 0x01, 0x30, 0x01, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
223 | }
224 |
225 | var (
226 | file_OrderInfo_proto_rawDescOnce sync.Once
227 | file_OrderInfo_proto_rawDescData = file_OrderInfo_proto_rawDesc
228 | )
229 |
230 | func file_OrderInfo_proto_rawDescGZIP() []byte {
231 | file_OrderInfo_proto_rawDescOnce.Do(func() {
232 | file_OrderInfo_proto_rawDescData = protoimpl.X.CompressGZIP(file_OrderInfo_proto_rawDescData)
233 | })
234 | return file_OrderInfo_proto_rawDescData
235 | }
236 |
237 | var file_OrderInfo_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
238 | var file_OrderInfo_proto_goTypes = []interface{}{
239 | (*Order)(nil), // 0: order.Order
240 | (*CombinedShipment)(nil), // 1: order.CombinedShipment
241 | (*wrappers.StringValue)(nil), // 2: google.protobuf.StringValue
242 | }
243 | var file_OrderInfo_proto_depIdxs = []int32{
244 | 0, // 0: order.CombinedShipment.orderList:type_name -> order.Order
245 | 2, // 1: order.OrderManagement.getOrder:input_type -> google.protobuf.StringValue
246 | 0, // 2: order.OrderManagement.addOrder:input_type -> order.Order
247 | 2, // 3: order.OrderManagement.searchOrder:input_type -> google.protobuf.StringValue
248 | 0, // 4: order.OrderManagement.updateOrder:input_type -> order.Order
249 | 2, // 5: order.OrderManagement.processOrder:input_type -> google.protobuf.StringValue
250 | 0, // 6: order.OrderManagement.getOrder:output_type -> order.Order
251 | 2, // 7: order.OrderManagement.addOrder:output_type -> google.protobuf.StringValue
252 | 0, // 8: order.OrderManagement.searchOrder:output_type -> order.Order
253 | 2, // 9: order.OrderManagement.updateOrder:output_type -> google.protobuf.StringValue
254 | 1, // 10: order.OrderManagement.processOrder:output_type -> order.CombinedShipment
255 | 6, // [6:11] is the sub-list for method output_type
256 | 1, // [1:6] is the sub-list for method input_type
257 | 1, // [1:1] is the sub-list for extension type_name
258 | 1, // [1:1] is the sub-list for extension extendee
259 | 0, // [0:1] is the sub-list for field type_name
260 | }
261 |
262 | func init() { file_OrderInfo_proto_init() }
263 | func file_OrderInfo_proto_init() {
264 | if File_OrderInfo_proto != nil {
265 | return
266 | }
267 | if !protoimpl.UnsafeEnabled {
268 | file_OrderInfo_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
269 | switch v := v.(*Order); i {
270 | case 0:
271 | return &v.state
272 | case 1:
273 | return &v.sizeCache
274 | case 2:
275 | return &v.unknownFields
276 | default:
277 | return nil
278 | }
279 | }
280 | file_OrderInfo_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
281 | switch v := v.(*CombinedShipment); i {
282 | case 0:
283 | return &v.state
284 | case 1:
285 | return &v.sizeCache
286 | case 2:
287 | return &v.unknownFields
288 | default:
289 | return nil
290 | }
291 | }
292 | }
293 | type x struct{}
294 | out := protoimpl.TypeBuilder{
295 | File: protoimpl.DescBuilder{
296 | GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
297 | RawDescriptor: file_OrderInfo_proto_rawDesc,
298 | NumEnums: 0,
299 | NumMessages: 2,
300 | NumExtensions: 0,
301 | NumServices: 1,
302 | },
303 | GoTypes: file_OrderInfo_proto_goTypes,
304 | DependencyIndexes: file_OrderInfo_proto_depIdxs,
305 | MessageInfos: file_OrderInfo_proto_msgTypes,
306 | }.Build()
307 | File_OrderInfo_proto = out.File
308 | file_OrderInfo_proto_rawDesc = nil
309 | file_OrderInfo_proto_goTypes = nil
310 | file_OrderInfo_proto_depIdxs = nil
311 | }
312 |
313 | // Reference imports to suppress errors if they are not otherwise used.
314 | var _ context.Context
315 | var _ grpc.ClientConnInterface
316 |
317 | // This is a compile-time assertion to ensure that this generated file
318 | // is compatible with the grpc package it is being compiled against.
319 | const _ = grpc.SupportPackageIsVersion6
320 |
321 | // OrderManagementClient is the client API for OrderManagement service.
322 | //
323 | // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
324 | type OrderManagementClient interface {
325 | //获取订单
326 | GetOrder(ctx context.Context, in *wrappers.StringValue, opts ...grpc.CallOption) (*Order, error)
327 | //添加订单
328 | AddOrder(ctx context.Context, in *Order, opts ...grpc.CallOption) (*wrappers.StringValue, error)
329 | //搜索订单
330 | SearchOrder(ctx context.Context, in *wrappers.StringValue, opts ...grpc.CallOption) (OrderManagement_SearchOrderClient, error)
331 | //更新订单
332 | UpdateOrder(ctx context.Context, opts ...grpc.CallOption) (OrderManagement_UpdateOrderClient, error)
333 | //处理订单
334 | ProcessOrder(ctx context.Context, opts ...grpc.CallOption) (OrderManagement_ProcessOrderClient, error)
335 | }
336 |
337 | type orderManagementClient struct {
338 | cc grpc.ClientConnInterface
339 | }
340 |
341 | func NewOrderManagementClient(cc grpc.ClientConnInterface) OrderManagementClient {
342 | return &orderManagementClient{cc}
343 | }
344 |
345 | func (c *orderManagementClient) GetOrder(ctx context.Context, in *wrappers.StringValue, opts ...grpc.CallOption) (*Order, error) {
346 | out := new(Order)
347 | err := c.cc.Invoke(ctx, "/order.OrderManagement/getOrder", in, out, opts...)
348 | if err != nil {
349 | return nil, err
350 | }
351 | return out, nil
352 | }
353 |
354 | func (c *orderManagementClient) AddOrder(ctx context.Context, in *Order, opts ...grpc.CallOption) (*wrappers.StringValue, error) {
355 | out := new(wrappers.StringValue)
356 | err := c.cc.Invoke(ctx, "/order.OrderManagement/addOrder", in, out, opts...)
357 | if err != nil {
358 | return nil, err
359 | }
360 | return out, nil
361 | }
362 |
363 | func (c *orderManagementClient) SearchOrder(ctx context.Context, in *wrappers.StringValue, opts ...grpc.CallOption) (OrderManagement_SearchOrderClient, error) {
364 | stream, err := c.cc.NewStream(ctx, &_OrderManagement_serviceDesc.Streams[0], "/order.OrderManagement/searchOrder", opts...)
365 | if err != nil {
366 | return nil, err
367 | }
368 | x := &orderManagementSearchOrderClient{stream}
369 | if err := x.ClientStream.SendMsg(in); err != nil {
370 | return nil, err
371 | }
372 | if err := x.ClientStream.CloseSend(); err != nil {
373 | return nil, err
374 | }
375 | return x, nil
376 | }
377 |
378 | type OrderManagement_SearchOrderClient interface {
379 | Recv() (*Order, error)
380 | grpc.ClientStream
381 | }
382 |
383 | type orderManagementSearchOrderClient struct {
384 | grpc.ClientStream
385 | }
386 |
387 | func (x *orderManagementSearchOrderClient) Recv() (*Order, error) {
388 | m := new(Order)
389 | if err := x.ClientStream.RecvMsg(m); err != nil {
390 | return nil, err
391 | }
392 | return m, nil
393 | }
394 |
395 | func (c *orderManagementClient) UpdateOrder(ctx context.Context, opts ...grpc.CallOption) (OrderManagement_UpdateOrderClient, error) {
396 | stream, err := c.cc.NewStream(ctx, &_OrderManagement_serviceDesc.Streams[1], "/order.OrderManagement/updateOrder", opts...)
397 | if err != nil {
398 | return nil, err
399 | }
400 | x := &orderManagementUpdateOrderClient{stream}
401 | return x, nil
402 | }
403 |
404 | type OrderManagement_UpdateOrderClient interface {
405 | Send(*Order) error
406 | CloseAndRecv() (*wrappers.StringValue, error)
407 | grpc.ClientStream
408 | }
409 |
410 | type orderManagementUpdateOrderClient struct {
411 | grpc.ClientStream
412 | }
413 |
414 | func (x *orderManagementUpdateOrderClient) Send(m *Order) error {
415 | return x.ClientStream.SendMsg(m)
416 | }
417 |
418 | func (x *orderManagementUpdateOrderClient) CloseAndRecv() (*wrappers.StringValue, error) {
419 | if err := x.ClientStream.CloseSend(); err != nil {
420 | return nil, err
421 | }
422 | m := new(wrappers.StringValue)
423 | if err := x.ClientStream.RecvMsg(m); err != nil {
424 | return nil, err
425 | }
426 | return m, nil
427 | }
428 |
429 | func (c *orderManagementClient) ProcessOrder(ctx context.Context, opts ...grpc.CallOption) (OrderManagement_ProcessOrderClient, error) {
430 | stream, err := c.cc.NewStream(ctx, &_OrderManagement_serviceDesc.Streams[2], "/order.OrderManagement/processOrder", opts...)
431 | if err != nil {
432 | return nil, err
433 | }
434 | x := &orderManagementProcessOrderClient{stream}
435 | return x, nil
436 | }
437 |
438 | type OrderManagement_ProcessOrderClient interface {
439 | Send(*wrappers.StringValue) error
440 | Recv() (*CombinedShipment, error)
441 | grpc.ClientStream
442 | }
443 |
444 | type orderManagementProcessOrderClient struct {
445 | grpc.ClientStream
446 | }
447 |
448 | func (x *orderManagementProcessOrderClient) Send(m *wrappers.StringValue) error {
449 | return x.ClientStream.SendMsg(m)
450 | }
451 |
452 | func (x *orderManagementProcessOrderClient) Recv() (*CombinedShipment, error) {
453 | m := new(CombinedShipment)
454 | if err := x.ClientStream.RecvMsg(m); err != nil {
455 | return nil, err
456 | }
457 | return m, nil
458 | }
459 |
460 | // OrderManagementServer is the server API for OrderManagement service.
461 | type OrderManagementServer interface {
462 | //获取订单
463 | GetOrder(context.Context, *wrappers.StringValue) (*Order, error)
464 | //添加订单
465 | AddOrder(context.Context, *Order) (*wrappers.StringValue, error)
466 | //搜索订单
467 | SearchOrder(*wrappers.StringValue, OrderManagement_SearchOrderServer) error
468 | //更新订单
469 | UpdateOrder(OrderManagement_UpdateOrderServer) error
470 | //处理订单
471 | ProcessOrder(OrderManagement_ProcessOrderServer) error
472 | }
473 |
474 | // UnimplementedOrderManagementServer can be embedded to have forward compatible implementations.
475 | type UnimplementedOrderManagementServer struct {
476 | }
477 |
478 | func (*UnimplementedOrderManagementServer) GetOrder(context.Context, *wrappers.StringValue) (*Order, error) {
479 | return nil, status.Errorf(codes.Unimplemented, "method GetOrder not implemented")
480 | }
481 | func (*UnimplementedOrderManagementServer) AddOrder(context.Context, *Order) (*wrappers.StringValue, error) {
482 | return nil, status.Errorf(codes.Unimplemented, "method AddOrder not implemented")
483 | }
484 | func (*UnimplementedOrderManagementServer) SearchOrder(*wrappers.StringValue, OrderManagement_SearchOrderServer) error {
485 | return status.Errorf(codes.Unimplemented, "method SearchOrder not implemented")
486 | }
487 | func (*UnimplementedOrderManagementServer) UpdateOrder(OrderManagement_UpdateOrderServer) error {
488 | return status.Errorf(codes.Unimplemented, "method UpdateOrder not implemented")
489 | }
490 | func (*UnimplementedOrderManagementServer) ProcessOrder(OrderManagement_ProcessOrderServer) error {
491 | return status.Errorf(codes.Unimplemented, "method ProcessOrder not implemented")
492 | }
493 |
494 | func RegisterOrderManagementServer(s *grpc.Server, srv OrderManagementServer) {
495 | s.RegisterService(&_OrderManagement_serviceDesc, srv)
496 | }
497 |
498 | func _OrderManagement_GetOrder_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
499 | in := new(wrappers.StringValue)
500 | if err := dec(in); err != nil {
501 | return nil, err
502 | }
503 | if interceptor == nil {
504 | return srv.(OrderManagementServer).GetOrder(ctx, in)
505 | }
506 | info := &grpc.UnaryServerInfo{
507 | Server: srv,
508 | FullMethod: "/order.OrderManagement/GetOrder",
509 | }
510 | handler := func(ctx context.Context, req interface{}) (interface{}, error) {
511 | return srv.(OrderManagementServer).GetOrder(ctx, req.(*wrappers.StringValue))
512 | }
513 | return interceptor(ctx, in, info, handler)
514 | }
515 |
516 | func _OrderManagement_AddOrder_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
517 | in := new(Order)
518 | if err := dec(in); err != nil {
519 | return nil, err
520 | }
521 | if interceptor == nil {
522 | return srv.(OrderManagementServer).AddOrder(ctx, in)
523 | }
524 | info := &grpc.UnaryServerInfo{
525 | Server: srv,
526 | FullMethod: "/order.OrderManagement/AddOrder",
527 | }
528 | handler := func(ctx context.Context, req interface{}) (interface{}, error) {
529 | return srv.(OrderManagementServer).AddOrder(ctx, req.(*Order))
530 | }
531 | return interceptor(ctx, in, info, handler)
532 | }
533 |
534 | func _OrderManagement_SearchOrder_Handler(srv interface{}, stream grpc.ServerStream) error {
535 | m := new(wrappers.StringValue)
536 | if err := stream.RecvMsg(m); err != nil {
537 | return err
538 | }
539 | return srv.(OrderManagementServer).SearchOrder(m, &orderManagementSearchOrderServer{stream})
540 | }
541 |
542 | type OrderManagement_SearchOrderServer interface {
543 | Send(*Order) error
544 | grpc.ServerStream
545 | }
546 |
547 | type orderManagementSearchOrderServer struct {
548 | grpc.ServerStream
549 | }
550 |
551 | func (x *orderManagementSearchOrderServer) Send(m *Order) error {
552 | return x.ServerStream.SendMsg(m)
553 | }
554 |
555 | func _OrderManagement_UpdateOrder_Handler(srv interface{}, stream grpc.ServerStream) error {
556 | return srv.(OrderManagementServer).UpdateOrder(&orderManagementUpdateOrderServer{stream})
557 | }
558 |
559 | type OrderManagement_UpdateOrderServer interface {
560 | SendAndClose(*wrappers.StringValue) error
561 | Recv() (*Order, error)
562 | grpc.ServerStream
563 | }
564 |
565 | type orderManagementUpdateOrderServer struct {
566 | grpc.ServerStream
567 | }
568 |
569 | func (x *orderManagementUpdateOrderServer) SendAndClose(m *wrappers.StringValue) error {
570 | return x.ServerStream.SendMsg(m)
571 | }
572 |
573 | func (x *orderManagementUpdateOrderServer) Recv() (*Order, error) {
574 | m := new(Order)
575 | if err := x.ServerStream.RecvMsg(m); err != nil {
576 | return nil, err
577 | }
578 | return m, nil
579 | }
580 |
581 | func _OrderManagement_ProcessOrder_Handler(srv interface{}, stream grpc.ServerStream) error {
582 | return srv.(OrderManagementServer).ProcessOrder(&orderManagementProcessOrderServer{stream})
583 | }
584 |
585 | type OrderManagement_ProcessOrderServer interface {
586 | Send(*CombinedShipment) error
587 | Recv() (*wrappers.StringValue, error)
588 | grpc.ServerStream
589 | }
590 |
591 | type orderManagementProcessOrderServer struct {
592 | grpc.ServerStream
593 | }
594 |
595 | func (x *orderManagementProcessOrderServer) Send(m *CombinedShipment) error {
596 | return x.ServerStream.SendMsg(m)
597 | }
598 |
599 | func (x *orderManagementProcessOrderServer) Recv() (*wrappers.StringValue, error) {
600 | m := new(wrappers.StringValue)
601 | if err := x.ServerStream.RecvMsg(m); err != nil {
602 | return nil, err
603 | }
604 | return m, nil
605 | }
606 |
607 | var _OrderManagement_serviceDesc = grpc.ServiceDesc{
608 | ServiceName: "order.OrderManagement",
609 | HandlerType: (*OrderManagementServer)(nil),
610 | Methods: []grpc.MethodDesc{
611 | {
612 | MethodName: "getOrder",
613 | Handler: _OrderManagement_GetOrder_Handler,
614 | },
615 | {
616 | MethodName: "addOrder",
617 | Handler: _OrderManagement_AddOrder_Handler,
618 | },
619 | },
620 | Streams: []grpc.StreamDesc{
621 | {
622 | StreamName: "searchOrder",
623 | Handler: _OrderManagement_SearchOrder_Handler,
624 | ServerStreams: true,
625 | },
626 | {
627 | StreamName: "updateOrder",
628 | Handler: _OrderManagement_UpdateOrder_Handler,
629 | ClientStreams: true,
630 | },
631 | {
632 | StreamName: "processOrder",
633 | Handler: _OrderManagement_ProcessOrder_Handler,
634 | ServerStreams: true,
635 | ClientStreams: true,
636 | },
637 | },
638 | Metadata: "OrderInfo.proto",
639 | }
640 |
--------------------------------------------------------------------------------
/order/OrderInfo.proto:
--------------------------------------------------------------------------------
1 | syntax = "proto3";
2 | package order;
3 |
4 | import "google/protobuf/wrappers.proto";
5 |
6 | service OrderManagement {
7 | //获取订单
8 | rpc getOrder(google.protobuf.StringValue) returns(Order);
9 | //添加订单
10 | rpc addOrder(Order) returns(google.protobuf.StringValue);
11 | //搜索订单
12 | rpc searchOrder(google.protobuf.StringValue) returns(stream Order);
13 | //更新订单
14 | rpc updateOrder(stream Order) returns(google.protobuf.StringValue);
15 | //处理订单
16 | rpc processOrder(stream google.protobuf.StringValue) returns(stream CombinedShipment);
17 | }
18 |
19 | message Order {
20 | //订单id
21 | string id = 1;
22 | //订单详情
23 | repeated string items = 2;
24 | //订单描述
25 | string description = 3;
26 | //订单价格
27 | float price = 4;
28 | //订单目的地
29 | string destination = 5;
30 | }
31 |
32 | message CombinedShipment {
33 | string id = 1;
34 | string status = 2;
35 | repeated Order orderList = 3;
36 | }
37 |
--------------------------------------------------------------------------------
/order/client/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "context"
5 | "fmt"
6 | "github.com/golang/protobuf/ptypes/wrappers"
7 | "google.golang.org/grpc"
8 | "grpc-demo/order"
9 | "io"
10 | "log"
11 | )
12 |
13 | const address = "localhost:50051"
14 |
15 | func main() {
16 | conn, err := grpc.Dial(address, grpc.WithInsecure())
17 | if err != nil {
18 | log.Println("did not connect.", err)
19 | return
20 | }
21 | defer conn.Close()
22 |
23 | ctx := context.Background()
24 | client := order.NewOrderManagementClient(conn)
25 |
26 | fmt.Println("----------------unary rpc----------------")
27 | id := AddOrder(ctx, client)
28 | GetOrder(ctx, client, id)
29 |
30 | fmt.Println("-----------server stream rpc-------------")
31 | SearchOrder(ctx, client)
32 |
33 | fmt.Println("------------client stream rpc------------")
34 | UpdateOrder(ctx, client)
35 |
36 | fmt.Println("---------bidirectional stream rpc---------")
37 | ProcessOrder(ctx, client)
38 | }
39 |
40 | //添加一个订单
41 | func AddOrder(ctx context.Context, client order.OrderManagementClient) string {
42 | odr := &order.Order{
43 | Description: "a new order for test-1",
44 | Price: 12322.232,
45 | Destination: "Shanghai",
46 | Items: []string{"doll", "22", "33"},
47 | }
48 |
49 | val, err := client.AddOrder(ctx, odr)
50 | if err != nil {
51 | log.Println("add order fail.", err)
52 | return ""
53 | }
54 | log.Println("add order success.id = ", val.String())
55 | return val.Value
56 | }
57 |
58 | //获取一个订单
59 | func GetOrder(ctx context.Context, client order.OrderManagementClient, id string) {
60 | val, err := client.GetOrder(ctx, &wrappers.StringValue{Value: id})
61 | if err != nil {
62 | log.Println("get order err.", err)
63 | return
64 | }
65 |
66 | log.Printf("get order succes. order = %+v", val)
67 | }
68 |
69 | //搜索订单
70 | func SearchOrder(ctx context.Context, client order.OrderManagementClient) {
71 | searchKey := "Apple"
72 | searchStream, _ := client.SearchOrder(ctx, &wrappers.StringValue{Value: searchKey})
73 | for {
74 | val, err := searchStream.Recv()
75 | if err == io.EOF { //服务端没有数据了
76 | break
77 | }
78 | log.Printf("search order from server : %+v", val)
79 | }
80 | return
81 | }
82 |
83 | //更新订单
84 | func UpdateOrder(ctx context.Context, client order.OrderManagementClient) {
85 | updateStream, _ := client.UpdateOrder(ctx)
86 | order1 := &order.Order{Id: "103", Items: []string{"Apple Watch S6"}, Destination: "San Jose, CA", Price: 4400.00}
87 | order2 := &order.Order{Id: "105", Items: []string{"Amazon Kindle"}, Destination: "San Jose, CA", Price: 330.00}
88 |
89 | //更新订单1
90 | if err := updateStream.Send(order1); err != nil {
91 | log.Println("send order err.", err)
92 | }
93 |
94 | //更新订单2
95 | if err := updateStream.Send(order2); err != nil {
96 | log.Println("send order err.", err)
97 | }
98 |
99 | //关闭流并接收响应
100 | recv, err := updateStream.CloseAndRecv()
101 | if err != nil {
102 | log.Println("close and recv err.", err)
103 | return
104 | }
105 | log.Printf("the update result : %+v", recv)
106 | }
107 |
108 | //处理订单
109 | func ProcessOrder(ctx context.Context, client order.OrderManagementClient) {
110 | processStream, _ := client.ProcessOrder(ctx)
111 |
112 | //发送两个订单处理
113 | if err := processStream.Send(&wrappers.StringValue{Value: "103"}); err != nil {
114 | log.Println("send order err.", err)
115 | }
116 | if err := processStream.Send(&wrappers.StringValue{Value: "105"}); err != nil {
117 | log.Println("send order err.", err)
118 | }
119 |
120 | chn := make(chan struct{})
121 | //异步接收服务端的结果
122 | go processResultFromServer(processStream, chn)
123 |
124 | //再发送一个订单
125 | if err := processStream.Send(&wrappers.StringValue{Value: "106"}); err != nil {
126 | log.Println("send order err.", err)
127 | }
128 | //发送完毕后记得关闭
129 | if err := processStream.CloseSend(); err != nil {
130 | log.Println("close send err.", err)
131 | }
132 |
133 | <-chn
134 | }
135 |
136 | //从服务端获取处理的结果
137 | func processResultFromServer(stream order.OrderManagement_ProcessOrderClient, chn chan struct{}) {
138 | defer close(chn)
139 | for {
140 | shipment, err := stream.Recv()
141 | if err == io.EOF {
142 | log.Println("[client]结束从服务端接收数据")
143 | break
144 | }
145 | log.Printf("[client]server process result : %+v\n", shipment)
146 | }
147 | }
148 |
--------------------------------------------------------------------------------
/order/server/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "context"
5 | "github.com/gofrs/uuid"
6 | "github.com/golang/protobuf/ptypes/wrappers"
7 | "google.golang.org/grpc"
8 | "google.golang.org/grpc/codes"
9 | "google.golang.org/grpc/status"
10 | "grpc-demo/order"
11 | "io"
12 | "log"
13 | "net"
14 | "strings"
15 | )
16 |
17 | const port = ":50051"
18 |
19 | //初始化添加一些订单数据
20 | func initSampleData(orderMap map[string]*order.Order) {
21 | orderMap["102"] = &order.Order{Id: "102", Items: []string{"Google Pixel 3A", "Mac Book Pro"}, Destination: "Mountain View, CA", Price: 1800.00}
22 | orderMap["103"] = &order.Order{Id: "103", Items: []string{"Apple Watch S4"}, Destination: "San Jose, CA", Price: 400.00}
23 | orderMap["104"] = &order.Order{Id: "104", Items: []string{"Google Home Mini", "Google Nest Hub"}, Destination: "Mountain View, CA", Price: 400.00}
24 | orderMap["105"] = &order.Order{Id: "105", Items: []string{"Amazon Echo"}, Destination: "San Jose, CA", Price: 30.00}
25 | orderMap["106"] = &order.Order{Id: "106", Items: []string{"Amazon Echo", "Apple iPhone XS"}, Destination: "Mountain View, CA", Price: 300.00}
26 | }
27 |
28 | func main() {
29 | server := &server{orderMap: make(map[string]*order.Order)}
30 | initSampleData(server.orderMap)
31 |
32 | listener, err := net.Listen("tcp", port)
33 | if err != nil {
34 | log.Println("net listen err ", err)
35 | return
36 | }
37 |
38 | s := grpc.NewServer()
39 | order.RegisterOrderManagementServer(s, server)
40 | log.Println("start gRPC listen on port " + port)
41 | if err := s.Serve(listener); err != nil {
42 | log.Println("failed to serve...", err)
43 | return
44 | }
45 | }
46 |
47 | type server struct {
48 | orderMap map[string]*order.Order
49 | }
50 |
51 | //获取订单
52 | func (s *server) GetOrder(ctx context.Context, req *wrappers.StringValue) (resp *order.Order, err error) {
53 | resp = &order.Order{}
54 | id := req.Value
55 | var exist bool
56 | if resp, exist = s.orderMap[id]; !exist {
57 | err = status.Error(codes.NotFound, "order not found id = "+id)
58 | return
59 | }
60 | return
61 | }
62 |
63 | //添加订单
64 | func (s *server) AddOrder(ctx context.Context, req *order.Order) (resp *wrappers.StringValue, err error) {
65 | resp = &wrappers.StringValue{}
66 | if s.orderMap == nil {
67 | s.orderMap = make(map[string]*order.Order)
68 | }
69 |
70 | v4, err := uuid.NewV4()
71 | if err != nil {
72 | return resp, status.Errorf(codes.Internal, "gen uuid err", err)
73 | }
74 | id := v4.String()
75 | req.Id = id
76 | s.orderMap[id] = req
77 |
78 | resp.Value = id
79 | return
80 | }
81 |
82 | //搜索订单
83 | func (s *server) SearchOrder(searchKey *wrappers.StringValue, stream order.OrderManagement_SearchOrderServer) (err error) {
84 | for _, val := range s.orderMap {
85 | for _, item := range val.Items {
86 | if strings.Contains(item, searchKey.Value) {
87 | err = stream.Send(val)
88 | if err != nil {
89 | log.Println("stream send order err.", err)
90 | return
91 | }
92 | break
93 | }
94 | }
95 | }
96 | return
97 | }
98 |
99 | //更新订单
100 | func (s *server) UpdateOrder(stream order.OrderManagement_UpdateOrderServer) (err error) {
101 | updatedIds := "updated order ids : "
102 | for {
103 | val, err := stream.Recv()
104 | if err == io.EOF { //完成读取订单流
105 | //向客户端发送消息
106 | return stream.SendAndClose(&wrappers.StringValue{Value: updatedIds})
107 | }
108 | s.orderMap[val.Id] = val
109 | log.Println("[server]update the order : ", val.Id)
110 | updatedIds += val.Id + ", "
111 | }
112 | }
113 |
114 | //处理订单
115 | func (s *server) ProcessOrder(stream order.OrderManagement_ProcessOrderServer) (err error) {
116 | var combinedShipmentMap = make(map[string]*order.CombinedShipment)
117 | for {
118 | val, err := stream.Recv() //接收从客户端发送来的订单
119 | if err == io.EOF { //接收完毕,返回结果
120 | for _, shipment := range combinedShipmentMap {
121 | if err := stream.Send(shipment); err != nil {
122 | log.Println("[server] process finished!")
123 | return err
124 | }
125 | }
126 | break
127 | }
128 | if err != nil {
129 | log.Println(err)
130 | break
131 | }
132 |
133 | if val != nil {
134 | orderId := val.Value
135 | log.Printf("[server]reading order : %+v\n", orderId)
136 |
137 | dest := s.orderMap[orderId].Destination
138 | shipment, exist := combinedShipmentMap[dest]
139 | if exist {
140 | ord := s.orderMap[orderId]
141 | shipment.OrderList = append(shipment.OrderList, ord)
142 | combinedShipmentMap[dest] = shipment
143 | } else {
144 | comShip := &order.CombinedShipment{Id: "cmb - " + (s.orderMap[orderId].Destination), Status: "Processed!"}
145 | ord := s.orderMap[orderId]
146 | comShip.OrderList = append(comShip.OrderList, ord)
147 | combinedShipmentMap[dest] = comShip
148 | log.Println(len(comShip.OrderList), comShip.GetId())
149 | }
150 | }
151 | }
152 | return
153 | }
154 |
--------------------------------------------------------------------------------
/order_advance_1/OrderInfo.pb.go:
--------------------------------------------------------------------------------
1 | // Code generated by protoc-gen-go. DO NOT EDIT.
2 | // versions:
3 | // protoc-gen-go v1.25.0
4 | // protoc v3.13.0
5 | // source: OrderInfo.proto
6 |
7 | package order
8 |
9 | import (
10 | context "context"
11 | proto "github.com/golang/protobuf/proto"
12 | wrappers "github.com/golang/protobuf/ptypes/wrappers"
13 | grpc "google.golang.org/grpc"
14 | codes "google.golang.org/grpc/codes"
15 | status "google.golang.org/grpc/status"
16 | protoreflect "google.golang.org/protobuf/reflect/protoreflect"
17 | protoimpl "google.golang.org/protobuf/runtime/protoimpl"
18 | reflect "reflect"
19 | sync "sync"
20 | )
21 |
22 | const (
23 | // Verify that this generated code is sufficiently up-to-date.
24 | _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
25 | // Verify that runtime/protoimpl is sufficiently up-to-date.
26 | _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
27 | )
28 |
29 | // This is a compile-time assertion that a sufficiently up-to-date version
30 | // of the legacy proto package is being used.
31 | const _ = proto.ProtoPackageIsVersion4
32 |
33 | type Order struct {
34 | state protoimpl.MessageState
35 | sizeCache protoimpl.SizeCache
36 | unknownFields protoimpl.UnknownFields
37 |
38 | //订单id
39 | Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
40 | //订单详情
41 | Items []string `protobuf:"bytes,2,rep,name=items,proto3" json:"items,omitempty"`
42 | //订单描述
43 | Description string `protobuf:"bytes,3,opt,name=description,proto3" json:"description,omitempty"`
44 | //订单价格
45 | Price float32 `protobuf:"fixed32,4,opt,name=price,proto3" json:"price,omitempty"`
46 | //订单目的地
47 | Destination string `protobuf:"bytes,5,opt,name=destination,proto3" json:"destination,omitempty"`
48 | }
49 |
50 | func (x *Order) Reset() {
51 | *x = Order{}
52 | if protoimpl.UnsafeEnabled {
53 | mi := &file_OrderInfo_proto_msgTypes[0]
54 | ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
55 | ms.StoreMessageInfo(mi)
56 | }
57 | }
58 |
59 | func (x *Order) String() string {
60 | return protoimpl.X.MessageStringOf(x)
61 | }
62 |
63 | func (*Order) ProtoMessage() {}
64 |
65 | func (x *Order) ProtoReflect() protoreflect.Message {
66 | mi := &file_OrderInfo_proto_msgTypes[0]
67 | if protoimpl.UnsafeEnabled && x != nil {
68 | ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
69 | if ms.LoadMessageInfo() == nil {
70 | ms.StoreMessageInfo(mi)
71 | }
72 | return ms
73 | }
74 | return mi.MessageOf(x)
75 | }
76 |
77 | // Deprecated: Use Order.ProtoReflect.Descriptor instead.
78 | func (*Order) Descriptor() ([]byte, []int) {
79 | return file_OrderInfo_proto_rawDescGZIP(), []int{0}
80 | }
81 |
82 | func (x *Order) GetId() string {
83 | if x != nil {
84 | return x.Id
85 | }
86 | return ""
87 | }
88 |
89 | func (x *Order) GetItems() []string {
90 | if x != nil {
91 | return x.Items
92 | }
93 | return nil
94 | }
95 |
96 | func (x *Order) GetDescription() string {
97 | if x != nil {
98 | return x.Description
99 | }
100 | return ""
101 | }
102 |
103 | func (x *Order) GetPrice() float32 {
104 | if x != nil {
105 | return x.Price
106 | }
107 | return 0
108 | }
109 |
110 | func (x *Order) GetDestination() string {
111 | if x != nil {
112 | return x.Destination
113 | }
114 | return ""
115 | }
116 |
117 | type CombinedShipment struct {
118 | state protoimpl.MessageState
119 | sizeCache protoimpl.SizeCache
120 | unknownFields protoimpl.UnknownFields
121 |
122 | Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
123 | Status string `protobuf:"bytes,2,opt,name=status,proto3" json:"status,omitempty"`
124 | OrderList []*Order `protobuf:"bytes,3,rep,name=orderList,proto3" json:"orderList,omitempty"`
125 | }
126 |
127 | func (x *CombinedShipment) Reset() {
128 | *x = CombinedShipment{}
129 | if protoimpl.UnsafeEnabled {
130 | mi := &file_OrderInfo_proto_msgTypes[1]
131 | ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
132 | ms.StoreMessageInfo(mi)
133 | }
134 | }
135 |
136 | func (x *CombinedShipment) String() string {
137 | return protoimpl.X.MessageStringOf(x)
138 | }
139 |
140 | func (*CombinedShipment) ProtoMessage() {}
141 |
142 | func (x *CombinedShipment) ProtoReflect() protoreflect.Message {
143 | mi := &file_OrderInfo_proto_msgTypes[1]
144 | if protoimpl.UnsafeEnabled && x != nil {
145 | ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
146 | if ms.LoadMessageInfo() == nil {
147 | ms.StoreMessageInfo(mi)
148 | }
149 | return ms
150 | }
151 | return mi.MessageOf(x)
152 | }
153 |
154 | // Deprecated: Use CombinedShipment.ProtoReflect.Descriptor instead.
155 | func (*CombinedShipment) Descriptor() ([]byte, []int) {
156 | return file_OrderInfo_proto_rawDescGZIP(), []int{1}
157 | }
158 |
159 | func (x *CombinedShipment) GetId() string {
160 | if x != nil {
161 | return x.Id
162 | }
163 | return ""
164 | }
165 |
166 | func (x *CombinedShipment) GetStatus() string {
167 | if x != nil {
168 | return x.Status
169 | }
170 | return ""
171 | }
172 |
173 | func (x *CombinedShipment) GetOrderList() []*Order {
174 | if x != nil {
175 | return x.OrderList
176 | }
177 | return nil
178 | }
179 |
180 | var File_OrderInfo_proto protoreflect.FileDescriptor
181 |
182 | var file_OrderInfo_proto_rawDesc = []byte{
183 | 0x0a, 0x0f, 0x4f, 0x72, 0x64, 0x65, 0x72, 0x49, 0x6e, 0x66, 0x6f, 0x2e, 0x70, 0x72, 0x6f, 0x74,
184 | 0x6f, 0x12, 0x05, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x1a, 0x1e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65,
185 | 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x77, 0x72, 0x61, 0x70, 0x70, 0x65,
186 | 0x72, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x87, 0x01, 0x0a, 0x05, 0x4f, 0x72, 0x64,
187 | 0x65, 0x72, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x02,
188 | 0x69, 0x64, 0x12, 0x14, 0x0a, 0x05, 0x69, 0x74, 0x65, 0x6d, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28,
189 | 0x09, 0x52, 0x05, 0x69, 0x74, 0x65, 0x6d, 0x73, 0x12, 0x20, 0x0a, 0x0b, 0x64, 0x65, 0x73, 0x63,
190 | 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x64,
191 | 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x14, 0x0a, 0x05, 0x70, 0x72,
192 | 0x69, 0x63, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x02, 0x52, 0x05, 0x70, 0x72, 0x69, 0x63, 0x65,
193 | 0x12, 0x20, 0x0a, 0x0b, 0x64, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18,
194 | 0x05, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x64, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x61, 0x74, 0x69,
195 | 0x6f, 0x6e, 0x22, 0x66, 0x0a, 0x10, 0x43, 0x6f, 0x6d, 0x62, 0x69, 0x6e, 0x65, 0x64, 0x53, 0x68,
196 | 0x69, 0x70, 0x6d, 0x65, 0x6e, 0x74, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01,
197 | 0x28, 0x09, 0x52, 0x02, 0x69, 0x64, 0x12, 0x16, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73,
198 | 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x2a,
199 | 0x0a, 0x09, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x4c, 0x69, 0x73, 0x74, 0x18, 0x03, 0x20, 0x03, 0x28,
200 | 0x0b, 0x32, 0x0c, 0x2e, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x2e, 0x4f, 0x72, 0x64, 0x65, 0x72, 0x52,
201 | 0x09, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x4c, 0x69, 0x73, 0x74, 0x32, 0xc6, 0x02, 0x0a, 0x0f, 0x4f,
202 | 0x72, 0x64, 0x65, 0x72, 0x4d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x12, 0x36,
203 | 0x0a, 0x08, 0x67, 0x65, 0x74, 0x4f, 0x72, 0x64, 0x65, 0x72, 0x12, 0x1c, 0x2e, 0x67, 0x6f, 0x6f,
204 | 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72,
205 | 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x1a, 0x0c, 0x2e, 0x6f, 0x72, 0x64, 0x65, 0x72,
206 | 0x2e, 0x4f, 0x72, 0x64, 0x65, 0x72, 0x12, 0x36, 0x0a, 0x08, 0x61, 0x64, 0x64, 0x4f, 0x72, 0x64,
207 | 0x65, 0x72, 0x12, 0x0c, 0x2e, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x2e, 0x4f, 0x72, 0x64, 0x65, 0x72,
208 | 0x1a, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62,
209 | 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x3b,
210 | 0x0a, 0x0b, 0x73, 0x65, 0x61, 0x72, 0x63, 0x68, 0x4f, 0x72, 0x64, 0x65, 0x72, 0x12, 0x1c, 0x2e,
211 | 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e,
212 | 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x1a, 0x0c, 0x2e, 0x6f, 0x72,
213 | 0x64, 0x65, 0x72, 0x2e, 0x4f, 0x72, 0x64, 0x65, 0x72, 0x30, 0x01, 0x12, 0x3b, 0x0a, 0x0b, 0x75,
214 | 0x70, 0x64, 0x61, 0x74, 0x65, 0x4f, 0x72, 0x64, 0x65, 0x72, 0x12, 0x0c, 0x2e, 0x6f, 0x72, 0x64,
215 | 0x65, 0x72, 0x2e, 0x4f, 0x72, 0x64, 0x65, 0x72, 0x1a, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c,
216 | 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e,
217 | 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x28, 0x01, 0x12, 0x49, 0x0a, 0x0c, 0x70, 0x72, 0x6f, 0x63,
218 | 0x65, 0x73, 0x73, 0x4f, 0x72, 0x64, 0x65, 0x72, 0x12, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c,
219 | 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e,
220 | 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x1a, 0x17, 0x2e, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x2e, 0x43,
221 | 0x6f, 0x6d, 0x62, 0x69, 0x6e, 0x65, 0x64, 0x53, 0x68, 0x69, 0x70, 0x6d, 0x65, 0x6e, 0x74, 0x28,
222 | 0x01, 0x30, 0x01, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
223 | }
224 |
225 | var (
226 | file_OrderInfo_proto_rawDescOnce sync.Once
227 | file_OrderInfo_proto_rawDescData = file_OrderInfo_proto_rawDesc
228 | )
229 |
230 | func file_OrderInfo_proto_rawDescGZIP() []byte {
231 | file_OrderInfo_proto_rawDescOnce.Do(func() {
232 | file_OrderInfo_proto_rawDescData = protoimpl.X.CompressGZIP(file_OrderInfo_proto_rawDescData)
233 | })
234 | return file_OrderInfo_proto_rawDescData
235 | }
236 |
237 | var file_OrderInfo_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
238 | var file_OrderInfo_proto_goTypes = []interface{}{
239 | (*Order)(nil), // 0: order.Order
240 | (*CombinedShipment)(nil), // 1: order.CombinedShipment
241 | (*wrappers.StringValue)(nil), // 2: google.protobuf.StringValue
242 | }
243 | var file_OrderInfo_proto_depIdxs = []int32{
244 | 0, // 0: order.CombinedShipment.orderList:type_name -> order.Order
245 | 2, // 1: order.OrderManagement.getOrder:input_type -> google.protobuf.StringValue
246 | 0, // 2: order.OrderManagement.addOrder:input_type -> order.Order
247 | 2, // 3: order.OrderManagement.searchOrder:input_type -> google.protobuf.StringValue
248 | 0, // 4: order.OrderManagement.updateOrder:input_type -> order.Order
249 | 2, // 5: order.OrderManagement.processOrder:input_type -> google.protobuf.StringValue
250 | 0, // 6: order.OrderManagement.getOrder:output_type -> order.Order
251 | 2, // 7: order.OrderManagement.addOrder:output_type -> google.protobuf.StringValue
252 | 0, // 8: order.OrderManagement.searchOrder:output_type -> order.Order
253 | 2, // 9: order.OrderManagement.updateOrder:output_type -> google.protobuf.StringValue
254 | 1, // 10: order.OrderManagement.processOrder:output_type -> order.CombinedShipment
255 | 6, // [6:11] is the sub-list for method output_type
256 | 1, // [1:6] is the sub-list for method input_type
257 | 1, // [1:1] is the sub-list for extension type_name
258 | 1, // [1:1] is the sub-list for extension extendee
259 | 0, // [0:1] is the sub-list for field type_name
260 | }
261 |
262 | func init() { file_OrderInfo_proto_init() }
263 | func file_OrderInfo_proto_init() {
264 | if File_OrderInfo_proto != nil {
265 | return
266 | }
267 | if !protoimpl.UnsafeEnabled {
268 | file_OrderInfo_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
269 | switch v := v.(*Order); i {
270 | case 0:
271 | return &v.state
272 | case 1:
273 | return &v.sizeCache
274 | case 2:
275 | return &v.unknownFields
276 | default:
277 | return nil
278 | }
279 | }
280 | file_OrderInfo_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
281 | switch v := v.(*CombinedShipment); i {
282 | case 0:
283 | return &v.state
284 | case 1:
285 | return &v.sizeCache
286 | case 2:
287 | return &v.unknownFields
288 | default:
289 | return nil
290 | }
291 | }
292 | }
293 | type x struct{}
294 | out := protoimpl.TypeBuilder{
295 | File: protoimpl.DescBuilder{
296 | GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
297 | RawDescriptor: file_OrderInfo_proto_rawDesc,
298 | NumEnums: 0,
299 | NumMessages: 2,
300 | NumExtensions: 0,
301 | NumServices: 1,
302 | },
303 | GoTypes: file_OrderInfo_proto_goTypes,
304 | DependencyIndexes: file_OrderInfo_proto_depIdxs,
305 | MessageInfos: file_OrderInfo_proto_msgTypes,
306 | }.Build()
307 | File_OrderInfo_proto = out.File
308 | file_OrderInfo_proto_rawDesc = nil
309 | file_OrderInfo_proto_goTypes = nil
310 | file_OrderInfo_proto_depIdxs = nil
311 | }
312 |
313 | // Reference imports to suppress errors if they are not otherwise used.
314 | var _ context.Context
315 | var _ grpc.ClientConnInterface
316 |
317 | // This is a compile-time assertion to ensure that this generated file
318 | // is compatible with the grpc package it is being compiled against.
319 | const _ = grpc.SupportPackageIsVersion6
320 |
321 | // OrderManagementClient is the client API for OrderManagement service.
322 | //
323 | // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
324 | type OrderManagementClient interface {
325 | //获取订单
326 | GetOrder(ctx context.Context, in *wrappers.StringValue, opts ...grpc.CallOption) (*Order, error)
327 | //添加订单
328 | AddOrder(ctx context.Context, in *Order, opts ...grpc.CallOption) (*wrappers.StringValue, error)
329 | //搜索订单
330 | SearchOrder(ctx context.Context, in *wrappers.StringValue, opts ...grpc.CallOption) (OrderManagement_SearchOrderClient, error)
331 | //更新订单
332 | UpdateOrder(ctx context.Context, opts ...grpc.CallOption) (OrderManagement_UpdateOrderClient, error)
333 | //处理订单
334 | ProcessOrder(ctx context.Context, opts ...grpc.CallOption) (OrderManagement_ProcessOrderClient, error)
335 | }
336 |
337 | type orderManagementClient struct {
338 | cc grpc.ClientConnInterface
339 | }
340 |
341 | func NewOrderManagementClient(cc grpc.ClientConnInterface) OrderManagementClient {
342 | return &orderManagementClient{cc}
343 | }
344 |
345 | func (c *orderManagementClient) GetOrder(ctx context.Context, in *wrappers.StringValue, opts ...grpc.CallOption) (*Order, error) {
346 | out := new(Order)
347 | err := c.cc.Invoke(ctx, "/order.OrderManagement/getOrder", in, out, opts...)
348 | if err != nil {
349 | return nil, err
350 | }
351 | return out, nil
352 | }
353 |
354 | func (c *orderManagementClient) AddOrder(ctx context.Context, in *Order, opts ...grpc.CallOption) (*wrappers.StringValue, error) {
355 | out := new(wrappers.StringValue)
356 | err := c.cc.Invoke(ctx, "/order.OrderManagement/addOrder", in, out, opts...)
357 | if err != nil {
358 | return nil, err
359 | }
360 | return out, nil
361 | }
362 |
363 | func (c *orderManagementClient) SearchOrder(ctx context.Context, in *wrappers.StringValue, opts ...grpc.CallOption) (OrderManagement_SearchOrderClient, error) {
364 | stream, err := c.cc.NewStream(ctx, &_OrderManagement_serviceDesc.Streams[0], "/order.OrderManagement/searchOrder", opts...)
365 | if err != nil {
366 | return nil, err
367 | }
368 | x := &orderManagementSearchOrderClient{stream}
369 | if err := x.ClientStream.SendMsg(in); err != nil {
370 | return nil, err
371 | }
372 | if err := x.ClientStream.CloseSend(); err != nil {
373 | return nil, err
374 | }
375 | return x, nil
376 | }
377 |
378 | type OrderManagement_SearchOrderClient interface {
379 | Recv() (*Order, error)
380 | grpc.ClientStream
381 | }
382 |
383 | type orderManagementSearchOrderClient struct {
384 | grpc.ClientStream
385 | }
386 |
387 | func (x *orderManagementSearchOrderClient) Recv() (*Order, error) {
388 | m := new(Order)
389 | if err := x.ClientStream.RecvMsg(m); err != nil {
390 | return nil, err
391 | }
392 | return m, nil
393 | }
394 |
395 | func (c *orderManagementClient) UpdateOrder(ctx context.Context, opts ...grpc.CallOption) (OrderManagement_UpdateOrderClient, error) {
396 | stream, err := c.cc.NewStream(ctx, &_OrderManagement_serviceDesc.Streams[1], "/order.OrderManagement/updateOrder", opts...)
397 | if err != nil {
398 | return nil, err
399 | }
400 | x := &orderManagementUpdateOrderClient{stream}
401 | return x, nil
402 | }
403 |
404 | type OrderManagement_UpdateOrderClient interface {
405 | Send(*Order) error
406 | CloseAndRecv() (*wrappers.StringValue, error)
407 | grpc.ClientStream
408 | }
409 |
410 | type orderManagementUpdateOrderClient struct {
411 | grpc.ClientStream
412 | }
413 |
414 | func (x *orderManagementUpdateOrderClient) Send(m *Order) error {
415 | return x.ClientStream.SendMsg(m)
416 | }
417 |
418 | func (x *orderManagementUpdateOrderClient) CloseAndRecv() (*wrappers.StringValue, error) {
419 | if err := x.ClientStream.CloseSend(); err != nil {
420 | return nil, err
421 | }
422 | m := new(wrappers.StringValue)
423 | if err := x.ClientStream.RecvMsg(m); err != nil {
424 | return nil, err
425 | }
426 | return m, nil
427 | }
428 |
429 | func (c *orderManagementClient) ProcessOrder(ctx context.Context, opts ...grpc.CallOption) (OrderManagement_ProcessOrderClient, error) {
430 | stream, err := c.cc.NewStream(ctx, &_OrderManagement_serviceDesc.Streams[2], "/order.OrderManagement/processOrder", opts...)
431 | if err != nil {
432 | return nil, err
433 | }
434 | x := &orderManagementProcessOrderClient{stream}
435 | return x, nil
436 | }
437 |
438 | type OrderManagement_ProcessOrderClient interface {
439 | Send(*wrappers.StringValue) error
440 | Recv() (*CombinedShipment, error)
441 | grpc.ClientStream
442 | }
443 |
444 | type orderManagementProcessOrderClient struct {
445 | grpc.ClientStream
446 | }
447 |
448 | func (x *orderManagementProcessOrderClient) Send(m *wrappers.StringValue) error {
449 | return x.ClientStream.SendMsg(m)
450 | }
451 |
452 | func (x *orderManagementProcessOrderClient) Recv() (*CombinedShipment, error) {
453 | m := new(CombinedShipment)
454 | if err := x.ClientStream.RecvMsg(m); err != nil {
455 | return nil, err
456 | }
457 | return m, nil
458 | }
459 |
460 | // OrderManagementServer is the server API for OrderManagement service.
461 | type OrderManagementServer interface {
462 | //获取订单
463 | GetOrder(context.Context, *wrappers.StringValue) (*Order, error)
464 | //添加订单
465 | AddOrder(context.Context, *Order) (*wrappers.StringValue, error)
466 | //搜索订单
467 | SearchOrder(*wrappers.StringValue, OrderManagement_SearchOrderServer) error
468 | //更新订单
469 | UpdateOrder(OrderManagement_UpdateOrderServer) error
470 | //处理订单
471 | ProcessOrder(OrderManagement_ProcessOrderServer) error
472 | }
473 |
474 | // UnimplementedOrderManagementServer can be embedded to have forward compatible implementations.
475 | type UnimplementedOrderManagementServer struct {
476 | }
477 |
478 | func (*UnimplementedOrderManagementServer) GetOrder(context.Context, *wrappers.StringValue) (*Order, error) {
479 | return nil, status.Errorf(codes.Unimplemented, "method GetOrder not implemented")
480 | }
481 | func (*UnimplementedOrderManagementServer) AddOrder(context.Context, *Order) (*wrappers.StringValue, error) {
482 | return nil, status.Errorf(codes.Unimplemented, "method AddOrder not implemented")
483 | }
484 | func (*UnimplementedOrderManagementServer) SearchOrder(*wrappers.StringValue, OrderManagement_SearchOrderServer) error {
485 | return status.Errorf(codes.Unimplemented, "method SearchOrder not implemented")
486 | }
487 | func (*UnimplementedOrderManagementServer) UpdateOrder(OrderManagement_UpdateOrderServer) error {
488 | return status.Errorf(codes.Unimplemented, "method UpdateOrder not implemented")
489 | }
490 | func (*UnimplementedOrderManagementServer) ProcessOrder(OrderManagement_ProcessOrderServer) error {
491 | return status.Errorf(codes.Unimplemented, "method ProcessOrder not implemented")
492 | }
493 |
494 | func RegisterOrderManagementServer(s *grpc.Server, srv OrderManagementServer) {
495 | s.RegisterService(&_OrderManagement_serviceDesc, srv)
496 | }
497 |
498 | func _OrderManagement_GetOrder_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
499 | in := new(wrappers.StringValue)
500 | if err := dec(in); err != nil {
501 | return nil, err
502 | }
503 | if interceptor == nil {
504 | return srv.(OrderManagementServer).GetOrder(ctx, in)
505 | }
506 | info := &grpc.UnaryServerInfo{
507 | Server: srv,
508 | FullMethod: "/order.OrderManagement/GetOrder",
509 | }
510 | handler := func(ctx context.Context, req interface{}) (interface{}, error) {
511 | return srv.(OrderManagementServer).GetOrder(ctx, req.(*wrappers.StringValue))
512 | }
513 | return interceptor(ctx, in, info, handler)
514 | }
515 |
516 | func _OrderManagement_AddOrder_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
517 | in := new(Order)
518 | if err := dec(in); err != nil {
519 | return nil, err
520 | }
521 | if interceptor == nil {
522 | return srv.(OrderManagementServer).AddOrder(ctx, in)
523 | }
524 | info := &grpc.UnaryServerInfo{
525 | Server: srv,
526 | FullMethod: "/order.OrderManagement/AddOrder",
527 | }
528 | handler := func(ctx context.Context, req interface{}) (interface{}, error) {
529 | return srv.(OrderManagementServer).AddOrder(ctx, req.(*Order))
530 | }
531 | return interceptor(ctx, in, info, handler)
532 | }
533 |
534 | func _OrderManagement_SearchOrder_Handler(srv interface{}, stream grpc.ServerStream) error {
535 | m := new(wrappers.StringValue)
536 | if err := stream.RecvMsg(m); err != nil {
537 | return err
538 | }
539 | return srv.(OrderManagementServer).SearchOrder(m, &orderManagementSearchOrderServer{stream})
540 | }
541 |
542 | type OrderManagement_SearchOrderServer interface {
543 | Send(*Order) error
544 | grpc.ServerStream
545 | }
546 |
547 | type orderManagementSearchOrderServer struct {
548 | grpc.ServerStream
549 | }
550 |
551 | func (x *orderManagementSearchOrderServer) Send(m *Order) error {
552 | return x.ServerStream.SendMsg(m)
553 | }
554 |
555 | func _OrderManagement_UpdateOrder_Handler(srv interface{}, stream grpc.ServerStream) error {
556 | return srv.(OrderManagementServer).UpdateOrder(&orderManagementUpdateOrderServer{stream})
557 | }
558 |
559 | type OrderManagement_UpdateOrderServer interface {
560 | SendAndClose(*wrappers.StringValue) error
561 | Recv() (*Order, error)
562 | grpc.ServerStream
563 | }
564 |
565 | type orderManagementUpdateOrderServer struct {
566 | grpc.ServerStream
567 | }
568 |
569 | func (x *orderManagementUpdateOrderServer) SendAndClose(m *wrappers.StringValue) error {
570 | return x.ServerStream.SendMsg(m)
571 | }
572 |
573 | func (x *orderManagementUpdateOrderServer) Recv() (*Order, error) {
574 | m := new(Order)
575 | if err := x.ServerStream.RecvMsg(m); err != nil {
576 | return nil, err
577 | }
578 | return m, nil
579 | }
580 |
581 | func _OrderManagement_ProcessOrder_Handler(srv interface{}, stream grpc.ServerStream) error {
582 | return srv.(OrderManagementServer).ProcessOrder(&orderManagementProcessOrderServer{stream})
583 | }
584 |
585 | type OrderManagement_ProcessOrderServer interface {
586 | Send(*CombinedShipment) error
587 | Recv() (*wrappers.StringValue, error)
588 | grpc.ServerStream
589 | }
590 |
591 | type orderManagementProcessOrderServer struct {
592 | grpc.ServerStream
593 | }
594 |
595 | func (x *orderManagementProcessOrderServer) Send(m *CombinedShipment) error {
596 | return x.ServerStream.SendMsg(m)
597 | }
598 |
599 | func (x *orderManagementProcessOrderServer) Recv() (*wrappers.StringValue, error) {
600 | m := new(wrappers.StringValue)
601 | if err := x.ServerStream.RecvMsg(m); err != nil {
602 | return nil, err
603 | }
604 | return m, nil
605 | }
606 |
607 | var _OrderManagement_serviceDesc = grpc.ServiceDesc{
608 | ServiceName: "order.OrderManagement",
609 | HandlerType: (*OrderManagementServer)(nil),
610 | Methods: []grpc.MethodDesc{
611 | {
612 | MethodName: "getOrder",
613 | Handler: _OrderManagement_GetOrder_Handler,
614 | },
615 | {
616 | MethodName: "addOrder",
617 | Handler: _OrderManagement_AddOrder_Handler,
618 | },
619 | },
620 | Streams: []grpc.StreamDesc{
621 | {
622 | StreamName: "searchOrder",
623 | Handler: _OrderManagement_SearchOrder_Handler,
624 | ServerStreams: true,
625 | },
626 | {
627 | StreamName: "updateOrder",
628 | Handler: _OrderManagement_UpdateOrder_Handler,
629 | ClientStreams: true,
630 | },
631 | {
632 | StreamName: "processOrder",
633 | Handler: _OrderManagement_ProcessOrder_Handler,
634 | ServerStreams: true,
635 | ClientStreams: true,
636 | },
637 | },
638 | Metadata: "OrderInfo.proto",
639 | }
640 |
--------------------------------------------------------------------------------
/order_advance_1/OrderInfo.proto:
--------------------------------------------------------------------------------
1 | syntax = "proto3";
2 | package order;
3 |
4 | import "google/protobuf/wrappers.proto";
5 |
6 | service OrderManagement {
7 | //获取订单
8 | rpc getOrder(google.protobuf.StringValue) returns(Order);
9 | //添加订单
10 | rpc addOrder(Order) returns(google.protobuf.StringValue);
11 | //搜索订单
12 | rpc searchOrder(google.protobuf.StringValue) returns(stream Order);
13 | //更新订单
14 | rpc updateOrder(stream Order) returns(google.protobuf.StringValue);
15 | //处理订单
16 | rpc processOrder(stream google.protobuf.StringValue) returns(stream CombinedShipment);
17 | }
18 |
19 | message Order {
20 | //订单id
21 | string id = 1;
22 | //订单详情
23 | repeated string items = 2;
24 | //订单描述
25 | string description = 3;
26 | //订单价格
27 | float price = 4;
28 | //订单目的地
29 | string destination = 5;
30 | }
31 |
32 | message CombinedShipment {
33 | string id = 1;
34 | string status = 2;
35 | repeated Order orderList = 3;
36 | }
37 |
--------------------------------------------------------------------------------
/order_advance_1/client/interceptor.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "context"
5 | "google.golang.org/grpc"
6 | "log"
7 | )
8 |
9 | //客户端一元拦截器
10 | func UnaryClientOrderInterceptor(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) (err error) {
11 | log.Println("=========[client interceptor] ", method)
12 | err = invoker(ctx, method, req, reply, cc, opts...)
13 | if err != nil {
14 | log.Println("invoke method err.", err)
15 | }
16 | log.Println("=========[client interceptor] end. reply : ", reply)
17 | return
18 | }
19 |
20 | // 客户端流拦截器
21 | type WrappedClientStream struct {
22 | grpc.ClientStream
23 | }
24 |
25 | func (w *WrappedClientStream) SendMsg(m interface{}) error {
26 | log.Printf("===========[client interceptor] send msg : %+v", m)
27 | return w.ClientStream.SendMsg(m)
28 | }
29 |
30 | func (w *WrappedClientStream) RecvMsg(m interface{}) error {
31 | log.Printf("============[client interceptor] recv msg : %+v", m)
32 | return w.ClientStream.RecvMsg(m)
33 | }
34 |
35 | func NewWrappedClientStream(s grpc.ClientStream) *WrappedClientStream {
36 | return &WrappedClientStream{s}
37 | }
38 |
39 | func StreamClientOrderInterceptor(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) {
40 | log.Printf("===========[client msg]start, method = %+v\n", method)
41 | clientStream, err := streamer(ctx, desc, cc, method, opts...)
42 | if err != nil {
43 | return nil, err
44 | }
45 | return NewWrappedClientStream(clientStream), nil
46 | }
47 |
--------------------------------------------------------------------------------
/order_advance_1/client/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "context"
5 | "fmt"
6 | "github.com/golang/protobuf/ptypes/wrappers"
7 | "google.golang.org/grpc"
8 | "grpc-demo/order"
9 | "io"
10 | "log"
11 | "sync"
12 | "time"
13 | )
14 |
15 | const address = "localhost:50051"
16 |
17 | func main() {
18 | conn, err := grpc.Dial(address,
19 | grpc.WithInsecure(),
20 | grpc.WithUnaryInterceptor(UnaryClientOrderInterceptor), //注册拦截器
21 | grpc.WithStreamInterceptor(StreamClientOrderInterceptor),
22 | )
23 | if err != nil {
24 | log.Println("did not connect.", err)
25 | return
26 | }
27 | defer conn.Close()
28 |
29 | // 使用带有截止时间的context
30 | ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(5*time.Second)) //适当调整截止时间观察不同的调用效果
31 | defer cancel()
32 |
33 | client := order.NewOrderManagementClient(conn)
34 | AddOrder(ctx, client)
35 |
36 | //fmt.Println("----------------unary rpc----------------")
37 | //id := AddOrder(ctx, client)
38 | //GetOrder(ctx, client, id)
39 |
40 | fmt.Println("----------request with deadline----------")
41 | chn := make(chan string)
42 | var wg sync.WaitGroup
43 | wg.Add(2)
44 | go func() {
45 | defer func() {
46 | fmt.Println("添加订单成功")
47 | wg.Done()
48 | }()
49 | id := AddOrder(ctx, client)
50 | time.Sleep(1 * time.Second)
51 | chn <- id
52 | }()
53 | go func() {
54 | id := <-chn
55 | time.Sleep(2 * time.Second)
56 | GetOrder(ctx, client, id)
57 | wg.Done()
58 | }()
59 | wg.Wait()
60 |
61 | fmt.Println("-----------cancel rpc request------------")
62 | cancelRpcRequest(client)
63 |
64 | ctx = context.Background()
65 | fmt.Println("-----------server stream rpc-------------")
66 | SearchOrder(ctx, client)
67 |
68 | fmt.Println("------------client stream rpc------------")
69 | UpdateOrder(ctx, client)
70 |
71 | fmt.Println("---------bidirectional stream rpc---------")
72 | ProcessOrder(ctx, client)
73 | }
74 |
75 | //添加一个订单
76 | func AddOrder(ctx context.Context, client order.OrderManagementClient) string {
77 | odr := &order.Order{
78 | Description: "a new order for test-1",
79 | Price: 12322.232,
80 | Destination: "Shanghai",
81 | Items: []string{"doll", "22", "33"},
82 | }
83 |
84 | val, err := client.AddOrder(ctx, odr)
85 | if err != nil {
86 | log.Println("add order fail.", err)
87 | return ""
88 | }
89 | log.Println("add order success.id = ", val.String())
90 | return val.Value
91 | }
92 |
93 | //获取一个订单
94 | func GetOrder(ctx context.Context, client order.OrderManagementClient, id string) {
95 | val, err := client.GetOrder(ctx, &wrappers.StringValue{Value: id})
96 | if err != nil {
97 | log.Println("get order err.", err)
98 | return
99 | }
100 |
101 | log.Printf("get order succes. order = %+v", val)
102 | }
103 |
104 | //搜索订单
105 | func SearchOrder(ctx context.Context, client order.OrderManagementClient) {
106 | searchKey := "Apple"
107 | searchStream, _ := client.SearchOrder(ctx, &wrappers.StringValue{Value: searchKey})
108 | for {
109 | val, err := searchStream.Recv()
110 | if err == io.EOF { //服务端没有数据了
111 | break
112 | }
113 | log.Printf("search order from server : %+v", val)
114 | }
115 | return
116 | }
117 |
118 | //更新订单
119 | func UpdateOrder(ctx context.Context, client order.OrderManagementClient) {
120 | updateStream, _ := client.UpdateOrder(ctx)
121 | order1 := &order.Order{Id: "103", Items: []string{"Apple Watch S6"}, Destination: "San Jose, CA", Price: 4400.00}
122 | order2 := &order.Order{Id: "105", Items: []string{"Amazon Kindle"}, Destination: "San Jose, CA", Price: 330.00}
123 |
124 | //更新订单1
125 | if err := updateStream.Send(order1); err != nil {
126 | log.Println("send order err.", err)
127 | }
128 |
129 | //更新订单2
130 | if err := updateStream.Send(order2); err != nil {
131 | log.Println("send order err.", err)
132 | }
133 |
134 | //关闭流并接收响应
135 | recv, err := updateStream.CloseAndRecv()
136 | if err != nil {
137 | log.Println("close and recv err.", err)
138 | return
139 | }
140 | log.Printf("the update result : %+v", recv)
141 | }
142 |
143 | //处理订单
144 | func ProcessOrder(ctx context.Context, client order.OrderManagementClient) {
145 | processStream, _ := client.ProcessOrder(ctx)
146 |
147 | //发送两个订单处理
148 | if err := processStream.Send(&wrappers.StringValue{Value: "103"}); err != nil {
149 | log.Println("send order err.", err)
150 | }
151 | if err := processStream.Send(&wrappers.StringValue{Value: "105"}); err != nil {
152 | log.Println("send order err.", err)
153 | }
154 |
155 | chn := make(chan struct{})
156 | //异步接收服务端的结果
157 | go processResultFromServer(processStream, chn)
158 |
159 | //再发送一个订单
160 | if err := processStream.Send(&wrappers.StringValue{Value: "106"}); err != nil {
161 | log.Println("send order err.", err)
162 | }
163 | //发送完毕后记得关闭
164 | if err := processStream.CloseSend(); err != nil {
165 | log.Println("close send err.", err)
166 | }
167 |
168 | <-chn
169 | }
170 |
171 | //从服务端获取处理的结果
172 | func processResultFromServer(stream order.OrderManagement_ProcessOrderClient, chn chan struct{}) {
173 | defer close(chn)
174 | for {
175 | shipment, err := stream.Recv()
176 | if err == io.EOF {
177 | log.Println("[client]结束从服务端接收数据")
178 | break
179 | }
180 | log.Printf("[client]server process result : %+v\n", shipment)
181 | }
182 | }
183 |
184 | // 取消RPC请求
185 | func cancelRpcRequest(client order.OrderManagementClient) {
186 | ctx, cancelFunc := context.WithCancel(context.Background())
187 | done := make(chan string)
188 | go func() {
189 | var id string
190 | defer func() {
191 | fmt.Println("结束执行, id = ", id)
192 | done <- id
193 | }()
194 |
195 | time.Sleep(2 * time.Second)
196 | id = AddOrder(ctx, client)
197 | log.Println("添加订单成功, id = ", id)
198 | }()
199 |
200 | //等待一秒后取消
201 | time.Sleep(time.Second)
202 | cancelFunc()
203 |
204 | <-done
205 | }
206 |
--------------------------------------------------------------------------------
/order_advance_1/server/interceptor.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "context"
5 | "google.golang.org/grpc"
6 | "log"
7 | )
8 |
9 | // 一元拦截器
10 | func orderUnaryServerInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo,
11 | handler grpc.UnaryHandler) (res interface{}, err error) {
12 | //前置处理
13 | log.Println("==========[Server Unary Interceptor]===========", info.FullMethod)
14 |
15 | //完成方法的正常执行
16 | res, err = handler(ctx, req)
17 |
18 | //后置处理
19 | log.Printf("After method call, res = %+v\n", res)
20 | return
21 | }
22 |
23 | // 服务端流拦截器
24 | type WrappedServerStream struct {
25 | grpc.ServerStream
26 | }
27 |
28 | func (w *WrappedServerStream) SendMsg(m interface{}) error {
29 | log.Printf("[order stream server interceptor] send a msg : %+v", m)
30 | return w.ServerStream.SendMsg(m)
31 | }
32 |
33 | func (w *WrappedServerStream) RecvMsg(m interface{}) error {
34 | log.Printf("[order stream server interceptor] recv a msg : %+v", m)
35 | return w.ServerStream.RecvMsg(m)
36 | }
37 |
38 | func NewWrappedServerStream(s grpc.ServerStream) *WrappedServerStream {
39 | return &WrappedServerStream{s}
40 | }
41 |
42 | func orderStreamServerInterceptor(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
43 | log.Printf("=========[order stream]start %s\n", info.FullMethod)
44 |
45 | //执行方法
46 | err := handler(srv, NewWrappedServerStream(ss))
47 | if err != nil {
48 | log.Println("handle method err.", err)
49 | }
50 |
51 | log.Printf("=========[order stream]end")
52 | return nil
53 | }
54 |
--------------------------------------------------------------------------------
/order_advance_1/server/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "context"
5 | "github.com/gofrs/uuid"
6 | "github.com/golang/protobuf/ptypes/wrappers"
7 | "google.golang.org/grpc"
8 | "google.golang.org/grpc/codes"
9 | "google.golang.org/grpc/status"
10 | "grpc-demo/order"
11 | "io"
12 | "log"
13 | "net"
14 | "strings"
15 | )
16 |
17 | const port = ":50051"
18 |
19 | //初始化添加一些订单数据
20 | func initSampleData(orderMap map[string]*order.Order) {
21 | orderMap["102"] = &order.Order{Id: "102", Items: []string{"Google Pixel 3A", "Mac Book Pro"}, Destination: "Mountain View, CA", Price: 1800.00}
22 | orderMap["103"] = &order.Order{Id: "103", Items: []string{"Apple Watch S4"}, Destination: "San Jose, CA", Price: 400.00}
23 | orderMap["104"] = &order.Order{Id: "104", Items: []string{"Google Home Mini", "Google Nest Hub"}, Destination: "Mountain View, CA", Price: 400.00}
24 | orderMap["105"] = &order.Order{Id: "105", Items: []string{"Amazon Echo"}, Destination: "San Jose, CA", Price: 30.00}
25 | orderMap["106"] = &order.Order{Id: "106", Items: []string{"Amazon Echo", "Apple iPhone XS"}, Destination: "Mountain View, CA", Price: 300.00}
26 | }
27 |
28 | func main() {
29 | server := &server{orderMap: make(map[string]*order.Order)}
30 | initSampleData(server.orderMap)
31 |
32 | listener, err := net.Listen("tcp", port)
33 | if err != nil {
34 | log.Println("net listen err ", err)
35 | return
36 | }
37 |
38 | // 注册拦截器
39 | s := grpc.NewServer(
40 | grpc.UnaryInterceptor(orderUnaryServerInterceptor),
41 | grpc.StreamInterceptor(orderStreamServerInterceptor),
42 | )
43 | order.RegisterOrderManagementServer(s, server)
44 | log.Println("start gRPC listen on port " + port)
45 | if err := s.Serve(listener); err != nil {
46 | log.Println("failed to serve...", err)
47 | return
48 | }
49 | }
50 |
51 | type server struct {
52 | orderMap map[string]*order.Order
53 | }
54 |
55 | //获取订单
56 | func (s *server) GetOrder(ctx context.Context, req *wrappers.StringValue) (resp *order.Order, err error) {
57 | resp = &order.Order{}
58 | id := req.Value
59 | var exist bool
60 | if resp, exist = s.orderMap[id]; !exist {
61 | err = status.Error(codes.NotFound, "order not found id = "+id)
62 | return
63 | }
64 | return
65 | }
66 |
67 | //添加订单
68 | func (s *server) AddOrder(ctx context.Context, req *order.Order) (resp *wrappers.StringValue, err error) {
69 | resp = &wrappers.StringValue{}
70 | if s.orderMap == nil {
71 | s.orderMap = make(map[string]*order.Order)
72 | }
73 |
74 | v4, err := uuid.NewV4()
75 | if err != nil {
76 | return resp, status.Errorf(codes.Internal, "gen uuid err", err)
77 | }
78 | id := v4.String()
79 | req.Id = id
80 | s.orderMap[id] = req
81 |
82 | resp.Value = id
83 | return
84 | }
85 |
86 | //搜索订单
87 | func (s *server) SearchOrder(searchKey *wrappers.StringValue, stream order.OrderManagement_SearchOrderServer) (err error) {
88 | for _, val := range s.orderMap {
89 | for _, item := range val.Items {
90 | if strings.Contains(item, searchKey.Value) {
91 | err = stream.Send(val)
92 | if err != nil {
93 | log.Println("stream send order err.", err)
94 | return
95 | }
96 | break
97 | }
98 | }
99 | }
100 | return
101 | }
102 |
103 | //更新订单
104 | func (s *server) UpdateOrder(stream order.OrderManagement_UpdateOrderServer) (err error) {
105 | updatedIds := "updated order ids : "
106 | for {
107 | val, err := stream.Recv()
108 | if err == io.EOF { //完成读取订单流
109 | //向客户端发送消息
110 | return stream.SendAndClose(&wrappers.StringValue{Value: updatedIds})
111 | }
112 | s.orderMap[val.Id] = val
113 | log.Println("[server]update the order : ", val.Id)
114 | updatedIds += val.Id + ", "
115 | }
116 | }
117 |
118 | //处理订单
119 | func (s *server) ProcessOrder(stream order.OrderManagement_ProcessOrderServer) (err error) {
120 | var combinedShipmentMap = make(map[string]*order.CombinedShipment)
121 | for {
122 | val, err := stream.Recv() //接收从客户端发送来的订单
123 | if err == io.EOF { //接收完毕,返回结果
124 | for _, shipment := range combinedShipmentMap {
125 | if err := stream.Send(shipment); err != nil {
126 | log.Println("[server] process finished!")
127 | return err
128 | }
129 | }
130 | break
131 | }
132 | if err != nil {
133 | log.Println(err)
134 | break
135 | }
136 |
137 | if val != nil {
138 | orderId := val.Value
139 | log.Printf("[server]reading order : %+v\n", orderId)
140 |
141 | dest := s.orderMap[orderId].Destination
142 | shipment, exist := combinedShipmentMap[dest]
143 | if exist {
144 | ord := s.orderMap[orderId]
145 | shipment.OrderList = append(shipment.OrderList, ord)
146 | combinedShipmentMap[dest] = shipment
147 | } else {
148 | comShip := &order.CombinedShipment{Id: "cmb - " + (s.orderMap[orderId].Destination), Status: "Processed!"}
149 | ord := s.orderMap[orderId]
150 | comShip.OrderList = append(comShip.OrderList, ord)
151 | combinedShipmentMap[dest] = comShip
152 | log.Println(len(comShip.OrderList), comShip.GetId())
153 | }
154 | }
155 | }
156 | return
157 | }
158 |
--------------------------------------------------------------------------------
/order_advance_2/Echo.pb.go:
--------------------------------------------------------------------------------
1 | // Code generated by protoc-gen-go. DO NOT EDIT.
2 | // versions:
3 | // protoc-gen-go v1.25.0
4 | // protoc v3.13.0
5 | // source: Echo.proto
6 |
7 | package order
8 |
9 | import (
10 | context "context"
11 | proto "github.com/golang/protobuf/proto"
12 | _ "github.com/golang/protobuf/ptypes/wrappers"
13 | grpc "google.golang.org/grpc"
14 | codes "google.golang.org/grpc/codes"
15 | status "google.golang.org/grpc/status"
16 | protoreflect "google.golang.org/protobuf/reflect/protoreflect"
17 | protoimpl "google.golang.org/protobuf/runtime/protoimpl"
18 | reflect "reflect"
19 | sync "sync"
20 | )
21 |
22 | const (
23 | // Verify that this generated code is sufficiently up-to-date.
24 | _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
25 | // Verify that runtime/protoimpl is sufficiently up-to-date.
26 | _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
27 | )
28 |
29 | // This is a compile-time assertion that a sufficiently up-to-date version
30 | // of the legacy proto package is being used.
31 | const _ = proto.ProtoPackageIsVersion4
32 |
33 | type EchoReq struct {
34 | state protoimpl.MessageState
35 | sizeCache protoimpl.SizeCache
36 | unknownFields protoimpl.UnknownFields
37 |
38 | Message string `protobuf:"bytes,1,opt,name=message,proto3" json:"message,omitempty"`
39 | }
40 |
41 | func (x *EchoReq) Reset() {
42 | *x = EchoReq{}
43 | if protoimpl.UnsafeEnabled {
44 | mi := &file_Echo_proto_msgTypes[0]
45 | ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
46 | ms.StoreMessageInfo(mi)
47 | }
48 | }
49 |
50 | func (x *EchoReq) String() string {
51 | return protoimpl.X.MessageStringOf(x)
52 | }
53 |
54 | func (*EchoReq) ProtoMessage() {}
55 |
56 | func (x *EchoReq) ProtoReflect() protoreflect.Message {
57 | mi := &file_Echo_proto_msgTypes[0]
58 | if protoimpl.UnsafeEnabled && x != nil {
59 | ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
60 | if ms.LoadMessageInfo() == nil {
61 | ms.StoreMessageInfo(mi)
62 | }
63 | return ms
64 | }
65 | return mi.MessageOf(x)
66 | }
67 |
68 | // Deprecated: Use EchoReq.ProtoReflect.Descriptor instead.
69 | func (*EchoReq) Descriptor() ([]byte, []int) {
70 | return file_Echo_proto_rawDescGZIP(), []int{0}
71 | }
72 |
73 | func (x *EchoReq) GetMessage() string {
74 | if x != nil {
75 | return x.Message
76 | }
77 | return ""
78 | }
79 |
80 | type EchoResp struct {
81 | state protoimpl.MessageState
82 | sizeCache protoimpl.SizeCache
83 | unknownFields protoimpl.UnknownFields
84 |
85 | Message string `protobuf:"bytes,1,opt,name=message,proto3" json:"message,omitempty"`
86 | Addr string `protobuf:"bytes,2,opt,name=addr,proto3" json:"addr,omitempty"`
87 | }
88 |
89 | func (x *EchoResp) Reset() {
90 | *x = EchoResp{}
91 | if protoimpl.UnsafeEnabled {
92 | mi := &file_Echo_proto_msgTypes[1]
93 | ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
94 | ms.StoreMessageInfo(mi)
95 | }
96 | }
97 |
98 | func (x *EchoResp) String() string {
99 | return protoimpl.X.MessageStringOf(x)
100 | }
101 |
102 | func (*EchoResp) ProtoMessage() {}
103 |
104 | func (x *EchoResp) ProtoReflect() protoreflect.Message {
105 | mi := &file_Echo_proto_msgTypes[1]
106 | if protoimpl.UnsafeEnabled && x != nil {
107 | ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
108 | if ms.LoadMessageInfo() == nil {
109 | ms.StoreMessageInfo(mi)
110 | }
111 | return ms
112 | }
113 | return mi.MessageOf(x)
114 | }
115 |
116 | // Deprecated: Use EchoResp.ProtoReflect.Descriptor instead.
117 | func (*EchoResp) Descriptor() ([]byte, []int) {
118 | return file_Echo_proto_rawDescGZIP(), []int{1}
119 | }
120 |
121 | func (x *EchoResp) GetMessage() string {
122 | if x != nil {
123 | return x.Message
124 | }
125 | return ""
126 | }
127 |
128 | func (x *EchoResp) GetAddr() string {
129 | if x != nil {
130 | return x.Addr
131 | }
132 | return ""
133 | }
134 |
135 | var File_Echo_proto protoreflect.FileDescriptor
136 |
137 | var file_Echo_proto_rawDesc = []byte{
138 | 0x0a, 0x0a, 0x45, 0x63, 0x68, 0x6f, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x05, 0x6f, 0x72,
139 | 0x64, 0x65, 0x72, 0x1a, 0x1e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74,
140 | 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x77, 0x72, 0x61, 0x70, 0x70, 0x65, 0x72, 0x73, 0x2e, 0x70, 0x72,
141 | 0x6f, 0x74, 0x6f, 0x22, 0x23, 0x0a, 0x07, 0x65, 0x63, 0x68, 0x6f, 0x52, 0x65, 0x71, 0x12, 0x18,
142 | 0x0a, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52,
143 | 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x22, 0x38, 0x0a, 0x08, 0x65, 0x63, 0x68, 0x6f,
144 | 0x52, 0x65, 0x73, 0x70, 0x12, 0x18, 0x0a, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18,
145 | 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x12, 0x12,
146 | 0x0a, 0x04, 0x61, 0x64, 0x64, 0x72, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x61, 0x64,
147 | 0x64, 0x72, 0x32, 0x3b, 0x0a, 0x0b, 0x45, 0x63, 0x68, 0x6f, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63,
148 | 0x65, 0x12, 0x2c, 0x0a, 0x09, 0x75, 0x6e, 0x61, 0x72, 0x79, 0x45, 0x63, 0x68, 0x6f, 0x12, 0x0e,
149 | 0x2e, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x2e, 0x65, 0x63, 0x68, 0x6f, 0x52, 0x65, 0x71, 0x1a, 0x0f,
150 | 0x2e, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x2e, 0x65, 0x63, 0x68, 0x6f, 0x52, 0x65, 0x73, 0x70, 0x62,
151 | 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
152 | }
153 |
154 | var (
155 | file_Echo_proto_rawDescOnce sync.Once
156 | file_Echo_proto_rawDescData = file_Echo_proto_rawDesc
157 | )
158 |
159 | func file_Echo_proto_rawDescGZIP() []byte {
160 | file_Echo_proto_rawDescOnce.Do(func() {
161 | file_Echo_proto_rawDescData = protoimpl.X.CompressGZIP(file_Echo_proto_rawDescData)
162 | })
163 | return file_Echo_proto_rawDescData
164 | }
165 |
166 | var file_Echo_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
167 | var file_Echo_proto_goTypes = []interface{}{
168 | (*EchoReq)(nil), // 0: order.echoReq
169 | (*EchoResp)(nil), // 1: order.echoResp
170 | }
171 | var file_Echo_proto_depIdxs = []int32{
172 | 0, // 0: order.EchoService.unaryEcho:input_type -> order.echoReq
173 | 1, // 1: order.EchoService.unaryEcho:output_type -> order.echoResp
174 | 1, // [1:2] is the sub-list for method output_type
175 | 0, // [0:1] is the sub-list for method input_type
176 | 0, // [0:0] is the sub-list for extension type_name
177 | 0, // [0:0] is the sub-list for extension extendee
178 | 0, // [0:0] is the sub-list for field type_name
179 | }
180 |
181 | func init() { file_Echo_proto_init() }
182 | func file_Echo_proto_init() {
183 | if File_Echo_proto != nil {
184 | return
185 | }
186 | if !protoimpl.UnsafeEnabled {
187 | file_Echo_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
188 | switch v := v.(*EchoReq); i {
189 | case 0:
190 | return &v.state
191 | case 1:
192 | return &v.sizeCache
193 | case 2:
194 | return &v.unknownFields
195 | default:
196 | return nil
197 | }
198 | }
199 | file_Echo_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
200 | switch v := v.(*EchoResp); i {
201 | case 0:
202 | return &v.state
203 | case 1:
204 | return &v.sizeCache
205 | case 2:
206 | return &v.unknownFields
207 | default:
208 | return nil
209 | }
210 | }
211 | }
212 | type x struct{}
213 | out := protoimpl.TypeBuilder{
214 | File: protoimpl.DescBuilder{
215 | GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
216 | RawDescriptor: file_Echo_proto_rawDesc,
217 | NumEnums: 0,
218 | NumMessages: 2,
219 | NumExtensions: 0,
220 | NumServices: 1,
221 | },
222 | GoTypes: file_Echo_proto_goTypes,
223 | DependencyIndexes: file_Echo_proto_depIdxs,
224 | MessageInfos: file_Echo_proto_msgTypes,
225 | }.Build()
226 | File_Echo_proto = out.File
227 | file_Echo_proto_rawDesc = nil
228 | file_Echo_proto_goTypes = nil
229 | file_Echo_proto_depIdxs = nil
230 | }
231 |
232 | // Reference imports to suppress errors if they are not otherwise used.
233 | var _ context.Context
234 | var _ grpc.ClientConnInterface
235 |
236 | // This is a compile-time assertion to ensure that this generated file
237 | // is compatible with the grpc package it is being compiled against.
238 | const _ = grpc.SupportPackageIsVersion6
239 |
240 | // EchoServiceClient is the client API for EchoService service.
241 | //
242 | // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
243 | type EchoServiceClient interface {
244 | UnaryEcho(ctx context.Context, in *EchoReq, opts ...grpc.CallOption) (*EchoResp, error)
245 | }
246 |
247 | type echoServiceClient struct {
248 | cc grpc.ClientConnInterface
249 | }
250 |
251 | func NewEchoServiceClient(cc grpc.ClientConnInterface) EchoServiceClient {
252 | return &echoServiceClient{cc}
253 | }
254 |
255 | func (c *echoServiceClient) UnaryEcho(ctx context.Context, in *EchoReq, opts ...grpc.CallOption) (*EchoResp, error) {
256 | out := new(EchoResp)
257 | err := c.cc.Invoke(ctx, "/order.EchoService/unaryEcho", in, out, opts...)
258 | if err != nil {
259 | return nil, err
260 | }
261 | return out, nil
262 | }
263 |
264 | // EchoServiceServer is the server API for EchoService service.
265 | type EchoServiceServer interface {
266 | UnaryEcho(context.Context, *EchoReq) (*EchoResp, error)
267 | }
268 |
269 | // UnimplementedEchoServiceServer can be embedded to have forward compatible implementations.
270 | type UnimplementedEchoServiceServer struct {
271 | }
272 |
273 | func (*UnimplementedEchoServiceServer) UnaryEcho(context.Context, *EchoReq) (*EchoResp, error) {
274 | return nil, status.Errorf(codes.Unimplemented, "method UnaryEcho not implemented")
275 | }
276 |
277 | func RegisterEchoServiceServer(s *grpc.Server, srv EchoServiceServer) {
278 | s.RegisterService(&_EchoService_serviceDesc, srv)
279 | }
280 |
281 | func _EchoService_UnaryEcho_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
282 | in := new(EchoReq)
283 | if err := dec(in); err != nil {
284 | return nil, err
285 | }
286 | if interceptor == nil {
287 | return srv.(EchoServiceServer).UnaryEcho(ctx, in)
288 | }
289 | info := &grpc.UnaryServerInfo{
290 | Server: srv,
291 | FullMethod: "/order.EchoService/UnaryEcho",
292 | }
293 | handler := func(ctx context.Context, req interface{}) (interface{}, error) {
294 | return srv.(EchoServiceServer).UnaryEcho(ctx, req.(*EchoReq))
295 | }
296 | return interceptor(ctx, in, info, handler)
297 | }
298 |
299 | var _EchoService_serviceDesc = grpc.ServiceDesc{
300 | ServiceName: "order.EchoService",
301 | HandlerType: (*EchoServiceServer)(nil),
302 | Methods: []grpc.MethodDesc{
303 | {
304 | MethodName: "unaryEcho",
305 | Handler: _EchoService_UnaryEcho_Handler,
306 | },
307 | },
308 | Streams: []grpc.StreamDesc{},
309 | Metadata: "Echo.proto",
310 | }
311 |
--------------------------------------------------------------------------------
/order_advance_2/Echo.proto:
--------------------------------------------------------------------------------
1 | syntax = "proto3";
2 | package order;
3 |
4 | import "google/protobuf/wrappers.proto";
5 |
6 | service EchoService {
7 | rpc unaryEcho(echoReq) returns(echoResp);
8 | }
9 |
10 | message echoReq {
11 | string message = 1;
12 | }
13 |
14 | message echoResp {
15 | string message = 1;
16 | string addr = 2;
17 | }
18 |
--------------------------------------------------------------------------------
/order_advance_2/OrderInfo.pb.go:
--------------------------------------------------------------------------------
1 | // Code generated by protoc-gen-go. DO NOT EDIT.
2 | // versions:
3 | // protoc-gen-go v1.25.0
4 | // protoc v3.13.0
5 | // source: OrderInfo.proto
6 |
7 | package order
8 |
9 | import (
10 | context "context"
11 | proto "github.com/golang/protobuf/proto"
12 | wrappers "github.com/golang/protobuf/ptypes/wrappers"
13 | grpc "google.golang.org/grpc"
14 | codes "google.golang.org/grpc/codes"
15 | status "google.golang.org/grpc/status"
16 | protoreflect "google.golang.org/protobuf/reflect/protoreflect"
17 | protoimpl "google.golang.org/protobuf/runtime/protoimpl"
18 | reflect "reflect"
19 | sync "sync"
20 | )
21 |
22 | const (
23 | // Verify that this generated code is sufficiently up-to-date.
24 | _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
25 | // Verify that runtime/protoimpl is sufficiently up-to-date.
26 | _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
27 | )
28 |
29 | // This is a compile-time assertion that a sufficiently up-to-date version
30 | // of the legacy proto package is being used.
31 | const _ = proto.ProtoPackageIsVersion4
32 |
33 | type Order struct {
34 | state protoimpl.MessageState
35 | sizeCache protoimpl.SizeCache
36 | unknownFields protoimpl.UnknownFields
37 |
38 | //订单id
39 | Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
40 | //订单详情
41 | Items []string `protobuf:"bytes,2,rep,name=items,proto3" json:"items,omitempty"`
42 | //订单描述
43 | Description string `protobuf:"bytes,3,opt,name=description,proto3" json:"description,omitempty"`
44 | //订单价格
45 | Price float32 `protobuf:"fixed32,4,opt,name=price,proto3" json:"price,omitempty"`
46 | //订单目的地
47 | Destination string `protobuf:"bytes,5,opt,name=destination,proto3" json:"destination,omitempty"`
48 | }
49 |
50 | func (x *Order) Reset() {
51 | *x = Order{}
52 | if protoimpl.UnsafeEnabled {
53 | mi := &file_OrderInfo_proto_msgTypes[0]
54 | ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
55 | ms.StoreMessageInfo(mi)
56 | }
57 | }
58 |
59 | func (x *Order) String() string {
60 | return protoimpl.X.MessageStringOf(x)
61 | }
62 |
63 | func (*Order) ProtoMessage() {}
64 |
65 | func (x *Order) ProtoReflect() protoreflect.Message {
66 | mi := &file_OrderInfo_proto_msgTypes[0]
67 | if protoimpl.UnsafeEnabled && x != nil {
68 | ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
69 | if ms.LoadMessageInfo() == nil {
70 | ms.StoreMessageInfo(mi)
71 | }
72 | return ms
73 | }
74 | return mi.MessageOf(x)
75 | }
76 |
77 | // Deprecated: Use Order.ProtoReflect.Descriptor instead.
78 | func (*Order) Descriptor() ([]byte, []int) {
79 | return file_OrderInfo_proto_rawDescGZIP(), []int{0}
80 | }
81 |
82 | func (x *Order) GetId() string {
83 | if x != nil {
84 | return x.Id
85 | }
86 | return ""
87 | }
88 |
89 | func (x *Order) GetItems() []string {
90 | if x != nil {
91 | return x.Items
92 | }
93 | return nil
94 | }
95 |
96 | func (x *Order) GetDescription() string {
97 | if x != nil {
98 | return x.Description
99 | }
100 | return ""
101 | }
102 |
103 | func (x *Order) GetPrice() float32 {
104 | if x != nil {
105 | return x.Price
106 | }
107 | return 0
108 | }
109 |
110 | func (x *Order) GetDestination() string {
111 | if x != nil {
112 | return x.Destination
113 | }
114 | return ""
115 | }
116 |
117 | type CombinedShipment struct {
118 | state protoimpl.MessageState
119 | sizeCache protoimpl.SizeCache
120 | unknownFields protoimpl.UnknownFields
121 |
122 | Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
123 | Status string `protobuf:"bytes,2,opt,name=status,proto3" json:"status,omitempty"`
124 | OrderList []*Order `protobuf:"bytes,3,rep,name=orderList,proto3" json:"orderList,omitempty"`
125 | }
126 |
127 | func (x *CombinedShipment) Reset() {
128 | *x = CombinedShipment{}
129 | if protoimpl.UnsafeEnabled {
130 | mi := &file_OrderInfo_proto_msgTypes[1]
131 | ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
132 | ms.StoreMessageInfo(mi)
133 | }
134 | }
135 |
136 | func (x *CombinedShipment) String() string {
137 | return protoimpl.X.MessageStringOf(x)
138 | }
139 |
140 | func (*CombinedShipment) ProtoMessage() {}
141 |
142 | func (x *CombinedShipment) ProtoReflect() protoreflect.Message {
143 | mi := &file_OrderInfo_proto_msgTypes[1]
144 | if protoimpl.UnsafeEnabled && x != nil {
145 | ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
146 | if ms.LoadMessageInfo() == nil {
147 | ms.StoreMessageInfo(mi)
148 | }
149 | return ms
150 | }
151 | return mi.MessageOf(x)
152 | }
153 |
154 | // Deprecated: Use CombinedShipment.ProtoReflect.Descriptor instead.
155 | func (*CombinedShipment) Descriptor() ([]byte, []int) {
156 | return file_OrderInfo_proto_rawDescGZIP(), []int{1}
157 | }
158 |
159 | func (x *CombinedShipment) GetId() string {
160 | if x != nil {
161 | return x.Id
162 | }
163 | return ""
164 | }
165 |
166 | func (x *CombinedShipment) GetStatus() string {
167 | if x != nil {
168 | return x.Status
169 | }
170 | return ""
171 | }
172 |
173 | func (x *CombinedShipment) GetOrderList() []*Order {
174 | if x != nil {
175 | return x.OrderList
176 | }
177 | return nil
178 | }
179 |
180 | var File_OrderInfo_proto protoreflect.FileDescriptor
181 |
182 | var file_OrderInfo_proto_rawDesc = []byte{
183 | 0x0a, 0x0f, 0x4f, 0x72, 0x64, 0x65, 0x72, 0x49, 0x6e, 0x66, 0x6f, 0x2e, 0x70, 0x72, 0x6f, 0x74,
184 | 0x6f, 0x12, 0x05, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x1a, 0x1e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65,
185 | 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x77, 0x72, 0x61, 0x70, 0x70, 0x65,
186 | 0x72, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x87, 0x01, 0x0a, 0x05, 0x4f, 0x72, 0x64,
187 | 0x65, 0x72, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x02,
188 | 0x69, 0x64, 0x12, 0x14, 0x0a, 0x05, 0x69, 0x74, 0x65, 0x6d, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28,
189 | 0x09, 0x52, 0x05, 0x69, 0x74, 0x65, 0x6d, 0x73, 0x12, 0x20, 0x0a, 0x0b, 0x64, 0x65, 0x73, 0x63,
190 | 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x64,
191 | 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x14, 0x0a, 0x05, 0x70, 0x72,
192 | 0x69, 0x63, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x02, 0x52, 0x05, 0x70, 0x72, 0x69, 0x63, 0x65,
193 | 0x12, 0x20, 0x0a, 0x0b, 0x64, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18,
194 | 0x05, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x64, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x61, 0x74, 0x69,
195 | 0x6f, 0x6e, 0x22, 0x66, 0x0a, 0x10, 0x43, 0x6f, 0x6d, 0x62, 0x69, 0x6e, 0x65, 0x64, 0x53, 0x68,
196 | 0x69, 0x70, 0x6d, 0x65, 0x6e, 0x74, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01,
197 | 0x28, 0x09, 0x52, 0x02, 0x69, 0x64, 0x12, 0x16, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73,
198 | 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x2a,
199 | 0x0a, 0x09, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x4c, 0x69, 0x73, 0x74, 0x18, 0x03, 0x20, 0x03, 0x28,
200 | 0x0b, 0x32, 0x0c, 0x2e, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x2e, 0x4f, 0x72, 0x64, 0x65, 0x72, 0x52,
201 | 0x09, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x4c, 0x69, 0x73, 0x74, 0x32, 0xc6, 0x02, 0x0a, 0x0f, 0x4f,
202 | 0x72, 0x64, 0x65, 0x72, 0x4d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x12, 0x36,
203 | 0x0a, 0x08, 0x67, 0x65, 0x74, 0x4f, 0x72, 0x64, 0x65, 0x72, 0x12, 0x1c, 0x2e, 0x67, 0x6f, 0x6f,
204 | 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72,
205 | 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x1a, 0x0c, 0x2e, 0x6f, 0x72, 0x64, 0x65, 0x72,
206 | 0x2e, 0x4f, 0x72, 0x64, 0x65, 0x72, 0x12, 0x36, 0x0a, 0x08, 0x61, 0x64, 0x64, 0x4f, 0x72, 0x64,
207 | 0x65, 0x72, 0x12, 0x0c, 0x2e, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x2e, 0x4f, 0x72, 0x64, 0x65, 0x72,
208 | 0x1a, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62,
209 | 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x3b,
210 | 0x0a, 0x0b, 0x73, 0x65, 0x61, 0x72, 0x63, 0x68, 0x4f, 0x72, 0x64, 0x65, 0x72, 0x12, 0x1c, 0x2e,
211 | 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e,
212 | 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x1a, 0x0c, 0x2e, 0x6f, 0x72,
213 | 0x64, 0x65, 0x72, 0x2e, 0x4f, 0x72, 0x64, 0x65, 0x72, 0x30, 0x01, 0x12, 0x3b, 0x0a, 0x0b, 0x75,
214 | 0x70, 0x64, 0x61, 0x74, 0x65, 0x4f, 0x72, 0x64, 0x65, 0x72, 0x12, 0x0c, 0x2e, 0x6f, 0x72, 0x64,
215 | 0x65, 0x72, 0x2e, 0x4f, 0x72, 0x64, 0x65, 0x72, 0x1a, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c,
216 | 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e,
217 | 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x28, 0x01, 0x12, 0x49, 0x0a, 0x0c, 0x70, 0x72, 0x6f, 0x63,
218 | 0x65, 0x73, 0x73, 0x4f, 0x72, 0x64, 0x65, 0x72, 0x12, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c,
219 | 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e,
220 | 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x1a, 0x17, 0x2e, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x2e, 0x43,
221 | 0x6f, 0x6d, 0x62, 0x69, 0x6e, 0x65, 0x64, 0x53, 0x68, 0x69, 0x70, 0x6d, 0x65, 0x6e, 0x74, 0x28,
222 | 0x01, 0x30, 0x01, 0x32, 0x58, 0x0a, 0x0e, 0x47, 0x72, 0x65, 0x65, 0x74, 0x65, 0x72, 0x53, 0x65,
223 | 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x46, 0x0a, 0x08, 0x73, 0x61, 0x79, 0x48, 0x65, 0x6c, 0x6c,
224 | 0x6f, 0x12, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f,
225 | 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x1a,
226 | 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75,
227 | 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x62, 0x06, 0x70,
228 | 0x72, 0x6f, 0x74, 0x6f, 0x33,
229 | }
230 |
231 | var (
232 | file_OrderInfo_proto_rawDescOnce sync.Once
233 | file_OrderInfo_proto_rawDescData = file_OrderInfo_proto_rawDesc
234 | )
235 |
236 | func file_OrderInfo_proto_rawDescGZIP() []byte {
237 | file_OrderInfo_proto_rawDescOnce.Do(func() {
238 | file_OrderInfo_proto_rawDescData = protoimpl.X.CompressGZIP(file_OrderInfo_proto_rawDescData)
239 | })
240 | return file_OrderInfo_proto_rawDescData
241 | }
242 |
243 | var file_OrderInfo_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
244 | var file_OrderInfo_proto_goTypes = []interface{}{
245 | (*Order)(nil), // 0: order.Order
246 | (*CombinedShipment)(nil), // 1: order.CombinedShipment
247 | (*wrappers.StringValue)(nil), // 2: google.protobuf.StringValue
248 | }
249 | var file_OrderInfo_proto_depIdxs = []int32{
250 | 0, // 0: order.CombinedShipment.orderList:type_name -> order.Order
251 | 2, // 1: order.OrderManagement.getOrder:input_type -> google.protobuf.StringValue
252 | 0, // 2: order.OrderManagement.addOrder:input_type -> order.Order
253 | 2, // 3: order.OrderManagement.searchOrder:input_type -> google.protobuf.StringValue
254 | 0, // 4: order.OrderManagement.updateOrder:input_type -> order.Order
255 | 2, // 5: order.OrderManagement.processOrder:input_type -> google.protobuf.StringValue
256 | 2, // 6: order.GreeterService.sayHello:input_type -> google.protobuf.StringValue
257 | 0, // 7: order.OrderManagement.getOrder:output_type -> order.Order
258 | 2, // 8: order.OrderManagement.addOrder:output_type -> google.protobuf.StringValue
259 | 0, // 9: order.OrderManagement.searchOrder:output_type -> order.Order
260 | 2, // 10: order.OrderManagement.updateOrder:output_type -> google.protobuf.StringValue
261 | 1, // 11: order.OrderManagement.processOrder:output_type -> order.CombinedShipment
262 | 2, // 12: order.GreeterService.sayHello:output_type -> google.protobuf.StringValue
263 | 7, // [7:13] is the sub-list for method output_type
264 | 1, // [1:7] is the sub-list for method input_type
265 | 1, // [1:1] is the sub-list for extension type_name
266 | 1, // [1:1] is the sub-list for extension extendee
267 | 0, // [0:1] is the sub-list for field type_name
268 | }
269 |
270 | func init() { file_OrderInfo_proto_init() }
271 | func file_OrderInfo_proto_init() {
272 | if File_OrderInfo_proto != nil {
273 | return
274 | }
275 | if !protoimpl.UnsafeEnabled {
276 | file_OrderInfo_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
277 | switch v := v.(*Order); i {
278 | case 0:
279 | return &v.state
280 | case 1:
281 | return &v.sizeCache
282 | case 2:
283 | return &v.unknownFields
284 | default:
285 | return nil
286 | }
287 | }
288 | file_OrderInfo_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
289 | switch v := v.(*CombinedShipment); i {
290 | case 0:
291 | return &v.state
292 | case 1:
293 | return &v.sizeCache
294 | case 2:
295 | return &v.unknownFields
296 | default:
297 | return nil
298 | }
299 | }
300 | }
301 | type x struct{}
302 | out := protoimpl.TypeBuilder{
303 | File: protoimpl.DescBuilder{
304 | GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
305 | RawDescriptor: file_OrderInfo_proto_rawDesc,
306 | NumEnums: 0,
307 | NumMessages: 2,
308 | NumExtensions: 0,
309 | NumServices: 2,
310 | },
311 | GoTypes: file_OrderInfo_proto_goTypes,
312 | DependencyIndexes: file_OrderInfo_proto_depIdxs,
313 | MessageInfos: file_OrderInfo_proto_msgTypes,
314 | }.Build()
315 | File_OrderInfo_proto = out.File
316 | file_OrderInfo_proto_rawDesc = nil
317 | file_OrderInfo_proto_goTypes = nil
318 | file_OrderInfo_proto_depIdxs = nil
319 | }
320 |
321 | // Reference imports to suppress errors if they are not otherwise used.
322 | var _ context.Context
323 | var _ grpc.ClientConnInterface
324 |
325 | // This is a compile-time assertion to ensure that this generated file
326 | // is compatible with the grpc package it is being compiled against.
327 | const _ = grpc.SupportPackageIsVersion6
328 |
329 | // OrderManagementClient is the client API for OrderManagement service.
330 | //
331 | // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
332 | type OrderManagementClient interface {
333 | //获取订单
334 | GetOrder(ctx context.Context, in *wrappers.StringValue, opts ...grpc.CallOption) (*Order, error)
335 | //添加订单
336 | AddOrder(ctx context.Context, in *Order, opts ...grpc.CallOption) (*wrappers.StringValue, error)
337 | //搜索订单
338 | SearchOrder(ctx context.Context, in *wrappers.StringValue, opts ...grpc.CallOption) (OrderManagement_SearchOrderClient, error)
339 | //更新订单
340 | UpdateOrder(ctx context.Context, opts ...grpc.CallOption) (OrderManagement_UpdateOrderClient, error)
341 | //处理订单
342 | ProcessOrder(ctx context.Context, opts ...grpc.CallOption) (OrderManagement_ProcessOrderClient, error)
343 | }
344 |
345 | type orderManagementClient struct {
346 | cc grpc.ClientConnInterface
347 | }
348 |
349 | func NewOrderManagementClient(cc grpc.ClientConnInterface) OrderManagementClient {
350 | return &orderManagementClient{cc}
351 | }
352 |
353 | func (c *orderManagementClient) GetOrder(ctx context.Context, in *wrappers.StringValue, opts ...grpc.CallOption) (*Order, error) {
354 | out := new(Order)
355 | err := c.cc.Invoke(ctx, "/order.OrderManagement/getOrder", in, out, opts...)
356 | if err != nil {
357 | return nil, err
358 | }
359 | return out, nil
360 | }
361 |
362 | func (c *orderManagementClient) AddOrder(ctx context.Context, in *Order, opts ...grpc.CallOption) (*wrappers.StringValue, error) {
363 | out := new(wrappers.StringValue)
364 | err := c.cc.Invoke(ctx, "/order.OrderManagement/addOrder", in, out, opts...)
365 | if err != nil {
366 | return nil, err
367 | }
368 | return out, nil
369 | }
370 |
371 | func (c *orderManagementClient) SearchOrder(ctx context.Context, in *wrappers.StringValue, opts ...grpc.CallOption) (OrderManagement_SearchOrderClient, error) {
372 | stream, err := c.cc.NewStream(ctx, &_OrderManagement_serviceDesc.Streams[0], "/order.OrderManagement/searchOrder", opts...)
373 | if err != nil {
374 | return nil, err
375 | }
376 | x := &orderManagementSearchOrderClient{stream}
377 | if err := x.ClientStream.SendMsg(in); err != nil {
378 | return nil, err
379 | }
380 | if err := x.ClientStream.CloseSend(); err != nil {
381 | return nil, err
382 | }
383 | return x, nil
384 | }
385 |
386 | type OrderManagement_SearchOrderClient interface {
387 | Recv() (*Order, error)
388 | grpc.ClientStream
389 | }
390 |
391 | type orderManagementSearchOrderClient struct {
392 | grpc.ClientStream
393 | }
394 |
395 | func (x *orderManagementSearchOrderClient) Recv() (*Order, error) {
396 | m := new(Order)
397 | if err := x.ClientStream.RecvMsg(m); err != nil {
398 | return nil, err
399 | }
400 | return m, nil
401 | }
402 |
403 | func (c *orderManagementClient) UpdateOrder(ctx context.Context, opts ...grpc.CallOption) (OrderManagement_UpdateOrderClient, error) {
404 | stream, err := c.cc.NewStream(ctx, &_OrderManagement_serviceDesc.Streams[1], "/order.OrderManagement/updateOrder", opts...)
405 | if err != nil {
406 | return nil, err
407 | }
408 | x := &orderManagementUpdateOrderClient{stream}
409 | return x, nil
410 | }
411 |
412 | type OrderManagement_UpdateOrderClient interface {
413 | Send(*Order) error
414 | CloseAndRecv() (*wrappers.StringValue, error)
415 | grpc.ClientStream
416 | }
417 |
418 | type orderManagementUpdateOrderClient struct {
419 | grpc.ClientStream
420 | }
421 |
422 | func (x *orderManagementUpdateOrderClient) Send(m *Order) error {
423 | return x.ClientStream.SendMsg(m)
424 | }
425 |
426 | func (x *orderManagementUpdateOrderClient) CloseAndRecv() (*wrappers.StringValue, error) {
427 | if err := x.ClientStream.CloseSend(); err != nil {
428 | return nil, err
429 | }
430 | m := new(wrappers.StringValue)
431 | if err := x.ClientStream.RecvMsg(m); err != nil {
432 | return nil, err
433 | }
434 | return m, nil
435 | }
436 |
437 | func (c *orderManagementClient) ProcessOrder(ctx context.Context, opts ...grpc.CallOption) (OrderManagement_ProcessOrderClient, error) {
438 | stream, err := c.cc.NewStream(ctx, &_OrderManagement_serviceDesc.Streams[2], "/order.OrderManagement/processOrder", opts...)
439 | if err != nil {
440 | return nil, err
441 | }
442 | x := &orderManagementProcessOrderClient{stream}
443 | return x, nil
444 | }
445 |
446 | type OrderManagement_ProcessOrderClient interface {
447 | Send(*wrappers.StringValue) error
448 | Recv() (*CombinedShipment, error)
449 | grpc.ClientStream
450 | }
451 |
452 | type orderManagementProcessOrderClient struct {
453 | grpc.ClientStream
454 | }
455 |
456 | func (x *orderManagementProcessOrderClient) Send(m *wrappers.StringValue) error {
457 | return x.ClientStream.SendMsg(m)
458 | }
459 |
460 | func (x *orderManagementProcessOrderClient) Recv() (*CombinedShipment, error) {
461 | m := new(CombinedShipment)
462 | if err := x.ClientStream.RecvMsg(m); err != nil {
463 | return nil, err
464 | }
465 | return m, nil
466 | }
467 |
468 | // OrderManagementServer is the server API for OrderManagement service.
469 | type OrderManagementServer interface {
470 | //获取订单
471 | GetOrder(context.Context, *wrappers.StringValue) (*Order, error)
472 | //添加订单
473 | AddOrder(context.Context, *Order) (*wrappers.StringValue, error)
474 | //搜索订单
475 | SearchOrder(*wrappers.StringValue, OrderManagement_SearchOrderServer) error
476 | //更新订单
477 | UpdateOrder(OrderManagement_UpdateOrderServer) error
478 | //处理订单
479 | ProcessOrder(OrderManagement_ProcessOrderServer) error
480 | }
481 |
482 | // UnimplementedOrderManagementServer can be embedded to have forward compatible implementations.
483 | type UnimplementedOrderManagementServer struct {
484 | }
485 |
486 | func (*UnimplementedOrderManagementServer) GetOrder(context.Context, *wrappers.StringValue) (*Order, error) {
487 | return nil, status.Errorf(codes.Unimplemented, "method GetOrder not implemented")
488 | }
489 | func (*UnimplementedOrderManagementServer) AddOrder(context.Context, *Order) (*wrappers.StringValue, error) {
490 | return nil, status.Errorf(codes.Unimplemented, "method AddOrder not implemented")
491 | }
492 | func (*UnimplementedOrderManagementServer) SearchOrder(*wrappers.StringValue, OrderManagement_SearchOrderServer) error {
493 | return status.Errorf(codes.Unimplemented, "method SearchOrder not implemented")
494 | }
495 | func (*UnimplementedOrderManagementServer) UpdateOrder(OrderManagement_UpdateOrderServer) error {
496 | return status.Errorf(codes.Unimplemented, "method UpdateOrder not implemented")
497 | }
498 | func (*UnimplementedOrderManagementServer) ProcessOrder(OrderManagement_ProcessOrderServer) error {
499 | return status.Errorf(codes.Unimplemented, "method ProcessOrder not implemented")
500 | }
501 |
502 | func RegisterOrderManagementServer(s *grpc.Server, srv OrderManagementServer) {
503 | s.RegisterService(&_OrderManagement_serviceDesc, srv)
504 | }
505 |
506 | func _OrderManagement_GetOrder_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
507 | in := new(wrappers.StringValue)
508 | if err := dec(in); err != nil {
509 | return nil, err
510 | }
511 | if interceptor == nil {
512 | return srv.(OrderManagementServer).GetOrder(ctx, in)
513 | }
514 | info := &grpc.UnaryServerInfo{
515 | Server: srv,
516 | FullMethod: "/order.OrderManagement/GetOrder",
517 | }
518 | handler := func(ctx context.Context, req interface{}) (interface{}, error) {
519 | return srv.(OrderManagementServer).GetOrder(ctx, req.(*wrappers.StringValue))
520 | }
521 | return interceptor(ctx, in, info, handler)
522 | }
523 |
524 | func _OrderManagement_AddOrder_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
525 | in := new(Order)
526 | if err := dec(in); err != nil {
527 | return nil, err
528 | }
529 | if interceptor == nil {
530 | return srv.(OrderManagementServer).AddOrder(ctx, in)
531 | }
532 | info := &grpc.UnaryServerInfo{
533 | Server: srv,
534 | FullMethod: "/order.OrderManagement/AddOrder",
535 | }
536 | handler := func(ctx context.Context, req interface{}) (interface{}, error) {
537 | return srv.(OrderManagementServer).AddOrder(ctx, req.(*Order))
538 | }
539 | return interceptor(ctx, in, info, handler)
540 | }
541 |
542 | func _OrderManagement_SearchOrder_Handler(srv interface{}, stream grpc.ServerStream) error {
543 | m := new(wrappers.StringValue)
544 | if err := stream.RecvMsg(m); err != nil {
545 | return err
546 | }
547 | return srv.(OrderManagementServer).SearchOrder(m, &orderManagementSearchOrderServer{stream})
548 | }
549 |
550 | type OrderManagement_SearchOrderServer interface {
551 | Send(*Order) error
552 | grpc.ServerStream
553 | }
554 |
555 | type orderManagementSearchOrderServer struct {
556 | grpc.ServerStream
557 | }
558 |
559 | func (x *orderManagementSearchOrderServer) Send(m *Order) error {
560 | return x.ServerStream.SendMsg(m)
561 | }
562 |
563 | func _OrderManagement_UpdateOrder_Handler(srv interface{}, stream grpc.ServerStream) error {
564 | return srv.(OrderManagementServer).UpdateOrder(&orderManagementUpdateOrderServer{stream})
565 | }
566 |
567 | type OrderManagement_UpdateOrderServer interface {
568 | SendAndClose(*wrappers.StringValue) error
569 | Recv() (*Order, error)
570 | grpc.ServerStream
571 | }
572 |
573 | type orderManagementUpdateOrderServer struct {
574 | grpc.ServerStream
575 | }
576 |
577 | func (x *orderManagementUpdateOrderServer) SendAndClose(m *wrappers.StringValue) error {
578 | return x.ServerStream.SendMsg(m)
579 | }
580 |
581 | func (x *orderManagementUpdateOrderServer) Recv() (*Order, error) {
582 | m := new(Order)
583 | if err := x.ServerStream.RecvMsg(m); err != nil {
584 | return nil, err
585 | }
586 | return m, nil
587 | }
588 |
589 | func _OrderManagement_ProcessOrder_Handler(srv interface{}, stream grpc.ServerStream) error {
590 | return srv.(OrderManagementServer).ProcessOrder(&orderManagementProcessOrderServer{stream})
591 | }
592 |
593 | type OrderManagement_ProcessOrderServer interface {
594 | Send(*CombinedShipment) error
595 | Recv() (*wrappers.StringValue, error)
596 | grpc.ServerStream
597 | }
598 |
599 | type orderManagementProcessOrderServer struct {
600 | grpc.ServerStream
601 | }
602 |
603 | func (x *orderManagementProcessOrderServer) Send(m *CombinedShipment) error {
604 | return x.ServerStream.SendMsg(m)
605 | }
606 |
607 | func (x *orderManagementProcessOrderServer) Recv() (*wrappers.StringValue, error) {
608 | m := new(wrappers.StringValue)
609 | if err := x.ServerStream.RecvMsg(m); err != nil {
610 | return nil, err
611 | }
612 | return m, nil
613 | }
614 |
615 | var _OrderManagement_serviceDesc = grpc.ServiceDesc{
616 | ServiceName: "order.OrderManagement",
617 | HandlerType: (*OrderManagementServer)(nil),
618 | Methods: []grpc.MethodDesc{
619 | {
620 | MethodName: "getOrder",
621 | Handler: _OrderManagement_GetOrder_Handler,
622 | },
623 | {
624 | MethodName: "addOrder",
625 | Handler: _OrderManagement_AddOrder_Handler,
626 | },
627 | },
628 | Streams: []grpc.StreamDesc{
629 | {
630 | StreamName: "searchOrder",
631 | Handler: _OrderManagement_SearchOrder_Handler,
632 | ServerStreams: true,
633 | },
634 | {
635 | StreamName: "updateOrder",
636 | Handler: _OrderManagement_UpdateOrder_Handler,
637 | ClientStreams: true,
638 | },
639 | {
640 | StreamName: "processOrder",
641 | Handler: _OrderManagement_ProcessOrder_Handler,
642 | ServerStreams: true,
643 | ClientStreams: true,
644 | },
645 | },
646 | Metadata: "OrderInfo.proto",
647 | }
648 |
649 | // GreeterServiceClient is the client API for GreeterService service.
650 | //
651 | // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
652 | type GreeterServiceClient interface {
653 | SayHello(ctx context.Context, in *wrappers.StringValue, opts ...grpc.CallOption) (*wrappers.StringValue, error)
654 | }
655 |
656 | type greeterServiceClient struct {
657 | cc grpc.ClientConnInterface
658 | }
659 |
660 | func NewGreeterServiceClient(cc grpc.ClientConnInterface) GreeterServiceClient {
661 | return &greeterServiceClient{cc}
662 | }
663 |
664 | func (c *greeterServiceClient) SayHello(ctx context.Context, in *wrappers.StringValue, opts ...grpc.CallOption) (*wrappers.StringValue, error) {
665 | out := new(wrappers.StringValue)
666 | err := c.cc.Invoke(ctx, "/order.GreeterService/sayHello", in, out, opts...)
667 | if err != nil {
668 | return nil, err
669 | }
670 | return out, nil
671 | }
672 |
673 | // GreeterServiceServer is the server API for GreeterService service.
674 | type GreeterServiceServer interface {
675 | SayHello(context.Context, *wrappers.StringValue) (*wrappers.StringValue, error)
676 | }
677 |
678 | // UnimplementedGreeterServiceServer can be embedded to have forward compatible implementations.
679 | type UnimplementedGreeterServiceServer struct {
680 | }
681 |
682 | func (*UnimplementedGreeterServiceServer) SayHello(context.Context, *wrappers.StringValue) (*wrappers.StringValue, error) {
683 | return nil, status.Errorf(codes.Unimplemented, "method SayHello not implemented")
684 | }
685 |
686 | func RegisterGreeterServiceServer(s *grpc.Server, srv GreeterServiceServer) {
687 | s.RegisterService(&_GreeterService_serviceDesc, srv)
688 | }
689 |
690 | func _GreeterService_SayHello_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
691 | in := new(wrappers.StringValue)
692 | if err := dec(in); err != nil {
693 | return nil, err
694 | }
695 | if interceptor == nil {
696 | return srv.(GreeterServiceServer).SayHello(ctx, in)
697 | }
698 | info := &grpc.UnaryServerInfo{
699 | Server: srv,
700 | FullMethod: "/order.GreeterService/SayHello",
701 | }
702 | handler := func(ctx context.Context, req interface{}) (interface{}, error) {
703 | return srv.(GreeterServiceServer).SayHello(ctx, req.(*wrappers.StringValue))
704 | }
705 | return interceptor(ctx, in, info, handler)
706 | }
707 |
708 | var _GreeterService_serviceDesc = grpc.ServiceDesc{
709 | ServiceName: "order.GreeterService",
710 | HandlerType: (*GreeterServiceServer)(nil),
711 | Methods: []grpc.MethodDesc{
712 | {
713 | MethodName: "sayHello",
714 | Handler: _GreeterService_SayHello_Handler,
715 | },
716 | },
717 | Streams: []grpc.StreamDesc{},
718 | Metadata: "OrderInfo.proto",
719 | }
720 |
--------------------------------------------------------------------------------
/order_advance_2/OrderInfo.proto:
--------------------------------------------------------------------------------
1 | syntax = "proto3";
2 | package order;
3 |
4 | import "google/protobuf/wrappers.proto";
5 |
6 | // 订单服务
7 | service OrderManagement {
8 | //获取订单
9 | rpc getOrder(google.protobuf.StringValue) returns(Order);
10 | //添加订单
11 | rpc addOrder(Order) returns(google.protobuf.StringValue);
12 | //搜索订单
13 | rpc searchOrder(google.protobuf.StringValue) returns(stream Order);
14 | //更新订单
15 | rpc updateOrder(stream Order) returns(google.protobuf.StringValue);
16 | //处理订单
17 | rpc processOrder(stream google.protobuf.StringValue) returns(stream CombinedShipment);
18 | }
19 |
20 | // 问候服务
21 | service GreeterService {
22 | rpc sayHello(google.protobuf.StringValue) returns (google.protobuf.StringValue);
23 | }
24 |
25 | message Order {
26 | //订单id
27 | string id = 1;
28 | //订单详情
29 | repeated string items = 2;
30 | //订单描述
31 | string description = 3;
32 | //订单价格
33 | float price = 4;
34 | //订单目的地
35 | string destination = 5;
36 | }
37 |
38 | message CombinedShipment {
39 | string id = 1;
40 | string status = 2;
41 | repeated Order orderList = 3;
42 | }
43 |
--------------------------------------------------------------------------------
/order_advance_2/client/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "context"
5 | "fmt"
6 | "github.com/golang/protobuf/ptypes/wrappers"
7 | "google.golang.org/grpc"
8 | "google.golang.org/grpc/metadata"
9 | order "grpc-demo/order_advance_2"
10 | "io"
11 | "log"
12 | "time"
13 | )
14 |
15 | const address = "localhost:50051"
16 |
17 | func main() {
18 | conn, err := grpc.Dial(address, grpc.WithInsecure())
19 | if err != nil {
20 | log.Println("did not connect.", err)
21 | return
22 | }
23 | defer conn.Close()
24 | client := order.NewOrderManagementClient(conn)
25 |
26 | md := metadata.Pairs(
27 | "timestamp", time.Now().Format(time.RFC3339),
28 | "test-key", "val1",
29 | "test-key", "val2",
30 | )
31 | //使用元数据context
32 | mdCtx := metadata.NewOutgoingContext(context.Background(), md)
33 | fmt.Println("----------------use metadata----------------")
34 | testOrder := &order.Order{Destination: "beijing", Items: []string{"book1", "book2"}, Price: 123.232}
35 |
36 | //接收从服务端发送过来的metadata信息
37 | var header metadata.MD
38 |
39 | _, err = client.AddOrder(mdCtx, testOrder, grpc.Header(&header))
40 | log.Printf("metadata from server : %+v\n", header)
41 |
42 | ctx := context.Background()
43 | fmt.Println("----------------unary rpc----------------")
44 | id := AddOrder(ctx, client)
45 | GetOrder(ctx, client, id)
46 |
47 | fmt.Println("-----------server stream rpc-------------")
48 | SearchOrder(ctx, client)
49 |
50 | fmt.Println("------------client stream rpc------------")
51 | UpdateOrder(ctx, client)
52 |
53 | fmt.Println("---------bidirectional stream rpc---------")
54 | ProcessOrder(ctx, client)
55 |
56 | // 问候服务客户端
57 | fmt.Println("-----------greeter client rpc-----------")
58 | greeterClient := order.NewGreeterServiceClient(conn)
59 | _, err = greeterClient.SayHello(ctx, &wrappers.StringValue{Value: "roseduan"})
60 | if err != nil {
61 | log.Println("call greeter server [say hello] err.", err)
62 | }
63 | }
64 |
65 | //添加一个订单
66 | func AddOrder(ctx context.Context, client order.OrderManagementClient) string {
67 | odr := &order.Order{
68 | Description: "a new order for test-1",
69 | Price: 12322.232,
70 | Destination: "Shanghai",
71 | Items: []string{"doll", "22", "33"},
72 | }
73 |
74 | val, err := client.AddOrder(ctx, odr)
75 | if err != nil {
76 | log.Println("add order fail.", err)
77 | return ""
78 | }
79 | log.Println("add order success.id = ", val.String())
80 | return val.Value
81 | }
82 |
83 | //获取一个订单
84 | func GetOrder(ctx context.Context, client order.OrderManagementClient, id string) {
85 | val, err := client.GetOrder(ctx, &wrappers.StringValue{Value: id})
86 | if err != nil {
87 | log.Println("get order err.", err)
88 | return
89 | }
90 |
91 | log.Printf("get order succes. order = %+v", val)
92 | }
93 |
94 | //搜索订单
95 | func SearchOrder(ctx context.Context, client order.OrderManagementClient) {
96 | searchKey := "Apple"
97 | searchStream, _ := client.SearchOrder(ctx, &wrappers.StringValue{Value: searchKey})
98 | for {
99 | val, err := searchStream.Recv()
100 | if err == io.EOF { //服务端没有数据了
101 | break
102 | }
103 | log.Printf("search order from server : %+v", val)
104 | }
105 | return
106 | }
107 |
108 | //更新订单
109 | func UpdateOrder(ctx context.Context, client order.OrderManagementClient) {
110 | updateStream, _ := client.UpdateOrder(ctx)
111 | order1 := &order.Order{Id: "103", Items: []string{"Apple Watch S6"}, Destination: "San Jose, CA", Price: 4400.00}
112 | order2 := &order.Order{Id: "105", Items: []string{"Amazon Kindle"}, Destination: "San Jose, CA", Price: 330.00}
113 |
114 | //更新订单1
115 | if err := updateStream.Send(order1); err != nil {
116 | log.Println("send order err.", err)
117 | }
118 |
119 | //更新订单2
120 | if err := updateStream.Send(order2); err != nil {
121 | log.Println("send order err.", err)
122 | }
123 |
124 | //关闭流并接收响应
125 | recv, err := updateStream.CloseAndRecv()
126 | if err != nil {
127 | log.Println("close and recv err.", err)
128 | return
129 | }
130 | log.Printf("the update result : %+v", recv)
131 | }
132 |
133 | //处理订单
134 | func ProcessOrder(ctx context.Context, client order.OrderManagementClient) {
135 | processStream, _ := client.ProcessOrder(ctx)
136 |
137 | //发送两个订单处理
138 | if err := processStream.Send(&wrappers.StringValue{Value: "103"}); err != nil {
139 | log.Println("send order err.", err)
140 | }
141 | if err := processStream.Send(&wrappers.StringValue{Value: "105"}); err != nil {
142 | log.Println("send order err.", err)
143 | }
144 |
145 | chn := make(chan struct{})
146 | //异步接收服务端的结果
147 | go processResultFromServer(processStream, chn)
148 |
149 | //再发送一个订单
150 | if err := processStream.Send(&wrappers.StringValue{Value: "106"}); err != nil {
151 | log.Println("send order err.", err)
152 | }
153 | //发送完毕后记得关闭
154 | if err := processStream.CloseSend(); err != nil {
155 | log.Println("close send err.", err)
156 | }
157 |
158 | <-chn
159 | }
160 |
161 | //从服务端获取处理的结果
162 | func processResultFromServer(stream order.OrderManagement_ProcessOrderClient, chn chan struct{}) {
163 | defer close(chn)
164 | for {
165 | shipment, err := stream.Recv()
166 | if err == io.EOF {
167 | log.Println("[client]结束从服务端接收数据")
168 | break
169 | }
170 | log.Printf("[client]server process result : %+v\n", shipment)
171 | }
172 | }
173 |
--------------------------------------------------------------------------------
/order_advance_2/server/echo.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "context"
5 | "fmt"
6 | "google.golang.org/grpc"
7 | order "grpc-demo/order_advance_2"
8 | "log"
9 | "net"
10 | )
11 |
12 | var addrs = []string{
13 | "50051",
14 | "50052",
15 | }
16 |
17 | type EchoServer struct {
18 | addr string
19 | }
20 |
21 | func (e *EchoServer) UnaryEcho(ctx context.Context, req *order.EchoReq) (resp *order.EchoResp, err error) {
22 | return &order.EchoResp{
23 | Message: fmt.Sprintf("%s from(%s)", req.Message, e.addr),
24 | Addr: e.addr,
25 | }, nil
26 | }
27 |
28 | func startServer(addr string) {
29 | listener, err := net.Listen("tcp", addr)
30 | if err != nil {
31 | log.Println("net listen err.", err)
32 | return
33 | }
34 |
35 | s := grpc.NewServer()
36 | order.RegisterEchoServiceServer(s, &EchoServer{addr})
37 | log.Printf("serve on %s", addr)
38 | if err := s.Serve(listener); err != nil {
39 | log.Fatalf("failed to serve %+v", err)
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/order_advance_2/server/greeter.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "context"
5 | "github.com/golang/protobuf/ptypes/wrappers"
6 | "log"
7 | )
8 |
9 | type GreeterServer struct {
10 | }
11 |
12 | func (s *GreeterServer) SayHello(ctx context.Context, req *wrappers.StringValue) (resp *wrappers.StringValue, err error) {
13 | resp = &wrappers.StringValue{}
14 | log.Printf("[greeter server]Hello, %s, this is greeter server.", req.Value)
15 | return
16 | }
17 |
--------------------------------------------------------------------------------
/order_advance_2/server/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "google.golang.org/grpc"
5 | order "grpc-demo/order_advance_2"
6 | "log"
7 | "net"
8 | )
9 |
10 | const port = ":50051"
11 |
12 | //初始化添加一些订单数据
13 | func initSampleData(orderMap map[string]*order.Order) {
14 | orderMap["102"] = &order.Order{Id: "102", Items: []string{"Google Pixel 3A", "Mac Book Pro"}, Destination: "Mountain View, CA", Price: 1800.00}
15 | orderMap["103"] = &order.Order{Id: "103", Items: []string{"Apple Watch S4"}, Destination: "San Jose, CA", Price: 400.00}
16 | orderMap["104"] = &order.Order{Id: "104", Items: []string{"Google Home Mini", "Google Nest Hub"}, Destination: "Mountain View, CA", Price: 400.00}
17 | orderMap["105"] = &order.Order{Id: "105", Items: []string{"Amazon Echo"}, Destination: "San Jose, CA", Price: 30.00}
18 | orderMap["106"] = &order.Order{Id: "106", Items: []string{"Amazon Echo", "Apple iPhone XS"}, Destination: "Mountain View, CA", Price: 300.00}
19 | }
20 |
21 | func main() {
22 | server := &OrderServer{orderMap: make(map[string]*order.Order)}
23 | initSampleData(server.orderMap)
24 |
25 | listener, err := net.Listen("tcp", port)
26 | if err != nil {
27 | log.Println("net listen err ", err)
28 | return
29 | }
30 |
31 | s := grpc.NewServer()
32 | //注册订单服务
33 | order.RegisterOrderManagementServer(s, server)
34 | //注册问候服务
35 | order.RegisterGreeterServiceServer(s, &GreeterServer{})
36 |
37 | log.Println("start gRPC listen on port " + port)
38 | if err := s.Serve(listener); err != nil {
39 | log.Println("failed to serve...", err)
40 | return
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/order_advance_2/server/order.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "context"
5 | "github.com/gofrs/uuid"
6 | "github.com/golang/protobuf/ptypes/wrappers"
7 | "google.golang.org/grpc"
8 | "google.golang.org/grpc/codes"
9 | "google.golang.org/grpc/metadata"
10 | "google.golang.org/grpc/status"
11 | order "grpc-demo/order_advance_2"
12 | "io"
13 | "log"
14 | "strings"
15 | "time"
16 | )
17 |
18 | type OrderServer struct {
19 | orderMap map[string]*order.Order
20 | }
21 |
22 | //获取订单
23 | func (s *OrderServer) GetOrder(ctx context.Context, req *wrappers.StringValue) (resp *order.Order, err error) {
24 | resp = &order.Order{}
25 | id := req.Value
26 | var exist bool
27 | if resp, exist = s.orderMap[id]; !exist {
28 | err = status.Error(codes.NotFound, "order not found id = "+id)
29 | return
30 | }
31 | return
32 | }
33 |
34 | //添加订单
35 | func (s *OrderServer) AddOrder(ctx context.Context, req *order.Order) (resp *wrappers.StringValue, err error) {
36 | resp = &wrappers.StringValue{}
37 | if s.orderMap == nil {
38 | s.orderMap = make(map[string]*order.Order)
39 | }
40 |
41 | v4, err := uuid.NewV4()
42 | if err != nil {
43 | return resp, status.Errorf(codes.Internal, "gen uuid err", err)
44 | }
45 | id := v4.String()
46 | req.Id = id
47 | s.orderMap[id] = req
48 |
49 | resp.Value = id
50 |
51 | //获取元数据
52 | if md, ok := metadata.FromIncomingContext(ctx); !ok {
53 | log.Println("failed to get metadata")
54 | } else {
55 | log.Printf("metadata from client : %+v\n", md)
56 | }
57 |
58 | //发送一个header元信息
59 | md := metadata.New(map[string]string{"location": "San Jose", "timestamp": time.Now().Format(time.StampNano)})
60 | err = grpc.SendHeader(ctx, md)
61 | if err != nil {
62 | log.Println("send header err")
63 | }
64 | return
65 | }
66 |
67 | //搜索订单
68 | func (s *OrderServer) SearchOrder(searchKey *wrappers.StringValue, stream order.OrderManagement_SearchOrderServer) (err error) {
69 | for _, val := range s.orderMap {
70 | for _, item := range val.Items {
71 | if strings.Contains(item, searchKey.Value) {
72 | err = stream.Send(val)
73 | if err != nil {
74 | log.Println("stream send order err.", err)
75 | return
76 | }
77 | break
78 | }
79 | }
80 | }
81 | return
82 | }
83 |
84 | //更新订单
85 | func (s *OrderServer) UpdateOrder(stream order.OrderManagement_UpdateOrderServer) (err error) {
86 | updatedIds := "updated order ids : "
87 | for {
88 | val, err := stream.Recv()
89 | if err == io.EOF { //完成读取订单流
90 | //向客户端发送消息
91 | return stream.SendAndClose(&wrappers.StringValue{Value: updatedIds})
92 | }
93 | s.orderMap[val.Id] = val
94 | log.Println("[OrderServer]update the order : ", val.Id)
95 | updatedIds += val.Id + ", "
96 | }
97 | }
98 |
99 | //处理订单
100 | func (s *OrderServer) ProcessOrder(stream order.OrderManagement_ProcessOrderServer) (err error) {
101 | var combinedShipmentMap = make(map[string]*order.CombinedShipment)
102 | for {
103 | val, err := stream.Recv() //接收从客户端发送来的订单
104 | if err == io.EOF { //接收完毕,返回结果
105 | for _, shipment := range combinedShipmentMap {
106 | if err := stream.Send(shipment); err != nil {
107 | log.Println("[OrderServer] process finished!")
108 | return err
109 | }
110 | }
111 | break
112 | }
113 | if err != nil {
114 | log.Println(err)
115 | break
116 | }
117 |
118 | if val != nil {
119 | orderId := val.Value
120 | log.Printf("[OrderServer]reading order : %+v\n", orderId)
121 |
122 | dest := s.orderMap[orderId].Destination
123 | shipment, exist := combinedShipmentMap[dest]
124 | if exist {
125 | ord := s.orderMap[orderId]
126 | shipment.OrderList = append(shipment.OrderList, ord)
127 | combinedShipmentMap[dest] = shipment
128 | } else {
129 | comShip := &order.CombinedShipment{Id: "cmb - " + (s.orderMap[orderId].Destination), Status: "Processed!"}
130 | ord := s.orderMap[orderId]
131 | comShip.OrderList = append(comShip.OrderList, ord)
132 | combinedShipmentMap[dest] = comShip
133 | log.Println(len(comShip.OrderList), comShip.GetId())
134 | }
135 | }
136 | }
137 | return
138 | }
139 |
--------------------------------------------------------------------------------
/product/ProductInfo.pb.go:
--------------------------------------------------------------------------------
1 | // Code generated by protoc-gen-go. DO NOT EDIT.
2 | // versions:
3 | // protoc-gen-go v1.25.0
4 | // protoc v3.13.0
5 | // source: ProductInfo.proto
6 |
7 | package product
8 |
9 | import (
10 | context "context"
11 | proto "github.com/golang/protobuf/proto"
12 | grpc "google.golang.org/grpc"
13 | codes "google.golang.org/grpc/codes"
14 | status "google.golang.org/grpc/status"
15 | protoreflect "google.golang.org/protobuf/reflect/protoreflect"
16 | protoimpl "google.golang.org/protobuf/runtime/protoimpl"
17 | reflect "reflect"
18 | sync "sync"
19 | )
20 |
21 | const (
22 | // Verify that this generated code is sufficiently up-to-date.
23 | _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
24 | // Verify that runtime/protoimpl is sufficiently up-to-date.
25 | _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
26 | )
27 |
28 | // This is a compile-time assertion that a sufficiently up-to-date version
29 | // of the legacy proto package is being used.
30 | const _ = proto.ProtoPackageIsVersion4
31 |
32 | type Product struct {
33 | state protoimpl.MessageState
34 | sizeCache protoimpl.SizeCache
35 | unknownFields protoimpl.UnknownFields
36 |
37 | Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
38 | Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"`
39 | Description string `protobuf:"bytes,3,opt,name=description,proto3" json:"description,omitempty"`
40 | }
41 |
42 | func (x *Product) Reset() {
43 | *x = Product{}
44 | if protoimpl.UnsafeEnabled {
45 | mi := &file_ProductInfo_proto_msgTypes[0]
46 | ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
47 | ms.StoreMessageInfo(mi)
48 | }
49 | }
50 |
51 | func (x *Product) String() string {
52 | return protoimpl.X.MessageStringOf(x)
53 | }
54 |
55 | func (*Product) ProtoMessage() {}
56 |
57 | func (x *Product) ProtoReflect() protoreflect.Message {
58 | mi := &file_ProductInfo_proto_msgTypes[0]
59 | if protoimpl.UnsafeEnabled && x != nil {
60 | ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
61 | if ms.LoadMessageInfo() == nil {
62 | ms.StoreMessageInfo(mi)
63 | }
64 | return ms
65 | }
66 | return mi.MessageOf(x)
67 | }
68 |
69 | // Deprecated: Use Product.ProtoReflect.Descriptor instead.
70 | func (*Product) Descriptor() ([]byte, []int) {
71 | return file_ProductInfo_proto_rawDescGZIP(), []int{0}
72 | }
73 |
74 | func (x *Product) GetId() string {
75 | if x != nil {
76 | return x.Id
77 | }
78 | return ""
79 | }
80 |
81 | func (x *Product) GetName() string {
82 | if x != nil {
83 | return x.Name
84 | }
85 | return ""
86 | }
87 |
88 | func (x *Product) GetDescription() string {
89 | if x != nil {
90 | return x.Description
91 | }
92 | return ""
93 | }
94 |
95 | type ProductId struct {
96 | state protoimpl.MessageState
97 | sizeCache protoimpl.SizeCache
98 | unknownFields protoimpl.UnknownFields
99 |
100 | Value string `protobuf:"bytes,1,opt,name=value,proto3" json:"value,omitempty"`
101 | }
102 |
103 | func (x *ProductId) Reset() {
104 | *x = ProductId{}
105 | if protoimpl.UnsafeEnabled {
106 | mi := &file_ProductInfo_proto_msgTypes[1]
107 | ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
108 | ms.StoreMessageInfo(mi)
109 | }
110 | }
111 |
112 | func (x *ProductId) String() string {
113 | return protoimpl.X.MessageStringOf(x)
114 | }
115 |
116 | func (*ProductId) ProtoMessage() {}
117 |
118 | func (x *ProductId) ProtoReflect() protoreflect.Message {
119 | mi := &file_ProductInfo_proto_msgTypes[1]
120 | if protoimpl.UnsafeEnabled && x != nil {
121 | ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
122 | if ms.LoadMessageInfo() == nil {
123 | ms.StoreMessageInfo(mi)
124 | }
125 | return ms
126 | }
127 | return mi.MessageOf(x)
128 | }
129 |
130 | // Deprecated: Use ProductId.ProtoReflect.Descriptor instead.
131 | func (*ProductId) Descriptor() ([]byte, []int) {
132 | return file_ProductInfo_proto_rawDescGZIP(), []int{1}
133 | }
134 |
135 | func (x *ProductId) GetValue() string {
136 | if x != nil {
137 | return x.Value
138 | }
139 | return ""
140 | }
141 |
142 | var File_ProductInfo_proto protoreflect.FileDescriptor
143 |
144 | var file_ProductInfo_proto_rawDesc = []byte{
145 | 0x0a, 0x11, 0x50, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x74, 0x49, 0x6e, 0x66, 0x6f, 0x2e, 0x70, 0x72,
146 | 0x6f, 0x74, 0x6f, 0x12, 0x07, 0x70, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x74, 0x22, 0x4f, 0x0a, 0x07,
147 | 0x50, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x74, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20,
148 | 0x01, 0x28, 0x09, 0x52, 0x02, 0x69, 0x64, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18,
149 | 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x20, 0x0a, 0x0b, 0x64,
150 | 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09,
151 | 0x52, 0x0b, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x21, 0x0a,
152 | 0x09, 0x50, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x74, 0x49, 0x64, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61,
153 | 0x6c, 0x75, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65,
154 | 0x32, 0x75, 0x0a, 0x0b, 0x50, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x74, 0x49, 0x6e, 0x66, 0x6f, 0x12,
155 | 0x32, 0x0a, 0x0a, 0x61, 0x64, 0x64, 0x50, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x74, 0x12, 0x10, 0x2e,
156 | 0x70, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x74, 0x2e, 0x50, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x74, 0x1a,
157 | 0x12, 0x2e, 0x70, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x74, 0x2e, 0x50, 0x72, 0x6f, 0x64, 0x75, 0x63,
158 | 0x74, 0x49, 0x64, 0x12, 0x32, 0x0a, 0x0a, 0x67, 0x65, 0x74, 0x50, 0x72, 0x6f, 0x64, 0x75, 0x63,
159 | 0x74, 0x12, 0x12, 0x2e, 0x70, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x74, 0x2e, 0x50, 0x72, 0x6f, 0x64,
160 | 0x75, 0x63, 0x74, 0x49, 0x64, 0x1a, 0x10, 0x2e, 0x70, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x74, 0x2e,
161 | 0x50, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x74, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
162 | }
163 |
164 | var (
165 | file_ProductInfo_proto_rawDescOnce sync.Once
166 | file_ProductInfo_proto_rawDescData = file_ProductInfo_proto_rawDesc
167 | )
168 |
169 | func file_ProductInfo_proto_rawDescGZIP() []byte {
170 | file_ProductInfo_proto_rawDescOnce.Do(func() {
171 | file_ProductInfo_proto_rawDescData = protoimpl.X.CompressGZIP(file_ProductInfo_proto_rawDescData)
172 | })
173 | return file_ProductInfo_proto_rawDescData
174 | }
175 |
176 | var file_ProductInfo_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
177 | var file_ProductInfo_proto_goTypes = []interface{}{
178 | (*Product)(nil), // 0: product.Product
179 | (*ProductId)(nil), // 1: product.ProductId
180 | }
181 | var file_ProductInfo_proto_depIdxs = []int32{
182 | 0, // 0: product.ProductInfo.addProduct:input_type -> product.Product
183 | 1, // 1: product.ProductInfo.getProduct:input_type -> product.ProductId
184 | 1, // 2: product.ProductInfo.addProduct:output_type -> product.ProductId
185 | 0, // 3: product.ProductInfo.getProduct:output_type -> product.Product
186 | 2, // [2:4] is the sub-list for method output_type
187 | 0, // [0:2] is the sub-list for method input_type
188 | 0, // [0:0] is the sub-list for extension type_name
189 | 0, // [0:0] is the sub-list for extension extendee
190 | 0, // [0:0] is the sub-list for field type_name
191 | }
192 |
193 | func init() { file_ProductInfo_proto_init() }
194 | func file_ProductInfo_proto_init() {
195 | if File_ProductInfo_proto != nil {
196 | return
197 | }
198 | if !protoimpl.UnsafeEnabled {
199 | file_ProductInfo_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
200 | switch v := v.(*Product); i {
201 | case 0:
202 | return &v.state
203 | case 1:
204 | return &v.sizeCache
205 | case 2:
206 | return &v.unknownFields
207 | default:
208 | return nil
209 | }
210 | }
211 | file_ProductInfo_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
212 | switch v := v.(*ProductId); i {
213 | case 0:
214 | return &v.state
215 | case 1:
216 | return &v.sizeCache
217 | case 2:
218 | return &v.unknownFields
219 | default:
220 | return nil
221 | }
222 | }
223 | }
224 | type x struct{}
225 | out := protoimpl.TypeBuilder{
226 | File: protoimpl.DescBuilder{
227 | GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
228 | RawDescriptor: file_ProductInfo_proto_rawDesc,
229 | NumEnums: 0,
230 | NumMessages: 2,
231 | NumExtensions: 0,
232 | NumServices: 1,
233 | },
234 | GoTypes: file_ProductInfo_proto_goTypes,
235 | DependencyIndexes: file_ProductInfo_proto_depIdxs,
236 | MessageInfos: file_ProductInfo_proto_msgTypes,
237 | }.Build()
238 | File_ProductInfo_proto = out.File
239 | file_ProductInfo_proto_rawDesc = nil
240 | file_ProductInfo_proto_goTypes = nil
241 | file_ProductInfo_proto_depIdxs = nil
242 | }
243 |
244 | // Reference imports to suppress errors if they are not otherwise used.
245 | var _ context.Context
246 | var _ grpc.ClientConnInterface
247 |
248 | // This is a compile-time assertion to ensure that this generated file
249 | // is compatible with the grpc package it is being compiled against.
250 | const _ = grpc.SupportPackageIsVersion6
251 |
252 | // ProductInfoClient is the client API for ProductInfo service.
253 | //
254 | // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
255 | type ProductInfoClient interface {
256 | //添加商品
257 | AddProduct(ctx context.Context, in *Product, opts ...grpc.CallOption) (*ProductId, error)
258 | //获取商品
259 | GetProduct(ctx context.Context, in *ProductId, opts ...grpc.CallOption) (*Product, error)
260 | }
261 |
262 | type productInfoClient struct {
263 | cc grpc.ClientConnInterface
264 | }
265 |
266 | func NewProductInfoClient(cc grpc.ClientConnInterface) ProductInfoClient {
267 | return &productInfoClient{cc}
268 | }
269 |
270 | func (c *productInfoClient) AddProduct(ctx context.Context, in *Product, opts ...grpc.CallOption) (*ProductId, error) {
271 | out := new(ProductId)
272 | err := c.cc.Invoke(ctx, "/product.ProductInfo/addProduct", in, out, opts...)
273 | if err != nil {
274 | return nil, err
275 | }
276 | return out, nil
277 | }
278 |
279 | func (c *productInfoClient) GetProduct(ctx context.Context, in *ProductId, opts ...grpc.CallOption) (*Product, error) {
280 | out := new(Product)
281 | err := c.cc.Invoke(ctx, "/product.ProductInfo/getProduct", in, out, opts...)
282 | if err != nil {
283 | return nil, err
284 | }
285 | return out, nil
286 | }
287 |
288 | // ProductInfoServer is the server API for ProductInfo service.
289 | type ProductInfoServer interface {
290 | //添加商品
291 | AddProduct(context.Context, *Product) (*ProductId, error)
292 | //获取商品
293 | GetProduct(context.Context, *ProductId) (*Product, error)
294 | }
295 |
296 | // UnimplementedProductInfoServer can be embedded to have forward compatible implementations.
297 | type UnimplementedProductInfoServer struct {
298 | }
299 |
300 | func (*UnimplementedProductInfoServer) AddProduct(context.Context, *Product) (*ProductId, error) {
301 | return nil, status.Errorf(codes.Unimplemented, "method AddProduct not implemented")
302 | }
303 | func (*UnimplementedProductInfoServer) GetProduct(context.Context, *ProductId) (*Product, error) {
304 | return nil, status.Errorf(codes.Unimplemented, "method GetProduct not implemented")
305 | }
306 |
307 | func RegisterProductInfoServer(s *grpc.Server, srv ProductInfoServer) {
308 | s.RegisterService(&_ProductInfo_serviceDesc, srv)
309 | }
310 |
311 | func _ProductInfo_AddProduct_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
312 | in := new(Product)
313 | if err := dec(in); err != nil {
314 | return nil, err
315 | }
316 | if interceptor == nil {
317 | return srv.(ProductInfoServer).AddProduct(ctx, in)
318 | }
319 | info := &grpc.UnaryServerInfo{
320 | Server: srv,
321 | FullMethod: "/product.ProductInfo/AddProduct",
322 | }
323 | handler := func(ctx context.Context, req interface{}) (interface{}, error) {
324 | return srv.(ProductInfoServer).AddProduct(ctx, req.(*Product))
325 | }
326 | return interceptor(ctx, in, info, handler)
327 | }
328 |
329 | func _ProductInfo_GetProduct_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
330 | in := new(ProductId)
331 | if err := dec(in); err != nil {
332 | return nil, err
333 | }
334 | if interceptor == nil {
335 | return srv.(ProductInfoServer).GetProduct(ctx, in)
336 | }
337 | info := &grpc.UnaryServerInfo{
338 | Server: srv,
339 | FullMethod: "/product.ProductInfo/GetProduct",
340 | }
341 | handler := func(ctx context.Context, req interface{}) (interface{}, error) {
342 | return srv.(ProductInfoServer).GetProduct(ctx, req.(*ProductId))
343 | }
344 | return interceptor(ctx, in, info, handler)
345 | }
346 |
347 | var _ProductInfo_serviceDesc = grpc.ServiceDesc{
348 | ServiceName: "product.ProductInfo",
349 | HandlerType: (*ProductInfoServer)(nil),
350 | Methods: []grpc.MethodDesc{
351 | {
352 | MethodName: "addProduct",
353 | Handler: _ProductInfo_AddProduct_Handler,
354 | },
355 | {
356 | MethodName: "getProduct",
357 | Handler: _ProductInfo_GetProduct_Handler,
358 | },
359 | },
360 | Streams: []grpc.StreamDesc{},
361 | Metadata: "ProductInfo.proto",
362 | }
363 |
--------------------------------------------------------------------------------
/product/ProductInfo.proto:
--------------------------------------------------------------------------------
1 | syntax = "proto3";
2 | package product;
3 |
4 | service ProductInfo {
5 | //添加商品
6 | rpc addProduct(Product) returns (ProductId);
7 | //获取商品
8 | rpc getProduct(ProductId) returns (Product);
9 | }
10 |
11 | message Product {
12 | string id = 1;
13 | string name = 2;
14 | string description = 3;
15 | }
16 |
17 | message ProductId {
18 | string value = 1;
19 | }
20 |
--------------------------------------------------------------------------------
/product/client/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "context"
5 | "google.golang.org/grpc"
6 | "grpc-demo/product"
7 | "log"
8 | )
9 |
10 | const (
11 | address = "localhost:50051"
12 | )
13 |
14 | func main() {
15 | conn, err := grpc.Dial(address, grpc.WithInsecure())
16 | if err != nil {
17 | log.Println("did not connect.", err)
18 | return
19 | }
20 | defer conn.Close()
21 |
22 | client := product.NewProductInfoClient(conn)
23 | ctx := context.Background()
24 |
25 | id := AddProduct(ctx, client)
26 | GetProduct(ctx, client, id)
27 | }
28 |
29 | // 添加一个测试的商品
30 | func AddProduct(ctx context.Context, client product.ProductInfoClient) (id string) {
31 | aMac := &product.Product{Name: "Mac Book Pro 2019", Description: "From Apple Inc."}
32 | productId, err := client.AddProduct(ctx, aMac)
33 | if err != nil {
34 | log.Println("add product fail.", err)
35 | return
36 | }
37 | log.Println("add product success, id = ", productId.Value)
38 | return productId.Value
39 | }
40 |
41 | // 获取一个商品
42 | func GetProduct(ctx context.Context, client product.ProductInfoClient, id string) {
43 | p, err := client.GetProduct(ctx, &product.ProductId{Value: id})
44 | if err != nil {
45 | log.Println("get product err.", err)
46 | return
47 | }
48 | log.Printf("get prodcut success : %+v\n", p)
49 | }
50 |
--------------------------------------------------------------------------------
/product/server/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "context"
5 | "github.com/gofrs/uuid"
6 | "google.golang.org/grpc"
7 | "google.golang.org/grpc/codes"
8 | "google.golang.org/grpc/status"
9 | "grpc-demo/product"
10 | "log"
11 | "net"
12 | )
13 |
14 | const port = ":50051"
15 |
16 | func main() {
17 | listener, err := net.Listen("tcp", port)
18 | if err != nil {
19 | log.Println("net listen err ", err)
20 | return
21 | }
22 |
23 | s := grpc.NewServer()
24 | product.RegisterProductInfoServer(s, &server{})
25 | log.Println("start gRPC listen on port " + port)
26 | if err := s.Serve(listener); err != nil {
27 | log.Println("failed to serve...", err)
28 | return
29 | }
30 | }
31 |
32 | type server struct {
33 | productMap map[string]*product.Product
34 | }
35 |
36 | //添加商品
37 | func (s *server) AddProduct(ctx context.Context, req *product.Product) (resp *product.ProductId, err error) {
38 | resp = &product.ProductId{}
39 | out, err := uuid.NewV4()
40 | if err != nil {
41 | return resp, status.Errorf(codes.Internal, "err while generate the uuid ", err)
42 | }
43 |
44 | req.Id = out.String()
45 | if s.productMap == nil {
46 | s.productMap = make(map[string]*product.Product)
47 | }
48 |
49 | s.productMap[req.Id] = req
50 | resp.Value = req.Id
51 | return
52 | }
53 |
54 | //获取商品
55 | func (s *server) GetProduct(ctx context.Context, req *product.ProductId) (resp *product.Product, err error) {
56 | if s.productMap == nil {
57 | s.productMap = make(map[string]*product.Product)
58 | }
59 |
60 | resp = s.productMap[req.Value]
61 | return
62 | }
63 |
--------------------------------------------------------------------------------
/secure-demo/ProductInfo.pb.go:
--------------------------------------------------------------------------------
1 | // Code generated by protoc-gen-go. DO NOT EDIT.
2 | // versions:
3 | // protoc-gen-go v1.25.0
4 | // protoc v3.13.0
5 | // source: ProductInfo.proto
6 |
7 | package product
8 |
9 | import (
10 | context "context"
11 | proto "github.com/golang/protobuf/proto"
12 | grpc "google.golang.org/grpc"
13 | codes "google.golang.org/grpc/codes"
14 | status "google.golang.org/grpc/status"
15 | protoreflect "google.golang.org/protobuf/reflect/protoreflect"
16 | protoimpl "google.golang.org/protobuf/runtime/protoimpl"
17 | reflect "reflect"
18 | sync "sync"
19 | )
20 |
21 | const (
22 | // Verify that this generated code is sufficiently up-to-date.
23 | _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
24 | // Verify that runtime/protoimpl is sufficiently up-to-date.
25 | _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
26 | )
27 |
28 | // This is a compile-time assertion that a sufficiently up-to-date version
29 | // of the legacy proto package is being used.
30 | const _ = proto.ProtoPackageIsVersion4
31 |
32 | type Product struct {
33 | state protoimpl.MessageState
34 | sizeCache protoimpl.SizeCache
35 | unknownFields protoimpl.UnknownFields
36 |
37 | Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
38 | Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"`
39 | Description string `protobuf:"bytes,3,opt,name=description,proto3" json:"description,omitempty"`
40 | }
41 |
42 | func (x *Product) Reset() {
43 | *x = Product{}
44 | if protoimpl.UnsafeEnabled {
45 | mi := &file_ProductInfo_proto_msgTypes[0]
46 | ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
47 | ms.StoreMessageInfo(mi)
48 | }
49 | }
50 |
51 | func (x *Product) String() string {
52 | return protoimpl.X.MessageStringOf(x)
53 | }
54 |
55 | func (*Product) ProtoMessage() {}
56 |
57 | func (x *Product) ProtoReflect() protoreflect.Message {
58 | mi := &file_ProductInfo_proto_msgTypes[0]
59 | if protoimpl.UnsafeEnabled && x != nil {
60 | ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
61 | if ms.LoadMessageInfo() == nil {
62 | ms.StoreMessageInfo(mi)
63 | }
64 | return ms
65 | }
66 | return mi.MessageOf(x)
67 | }
68 |
69 | // Deprecated: Use Product.ProtoReflect.Descriptor instead.
70 | func (*Product) Descriptor() ([]byte, []int) {
71 | return file_ProductInfo_proto_rawDescGZIP(), []int{0}
72 | }
73 |
74 | func (x *Product) GetId() string {
75 | if x != nil {
76 | return x.Id
77 | }
78 | return ""
79 | }
80 |
81 | func (x *Product) GetName() string {
82 | if x != nil {
83 | return x.Name
84 | }
85 | return ""
86 | }
87 |
88 | func (x *Product) GetDescription() string {
89 | if x != nil {
90 | return x.Description
91 | }
92 | return ""
93 | }
94 |
95 | type ProductId struct {
96 | state protoimpl.MessageState
97 | sizeCache protoimpl.SizeCache
98 | unknownFields protoimpl.UnknownFields
99 |
100 | Value string `protobuf:"bytes,1,opt,name=value,proto3" json:"value,omitempty"`
101 | }
102 |
103 | func (x *ProductId) Reset() {
104 | *x = ProductId{}
105 | if protoimpl.UnsafeEnabled {
106 | mi := &file_ProductInfo_proto_msgTypes[1]
107 | ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
108 | ms.StoreMessageInfo(mi)
109 | }
110 | }
111 |
112 | func (x *ProductId) String() string {
113 | return protoimpl.X.MessageStringOf(x)
114 | }
115 |
116 | func (*ProductId) ProtoMessage() {}
117 |
118 | func (x *ProductId) ProtoReflect() protoreflect.Message {
119 | mi := &file_ProductInfo_proto_msgTypes[1]
120 | if protoimpl.UnsafeEnabled && x != nil {
121 | ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
122 | if ms.LoadMessageInfo() == nil {
123 | ms.StoreMessageInfo(mi)
124 | }
125 | return ms
126 | }
127 | return mi.MessageOf(x)
128 | }
129 |
130 | // Deprecated: Use ProductId.ProtoReflect.Descriptor instead.
131 | func (*ProductId) Descriptor() ([]byte, []int) {
132 | return file_ProductInfo_proto_rawDescGZIP(), []int{1}
133 | }
134 |
135 | func (x *ProductId) GetValue() string {
136 | if x != nil {
137 | return x.Value
138 | }
139 | return ""
140 | }
141 |
142 | var File_ProductInfo_proto protoreflect.FileDescriptor
143 |
144 | var file_ProductInfo_proto_rawDesc = []byte{
145 | 0x0a, 0x11, 0x50, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x74, 0x49, 0x6e, 0x66, 0x6f, 0x2e, 0x70, 0x72,
146 | 0x6f, 0x74, 0x6f, 0x12, 0x07, 0x70, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x74, 0x22, 0x4f, 0x0a, 0x07,
147 | 0x50, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x74, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20,
148 | 0x01, 0x28, 0x09, 0x52, 0x02, 0x69, 0x64, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18,
149 | 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x20, 0x0a, 0x0b, 0x64,
150 | 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09,
151 | 0x52, 0x0b, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x21, 0x0a,
152 | 0x09, 0x50, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x74, 0x49, 0x64, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61,
153 | 0x6c, 0x75, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65,
154 | 0x32, 0x75, 0x0a, 0x0b, 0x50, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x74, 0x49, 0x6e, 0x66, 0x6f, 0x12,
155 | 0x32, 0x0a, 0x0a, 0x61, 0x64, 0x64, 0x50, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x74, 0x12, 0x10, 0x2e,
156 | 0x70, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x74, 0x2e, 0x50, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x74, 0x1a,
157 | 0x12, 0x2e, 0x70, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x74, 0x2e, 0x50, 0x72, 0x6f, 0x64, 0x75, 0x63,
158 | 0x74, 0x49, 0x64, 0x12, 0x32, 0x0a, 0x0a, 0x67, 0x65, 0x74, 0x50, 0x72, 0x6f, 0x64, 0x75, 0x63,
159 | 0x74, 0x12, 0x12, 0x2e, 0x70, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x74, 0x2e, 0x50, 0x72, 0x6f, 0x64,
160 | 0x75, 0x63, 0x74, 0x49, 0x64, 0x1a, 0x10, 0x2e, 0x70, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x74, 0x2e,
161 | 0x50, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x74, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
162 | }
163 |
164 | var (
165 | file_ProductInfo_proto_rawDescOnce sync.Once
166 | file_ProductInfo_proto_rawDescData = file_ProductInfo_proto_rawDesc
167 | )
168 |
169 | func file_ProductInfo_proto_rawDescGZIP() []byte {
170 | file_ProductInfo_proto_rawDescOnce.Do(func() {
171 | file_ProductInfo_proto_rawDescData = protoimpl.X.CompressGZIP(file_ProductInfo_proto_rawDescData)
172 | })
173 | return file_ProductInfo_proto_rawDescData
174 | }
175 |
176 | var file_ProductInfo_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
177 | var file_ProductInfo_proto_goTypes = []interface{}{
178 | (*Product)(nil), // 0: product.Product
179 | (*ProductId)(nil), // 1: product.ProductId
180 | }
181 | var file_ProductInfo_proto_depIdxs = []int32{
182 | 0, // 0: product.ProductInfo.addProduct:input_type -> product.Product
183 | 1, // 1: product.ProductInfo.getProduct:input_type -> product.ProductId
184 | 1, // 2: product.ProductInfo.addProduct:output_type -> product.ProductId
185 | 0, // 3: product.ProductInfo.getProduct:output_type -> product.Product
186 | 2, // [2:4] is the sub-list for method output_type
187 | 0, // [0:2] is the sub-list for method input_type
188 | 0, // [0:0] is the sub-list for extension type_name
189 | 0, // [0:0] is the sub-list for extension extendee
190 | 0, // [0:0] is the sub-list for field type_name
191 | }
192 |
193 | func init() { file_ProductInfo_proto_init() }
194 | func file_ProductInfo_proto_init() {
195 | if File_ProductInfo_proto != nil {
196 | return
197 | }
198 | if !protoimpl.UnsafeEnabled {
199 | file_ProductInfo_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
200 | switch v := v.(*Product); i {
201 | case 0:
202 | return &v.state
203 | case 1:
204 | return &v.sizeCache
205 | case 2:
206 | return &v.unknownFields
207 | default:
208 | return nil
209 | }
210 | }
211 | file_ProductInfo_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
212 | switch v := v.(*ProductId); i {
213 | case 0:
214 | return &v.state
215 | case 1:
216 | return &v.sizeCache
217 | case 2:
218 | return &v.unknownFields
219 | default:
220 | return nil
221 | }
222 | }
223 | }
224 | type x struct{}
225 | out := protoimpl.TypeBuilder{
226 | File: protoimpl.DescBuilder{
227 | GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
228 | RawDescriptor: file_ProductInfo_proto_rawDesc,
229 | NumEnums: 0,
230 | NumMessages: 2,
231 | NumExtensions: 0,
232 | NumServices: 1,
233 | },
234 | GoTypes: file_ProductInfo_proto_goTypes,
235 | DependencyIndexes: file_ProductInfo_proto_depIdxs,
236 | MessageInfos: file_ProductInfo_proto_msgTypes,
237 | }.Build()
238 | File_ProductInfo_proto = out.File
239 | file_ProductInfo_proto_rawDesc = nil
240 | file_ProductInfo_proto_goTypes = nil
241 | file_ProductInfo_proto_depIdxs = nil
242 | }
243 |
244 | // Reference imports to suppress errors if they are not otherwise used.
245 | var _ context.Context
246 | var _ grpc.ClientConnInterface
247 |
248 | // This is a compile-time assertion to ensure that this generated file
249 | // is compatible with the grpc package it is being compiled against.
250 | const _ = grpc.SupportPackageIsVersion6
251 |
252 | // ProductInfoClient is the client API for ProductInfo service.
253 | //
254 | // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
255 | type ProductInfoClient interface {
256 | //添加商品
257 | AddProduct(ctx context.Context, in *Product, opts ...grpc.CallOption) (*ProductId, error)
258 | //获取商品
259 | GetProduct(ctx context.Context, in *ProductId, opts ...grpc.CallOption) (*Product, error)
260 | }
261 |
262 | type productInfoClient struct {
263 | cc grpc.ClientConnInterface
264 | }
265 |
266 | func NewProductInfoClient(cc grpc.ClientConnInterface) ProductInfoClient {
267 | return &productInfoClient{cc}
268 | }
269 |
270 | func (c *productInfoClient) AddProduct(ctx context.Context, in *Product, opts ...grpc.CallOption) (*ProductId, error) {
271 | out := new(ProductId)
272 | err := c.cc.Invoke(ctx, "/product.ProductInfo/addProduct", in, out, opts...)
273 | if err != nil {
274 | return nil, err
275 | }
276 | return out, nil
277 | }
278 |
279 | func (c *productInfoClient) GetProduct(ctx context.Context, in *ProductId, opts ...grpc.CallOption) (*Product, error) {
280 | out := new(Product)
281 | err := c.cc.Invoke(ctx, "/product.ProductInfo/getProduct", in, out, opts...)
282 | if err != nil {
283 | return nil, err
284 | }
285 | return out, nil
286 | }
287 |
288 | // ProductInfoServer is the server API for ProductInfo service.
289 | type ProductInfoServer interface {
290 | //添加商品
291 | AddProduct(context.Context, *Product) (*ProductId, error)
292 | //获取商品
293 | GetProduct(context.Context, *ProductId) (*Product, error)
294 | }
295 |
296 | // UnimplementedProductInfoServer can be embedded to have forward compatible implementations.
297 | type UnimplementedProductInfoServer struct {
298 | }
299 |
300 | func (*UnimplementedProductInfoServer) AddProduct(context.Context, *Product) (*ProductId, error) {
301 | return nil, status.Errorf(codes.Unimplemented, "method AddProduct not implemented")
302 | }
303 | func (*UnimplementedProductInfoServer) GetProduct(context.Context, *ProductId) (*Product, error) {
304 | return nil, status.Errorf(codes.Unimplemented, "method GetProduct not implemented")
305 | }
306 |
307 | func RegisterProductInfoServer(s *grpc.Server, srv ProductInfoServer) {
308 | s.RegisterService(&_ProductInfo_serviceDesc, srv)
309 | }
310 |
311 | func _ProductInfo_AddProduct_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
312 | in := new(Product)
313 | if err := dec(in); err != nil {
314 | return nil, err
315 | }
316 | if interceptor == nil {
317 | return srv.(ProductInfoServer).AddProduct(ctx, in)
318 | }
319 | info := &grpc.UnaryServerInfo{
320 | Server: srv,
321 | FullMethod: "/product.ProductInfo/AddProduct",
322 | }
323 | handler := func(ctx context.Context, req interface{}) (interface{}, error) {
324 | return srv.(ProductInfoServer).AddProduct(ctx, req.(*Product))
325 | }
326 | return interceptor(ctx, in, info, handler)
327 | }
328 |
329 | func _ProductInfo_GetProduct_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
330 | in := new(ProductId)
331 | if err := dec(in); err != nil {
332 | return nil, err
333 | }
334 | if interceptor == nil {
335 | return srv.(ProductInfoServer).GetProduct(ctx, in)
336 | }
337 | info := &grpc.UnaryServerInfo{
338 | Server: srv,
339 | FullMethod: "/product.ProductInfo/GetProduct",
340 | }
341 | handler := func(ctx context.Context, req interface{}) (interface{}, error) {
342 | return srv.(ProductInfoServer).GetProduct(ctx, req.(*ProductId))
343 | }
344 | return interceptor(ctx, in, info, handler)
345 | }
346 |
347 | var _ProductInfo_serviceDesc = grpc.ServiceDesc{
348 | ServiceName: "product.ProductInfo",
349 | HandlerType: (*ProductInfoServer)(nil),
350 | Methods: []grpc.MethodDesc{
351 | {
352 | MethodName: "addProduct",
353 | Handler: _ProductInfo_AddProduct_Handler,
354 | },
355 | {
356 | MethodName: "getProduct",
357 | Handler: _ProductInfo_GetProduct_Handler,
358 | },
359 | },
360 | Streams: []grpc.StreamDesc{},
361 | Metadata: "ProductInfo.proto",
362 | }
363 |
--------------------------------------------------------------------------------
/secure-demo/ProductInfo.proto:
--------------------------------------------------------------------------------
1 | syntax = "proto3";
2 | package product;
3 |
4 | service ProductInfo {
5 | //添加商品
6 | rpc addProduct(Product) returns (ProductId);
7 | //获取商品
8 | rpc getProduct(ProductId) returns (Product);
9 | }
10 |
11 | message Product {
12 | string id = 1;
13 | string name = 2;
14 | string description = 3;
15 | }
16 |
17 | message ProductId {
18 | string value = 1;
19 | }
20 |
--------------------------------------------------------------------------------
/secure-demo/certs/ca.crt:
--------------------------------------------------------------------------------
1 | -----BEGIN CERTIFICATE-----
2 | MIIFgDCCA2gCCQC2kD8dAwkffzANBgkqhkiG9w0BAQsFADCBgTELMAkGA1UEBhMC
3 | VVMxEzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcx
4 | ITAfBgNVBAoMGE/DosKAwplSZWlsbHkgTWVkaWEsIEluYzETMBEGA1UECwwKUHVi
5 | bGlzaGVyczENMAsGA1UEAwwENDJDQTAeFw0xOTA4MTgwNjE4MDBaFw0yMTA4MTcw
6 | NjE4MDBaMIGBMQswCQYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQG
7 | A1UEBwwNTW91bnRhaW4gVmlldzEhMB8GA1UECgwYT8OiwoDCmVJlaWxseSBNZWRp
8 | YSwgSW5jMRMwEQYDVQQLDApQdWJsaXNoZXJzMQ0wCwYDVQQDDAQ0MkNBMIICIjAN
9 | BgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEApuI7yuoXiUaiRJnYyJ1uV9T2r0PB
10 | 3BA6uyHcg/Cenp9v4I9hVtS1O1yDyNe23felP9pEkXJBnKl9IAAJftC/cjsYbX2y
11 | cO91O7n3L1DtWPSR0+zMT32waU0E7llqp5ejExr5BMfodm6Oxtqd1T/LrGAf361a
12 | YDvyzsAjlusVe83zOH5R07M7v+ap5PYQJ1KjxBbOoAFuc0EWGwfbtq9P0SCcLExR
13 | 50I2ahLFOss5tuOT36pNVI80GSDyIjJwPOkHG83JAZsDPeA+NEZcJvmrPxbUES0K
14 | 9PFUTDwUjzrn7D931lPHgFhK4U/IAmhlePpJcq+ioTQA/NsLvA5I2JtBlnflwa5N
15 | rO8y1UP/E15UDxNIN4ICeLjGu3umdRi89LlG6DhwmB7Mx04nnm2yCP5YYfsY3Tku
16 | 4ElQwebXyDYo7yoLxyw1MrDweQOXOWtS7/X6BSZgv7z8hPqYyZ06+HlrYNwLN2Pn
17 | 74+m0zzomA9IRrwuWpSokibW+VJ2pS4C9ZF2gNS/GAu3GFJ5m4Hi9iLlBqc4D209
18 | rCOjxAqwONsZx3ebiOQUeHwL050FRFNhVhD9qViLWX2OreW4w8h5pDrhnV1SivQV
19 | PhcSq9fhVOQ95a1elchaRWLL2DUeevrrTebfO7eULthmm+TP2zLGX5L6ah6Kqhyj
20 | kNvR8xWpA2ZtEO8CAwEAATANBgkqhkiG9w0BAQsFAAOCAgEAQjpx6Vb8s88W63Tc
21 | aMd5kYHC4C53tZOAYw4hjCtnsivqaZpv0viemWiKMkIaeo4ChB4qcZVWdOEIpnMf
22 | dwrSlWx1YOEs5RtMqn1YTO7Al79QkNSPPV0e8LofzRkp3EwZvEW1o9UZvWnn94Ad
23 | Qm1LSk2IOSE4FLCkd8MrIRdHPjlPl7x0lgJfA769/Mg/VP5Zspe9HpGKxItLPlzB
24 | YIVymb1o3ZGIIRZTQP3kdA/lwaa7wGhgsHZfX0p85MSuiCKpLIOLatZGUd2F/3K9
25 | qlox3YSYwyFCmnKxnbeKhsF15hlQetU0vVc+miM9oSmGqCD7DKHCRHZjuyGrooTC
26 | X+ppId7ypxsx4BZFvn3HpQdEBQdAIpbLJL+sDoesOOVeyjugIdHrC4crWfUevvsk
27 | bzP8e7VEJcus40U345qiCwTavL0JZGqVfus5aUtQyRCqvsk4ZtbuzK5aiPBogq+6
28 | 8g8iFU8UJ71xKMkYZ6eBuobTjCZ0iWHDkH0uKbYPD+3nTbY5pkqkRukMBBTEIvs4
29 | SOi+gD4VHy879GmBVKu5pJxNQmhxkpi/O9WZAxLBHeRUyKqwfGHEquIGZ0EQJWGD
30 | YNadlON1EWjt6jl/dzDNlq/ygJg82DsC8qEr7aHqhTC+pGzFb7qdpli2wWWgZqWB
31 | 253z3lqkeHt3eZzhVVe557VDvJg=
32 | -----END CERTIFICATE-----
33 |
--------------------------------------------------------------------------------
/secure-demo/certs/client.crt:
--------------------------------------------------------------------------------
1 | -----BEGIN CERTIFICATE-----
2 | MIICEzCCAZkCCQDszoZfd2njmzAKBggqhkjOPQQDAjBzMQswCQYDVQQGEwJVUzET
3 | MBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzESMBAG
4 | A1UEAwwJbG9jYWxob3N0MSMwIQYJKoZIhvcNAQkBFhRka25rdXJ1cHB1QGdtYWls
5 | LmNvbTAeFw0xOTA3MjAwODI5NDVaFw0yOTA3MTcwODI5NDVaMHMxCzAJBgNVBAYT
6 | AlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRYwFAYDVQQHDA1Nb3VudGFpbiBWaWV3
7 | MRIwEAYDVQQDDAlsb2NhbGhvc3QxIzAhBgkqhkiG9w0BCQEWFGRrbmt1cnVwcHVA
8 | Z21haWwuY29tMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE24ibiJD/DewZm5DI8jMi
9 | +kQmh3p4a/QYRMnJF/JRvIkhWcVjXsjTXm9CLAxf/jEgzaChS+3S7o2SI2zNOyUm
10 | 0DimiqsyKqSoxH11gUavHHkXdcJP9lYorRNn6V4JsxVCMAoGCCqGSM49BAMCA2gA
11 | MGUCMQCwnwZQoEYZhuYkq5b739MbasBhx9d/AbFdh6ywJ5a9SF/5yajPi/738n4u
12 | qLtzAZkCMBOBuEEe8hqQ4mZRNRTBsP6aZVMGZyVifTr0laQV3Pc6R97vO0TUOR6H
13 | O92vhCY2Rw==
14 | -----END CERTIFICATE-----
15 |
--------------------------------------------------------------------------------
/secure-demo/certs/client.key:
--------------------------------------------------------------------------------
1 | -----BEGIN RSA PRIVATE KEY-----
2 | MIIEogIBAAKCAQEA8GKNkiTbBW5gMIcr3UEAtNvn5AZmAiOMh+oJOkNmSW5koKHB
3 | QCuNrU0DwbLWyf2S0c1Lqpzx3wetxfTw9HurvsWowmOGOI2sO8a9ksnvrH/NY4K1
4 | w8OX37w3SBD0ayWlt183d/3YXzlpPij/LXIuRyiSo45MK9rL4N/Ni7MDZo//dt6I
5 | DHp5TULaVWEt5FLOD9EIsaXWEmyDT+dr2V9W40Kg6jxyS49Yk13oJmB0DOvX7Jr2
6 | qJsWJKXXD1D+mab/twqXGdUQurNukKBgEFmj/KPiYVZTmGXtPPC4/2F1K4KGfPdb
7 | yPG1TKIWvFSa7A/ZvesA6G++IfpsicqdzijLBwIDAQABAoIBAFibKy3sceMdnU0l
8 | 9hA3Lqh7yo0topo1Ok67AK2+PEzi6SqglRgvNajkk3bpkeygkGbPMo3wDeO08+Pc
9 | 9phXoaXPO/ZzMv1Tk2HxTt11m+fMsAt3GcLQLQImYYYp4b5BAUWHTm3nXsMy6U0l
10 | VXIN/WrzVKH/CKq9mpsIQ76zvJQn1w3de0VW+9ymajo4LY9KWPeomlo2VIMiMHIz
11 | ioL1eISTUdMdx0UcUiWUNgx171CBqR85tEEjuJO+YKUGUN1j06SJWMxUtm+Y2T/2
12 | 4XqbyFwvCNhwlRdUk1vUO9mICqDX4bMdCS6iU4eXijtr98pxcvhOWt9o1iuRhosO
13 | h+EHGjECgYEA/DXSSFoul8FOMb5lMzHxtMm90CIh4dY8fTLbDvBpZZ1/6VDyaqMI
14 | 0wIWJD3dn90vHaGNS7qA/rotkPx/00OQtZw9j59B6j4fohI6m0HL7yrw18xFBX5X
15 | usE6iOfCDzNkQkIyrfuYRZvCw7ZC0G9a+CDxSCdBv+yWCVWMw1aa4c8CgYEA8/8+
16 | RwVonnAHXTmxDD20Gt+1lSw4whrR2Yly2lW4r0212QdeNAJlMLyhWTpwdJgBNjAb
17 | L1BRf1QZbGOktvAs+mCFWxhikGHxdbFhRVOD/96wApuqSxUcKvRw38GdozD3snEl
18 | Yxrfxu3ZRmyDCuIBB4h3VzgbKn2VnyA48o836UkCgYANvBychhS9fPB2Mwkt1Y11
19 | K/tjR0iTFOisZMWbNap3tzENErRw7DoBy75K8PeNyizTr0WTly+JL7hlieqoJajO
20 | yxhrJuAfEo0EdXutktK5TpxZFC26E9xRNk6qv/xIeaL/HL3HzcjIGahsohNXaIkK
21 | tDiPllu1SPwOvBLzXFcI7wKBgEsb0UHvikrrVXj/H18TR3PWVYE8AaTOuLZsNyy6
22 | ooVkOIw8VmVQL3IXPtvGv4NEn2rc2CFyagP2EXVqHvQpbs8ME0D9eqnTXI7MMZMz
23 | qDiFhkznOj6umuMmJ/DZGvt3QWhuqAGf7i7AXNfu40/gTkzRV1tD7CjiS8KWGrGg
24 | IKfxAoGANBPi7T0owCif9iuNY59/vGl56PmZDpKrHTSt10GeyhM0tgHQv5Fkgp/T
25 | NeG3biWW9P4awSd3ngY3ImUXjE+e5AMChBSsRXTDgjwoYV7AvJGyfVV7/sk5PGXd
26 | 3J9efSSGAnOhMarAityl6pnnPTQsmGRFm2QvnMA14B34ZIkntK0=
27 | -----END RSA PRIVATE KEY-----
28 |
--------------------------------------------------------------------------------
/secure-demo/certs/server.crt:
--------------------------------------------------------------------------------
1 | -----BEGIN CERTIFICATE-----
2 | MIICEzCCAZkCCQDszoZfd2njmzAKBggqhkjOPQQDAjBzMQswCQYDVQQGEwJVUzET
3 | MBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzESMBAG
4 | A1UEAwwJbG9jYWxob3N0MSMwIQYJKoZIhvcNAQkBFhRka25rdXJ1cHB1QGdtYWls
5 | LmNvbTAeFw0xOTA3MjAwODI5NDVaFw0yOTA3MTcwODI5NDVaMHMxCzAJBgNVBAYT
6 | AlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRYwFAYDVQQHDA1Nb3VudGFpbiBWaWV3
7 | MRIwEAYDVQQDDAlsb2NhbGhvc3QxIzAhBgkqhkiG9w0BCQEWFGRrbmt1cnVwcHVA
8 | Z21haWwuY29tMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE24ibiJD/DewZm5DI8jMi
9 | +kQmh3p4a/QYRMnJF/JRvIkhWcVjXsjTXm9CLAxf/jEgzaChS+3S7o2SI2zNOyUm
10 | 0DimiqsyKqSoxH11gUavHHkXdcJP9lYorRNn6V4JsxVCMAoGCCqGSM49BAMCA2gA
11 | MGUCMQCwnwZQoEYZhuYkq5b739MbasBhx9d/AbFdh6ywJ5a9SF/5yajPi/738n4u
12 | qLtzAZkCMBOBuEEe8hqQ4mZRNRTBsP6aZVMGZyVifTr0laQV3Pc6R97vO0TUOR6O
13 | O92vhCY2Rw==
14 | -----END CERTIFICATE-----
15 |
--------------------------------------------------------------------------------
/secure-demo/certs/server.key:
--------------------------------------------------------------------------------
1 | -----BEGIN EC PARAMETERS-----
2 | BgUrgQQAIg==
3 | -----END EC PARAMETERS-----
4 | -----BEGIN EC PRIVATE KEY-----
5 | MIGkAgEBBDBT8nJZJoXJDYpxA7i2aYmOmuN0nxDasu+9WJoUoADXY+Aeni57bsPt
6 | J9cBkp4J5oygBwYFK4EEACKhZANiAATbiJuIkP8N7BmbkMjyMyL6RCaHenhr9BhE
7 | yckX8lG8iSFZxWNeyNNeb0IsDF/+MSDNoKFL7dLujZIjbM07JSbQOKaKqzIqpKjE
8 | fXWBRq8ceRd1wk/2ViitE2fpXgmzFUI=
9 | -----END EC PRIVATE KEY-----
10 |
--------------------------------------------------------------------------------
/secure-demo/certs/server.pem:
--------------------------------------------------------------------------------
1 | -----BEGIN PRIVATE KEY-----
2 | MIG2AgEAMBAGByqGSM49AgEGBSuBBAAiBIGeMIGbAgEBBDBT8nJZJoXJDYpxA7i2
3 | aYmOmuN0nxDasu+9WJoUoADXY+Aeni57bsPtJ9cBkp4J5oyhZANiAATbiJuIkP8N
4 | 7BmbkMjyMyL6RCaHenhr9BhEyckX8lG8iSFZxWNeyNNeb0IsDF/+MSDNoKFL7dLu
5 | jZIjbM07JSbQOKaKqzIqpKjEfXWBRq8ceRd1wk/2ViitE2fpXgmzFUI=
6 | -----END PRIVATE KEY-----
7 |
--------------------------------------------------------------------------------
/secure-demo/client/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "context"
5 | "crypto/tls"
6 | "crypto/x509"
7 | "google.golang.org/grpc"
8 | "google.golang.org/grpc/credentials"
9 | "grpc-demo/product"
10 | "io/ioutil"
11 | "log"
12 | )
13 |
14 | const (
15 | address = "localhost:50051"
16 | hostname = "localhost"
17 |
18 | //certFile = "secure-demo/certs/client.crt"
19 |
20 | clientCert = "secure-demo/certs/client.crt"
21 | clientKey = "secure-demo/certs/client.key"
22 | caFile = "secure-demo/certs/ca.crt"
23 | )
24 |
25 | func main() {
26 | // 单向 TLS 的代码
27 |
28 | //credds, err := credentials.NewClientTLSFromFile(certFile, hostname)
29 | //if err != nil {
30 | // log.Println("new tls client err.", err)
31 | // return
32 | //}
33 | //
34 | //opts := []grpc.DialOption{
35 | // grpc.WithTransportCredentials(credds),
36 | //}
37 | //conn, err := grpc.Dial(address, opts...)
38 | //
39 |
40 | // mTLS的代码
41 | keyPair, err := tls.LoadX509KeyPair(clientCert, clientKey)
42 | if err != nil {
43 | log.Fatal("failed to load client cert.", err)
44 | return
45 | }
46 |
47 | certPool := x509.NewCertPool()
48 | ca, err := ioutil.ReadFile(caFile)
49 | if err != nil {
50 | log.Fatal("can`t not read ca file.", err)
51 | return
52 | }
53 | if ok := certPool.AppendCertsFromPEM(ca); !ok {
54 | log.Fatalf("failed to append ca file")
55 | return
56 | }
57 |
58 | opts := []grpc.DialOption{
59 | grpc.WithTransportCredentials(
60 | credentials.NewTLS(&tls.Config{
61 | ServerName: hostname,
62 | Certificates: []tls.Certificate{keyPair},
63 | RootCAs: certPool,
64 | }),
65 | ),
66 | }
67 |
68 | conn, err := grpc.Dial(address, opts...)
69 | if err != nil {
70 | log.Println("did not connect.", err)
71 | return
72 | }
73 | defer conn.Close()
74 |
75 | client := product.NewProductInfoClient(conn)
76 | ctx := context.Background()
77 |
78 | id := AddProduct(ctx, client)
79 | GetProduct(ctx, client, id)
80 | }
81 |
82 | // 添加一个测试的商品
83 | func AddProduct(ctx context.Context, client product.ProductInfoClient) (id string) {
84 | aMac := &product.Product{Name: "Mac Book Pro 2019", Description: "From Apple Inc."}
85 | productId, err := client.AddProduct(ctx, aMac)
86 | if err != nil {
87 | log.Println("add product fail.", err)
88 | return
89 | }
90 | log.Println("add product success, id = ", productId.Value)
91 | return productId.Value
92 | }
93 |
94 | // 获取一个商品
95 | func GetProduct(ctx context.Context, client product.ProductInfoClient, id string) {
96 | p, err := client.GetProduct(ctx, &product.ProductId{Value: id})
97 | if err != nil {
98 | log.Println("get product err.", err)
99 | return
100 | }
101 | log.Printf("get prodcut success : %+v\n", p)
102 | }
103 |
--------------------------------------------------------------------------------
/secure-demo/server/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "context"
5 | "crypto/tls"
6 | "crypto/x509"
7 | "github.com/gofrs/uuid"
8 | "google.golang.org/grpc"
9 | "google.golang.org/grpc/codes"
10 | "google.golang.org/grpc/credentials"
11 | "google.golang.org/grpc/status"
12 | "grpc-demo/product"
13 | "io/ioutil"
14 | "log"
15 | "net"
16 | )
17 |
18 | const (
19 | port = ":50051"
20 |
21 | //certFile = "secure-demo/certs/server.crt"
22 | //keyFile = "secure-demo/certs/server.key"
23 |
24 | serverCert = "secure-demo/certs/server.crt"
25 | serverKey = "secure-demo/certs/server.key"
26 | caFile = "secure-demo/certs/ca.crt"
27 | )
28 |
29 | func main() {
30 | listener, err := net.Listen("tcp", port)
31 | if err != nil {
32 | log.Println("net listen err ", err)
33 | return
34 | }
35 |
36 | // 单向 TLS 的代码
37 | //// 加载证书
38 | //x509KeyPair, err := tls.LoadX509KeyPair(certFile, keyFile)
39 | //if err != nil {
40 | // log.Println("load cert err.", err)
41 | // return
42 | //}
43 | //
44 | //opts := []grpc.ServerOption{
45 | // grpc.Creds(credentials.NewServerTLSFromCert(&x509KeyPair)),
46 | //}
47 | //
48 | //s := grpc.NewServer(opts...)
49 |
50 | // mTLS 的代码
51 | keyPair, err := tls.LoadX509KeyPair(serverCert, serverKey)
52 | if err != nil {
53 | log.Fatal("failed to load key pair.", err)
54 | return
55 | }
56 |
57 | certPool := x509.NewCertPool()
58 | ca, err := ioutil.ReadFile(caFile)
59 | if err != nil {
60 | log.Fatal("can`t not read ca file.", err)
61 | return
62 | }
63 | if ok := certPool.AppendCertsFromPEM(ca); !ok {
64 | log.Fatalf("failed to append ca file")
65 | return
66 | }
67 |
68 | // 为所有传入的连接启用TLS
69 | opts := []grpc.ServerOption{
70 | grpc.Creds(
71 | credentials.NewTLS(&tls.Config{
72 | ClientAuth: tls.RequestClientCert,
73 | Certificates: []tls.Certificate{keyPair},
74 | ClientCAs: certPool,
75 | }),
76 | ),
77 | }
78 |
79 | s := grpc.NewServer(opts...)
80 | product.RegisterProductInfoServer(s, &server{})
81 | log.Println("start gRPC listen on port " + port)
82 | if err := s.Serve(listener); err != nil {
83 | log.Println("failed to serve...", err)
84 | return
85 | }
86 | }
87 |
88 | type server struct {
89 | productMap map[string]*product.Product
90 | }
91 |
92 | //添加商品
93 | func (s *server) AddProduct(ctx context.Context, req *product.Product) (resp *product.ProductId, err error) {
94 | resp = &product.ProductId{}
95 | out, err := uuid.NewV4()
96 | if err != nil {
97 | return resp, status.Errorf(codes.Internal, "err while generate the uuid ", err)
98 | }
99 |
100 | req.Id = out.String()
101 | if s.productMap == nil {
102 | s.productMap = make(map[string]*product.Product)
103 | }
104 |
105 | s.productMap[req.Id] = req
106 | resp.Value = req.Id
107 | return
108 | }
109 |
110 | //获取商品
111 | func (s *server) GetProduct(ctx context.Context, req *product.ProductId) (resp *product.Product, err error) {
112 | if s.productMap == nil {
113 | s.productMap = make(map[string]*product.Product)
114 | }
115 |
116 | resp = s.productMap[req.Value]
117 | return
118 | }
119 |
--------------------------------------------------------------------------------