一、go環境安裝
1、下載 golang.google.cn
2、下載並安裝,然後配置環境變量。我將壓縮包下載到D盤的自己建立的go文件夾,然後解壓縮生成go,在自己建立的go文件夾的同級目錄下建立go_work文件夾。
3、添加系統變量
4、編輯path
over
二、下載並配置protoc.exe
1、下載Release Protocol Buffers v3.19.4 · protocolbuffers/protobuf
2、 選擇最新的 protoc-3.19.0-win64.zip,解壓縮,找到bin目錄下的protoc.exe,將protoc.exe放到go環境的bin目錄下。
3、 為了確保能找到protoc.exe,需要在系統環境變量的PATH設置。
4、可以使用命令查看版本 protoc --version
三、安裝protobuf和grpc
1、安裝protobuf
1)執行 go get -u github.com/golang/protobuf/proto
報錯:go get: module github.com/golang/protobuf/protoc-gen-go: Get
“https://proxy.golang.org/github.com/golang/protobuf/protoc-gen-go/@v/list”:
dial tcp 142.251.42.241:4 43: connectex: A connection attempt failed
because the connected party did not properly respond after a period of
time, or established connection failed because connected host has
failed to respond.
解決辦法,先執行如下兩條命令:
go env -w GO111MODULE=on
go env -w GOPROXY=https://goproxy.cn,direct
再執行go get下載(如果還繼續報錯,那看看是不是下面的錯誤)
2) 執行go get -u github.com/golang/protobuf/protoc-gen-go
報錯: go: module github.com/golang/protobuf is deprecated: Use the
“google.golang.org/protobuf” module instead. go get: installing
executable with ‘go get’ in module mode is deprecated.
Use ‘go install pkg@version’ instead.
For more information, see https://golang.org/doc/go-get-install-deprecation
or run ‘go help get’ or ‘go help install’.
解決辦法,報了兩個錯誤:
現在想要拉取protoc-gen-go需要去google.golang.org/protobuf拉取,原來的路徑已經廢棄了。
使用的go版本是1.17。而Go1.17版使用go install安裝依賴。所以應該按照它下面的格式go install pkg@version進行拉取。
所以拉取命令如下:
go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
報錯: go install: google.golang.org/protobuf/cmd/proto@latest: module
google.golang.org/protobuf@latest found (v1.28.0), but does not
contain package google.golang.org/protobuf/cmd/proto
解決辦法:
找到GOPATH/src目錄,新建google.golang.org文件夾。(如果有,可以把裏面的內容刪除)在google.golang.org目錄下打開cmd,執行:
git clone https://e.coding.net/robinqiwei/googleprotobuf.git protobuf
安裝完後,會在bin目錄下生成protoc-gen-go.exe
使用命令安裝grpc
go get -u google.golang.org/grpc
如果不行
- 下載net包: git clone https://github.com/golang/net.git $GOPATH/src/golang.org/x/net#
- 下載text包:git clone https://github.com/golang/text.git $GOPATH/src/golang.org/x/text
- 下載go-genproto包:git clone https://github.com/google/go-genproto.git $GOPATH/src/google.golang.org/genproto
- 下載grpc-go包:git clone https://github.com/grpc/grpc-go.git $GOPATH/src/google.golang.org/grpc
切換到GOPATH/src目錄,執行如下命令: go installgoogle.golang.org/grpc 四、測試
1、 www.grpc.io(進入網站可看到如下頁面)
綠色框的內容我們已經完成了,可以將紅色框的內容執行一遍。
2、下載grpc實例
git clone -b v1.46.0 --depth 1 https://github.com/grpc/grpc-go
3、運行實例
1)可以用編譯器打開其中的examples文件夾
2)啓動終端執行:go run greeter_server/main.go
3)另起終端編譯並執行:go run greeter_client/main.go
4)其中最重要的文件是這兩個pb.go文件,但是我們下載下來的例子其實是自帶這兩個文件的。
將這兩個文件刪除後就會發現我們的程序不好用了。
重新編譯生成pb.go文件
protoc --go_out=. --go_opt=paths=source_relative --go-grpc_out=. --go-grpc_opt=paths=source_relative helloworld/helloworld.proto //一整行的命令