项目的目录结构
.
├── Makefile
├── client
│ └── main.go
├── go.mod
├── go.sum
├── pb
│ ├── entity.pb.go
│ └── entity.proto
└── server
└── main.go
proto文件介绍
syntax = "proto3";
option go_package = "../pb";
package pb;
service Query{
//通过城市名称获取天气预报详细信息,这是最普通的数据传输方式,一问一答
//客户端发送请求,只有服务端返回时,客户端才能继续发送第二个请求,阻塞式
rpc GetByName(WeatherRequest) returns(WeatherResponse);
//通过城市id获取天气预报,同上
rpc GetById(WeatherRequest) returns(WeatherResponse);
//客户端通过流的方式进行发送数据,而服务端等到客户端的请求发送完毕后
//一次性返回数据给客户端,此时服务端需要从客户端的流中循环读取从
//客户端发送过来的数据,直到收到客户端发送完毕的信号,才一次性返回数据
rpc GetByStream(stream WeatherRequest) returns(StreamResp);
//客户端发送一个普通的请求,但是服务端是采用流的方式返回数据
//此种使用场景如:用户发送一个城市ID,服务端需要返回这个城市下面的
//所有县级市的所有信息,服务端每次处理一个县级市信息,每次处理完
//一个县级市,就立即返回给客户端,此时客户端进行读取服务端的返回时
//需要从服务端的流中循环读取返回数据,直到收到服务端返回完毕的信号
//后,才停止接收返回数据
rpc ReturnByStream(CityRequest) returns(stream CityResp);
//双向流,客户端通过流的方式不断的向服务端发送商品id
//服务端每接收到一个商品ID后,立即查询商品详情,查到后立即通过流的方式返回给客户端
//此时客户端需要不断的向服务端发送数据,服务端需要不断的从客户端的流中读取请求数据
//同时处理请求数据,每处理完一个请求就立即返回,客户端此时也需要不断的从服务端的流
//中读取返回数据
rpc BidirectionalStream(stream Product) returns(stream Product);
}
//商品
message Product {
int64 id = 1;//商品id
string name = 2;//商品名称
}
//通过流的方式返回天气
message StreamResp{
repeated WeatherResponse results = 1;
}
//城市请求体
message CityRequest{
string province = 1;
}
//城市返回体
message CityResp{
string cityname = 1;
}
//天气预报result字段
message Result{
string city = 1;
Realtime realtime = 2;
repeated Future future = 3;
}
//天气预报实时字段
message Realtime{
string temperature = 1;
string humidity = 2;
string info = 3;
string wid = 4;
string direct = 5;
string power = 6;
string aqi = 7;
}
message Wid {
string day = 1;
string night = 2;
}
//天气预报未来预报
message Future{
string date = 1;
string temperature = 2;
string weather = 3;
Wid wid = 4;
string direct = 5;
}
//天气预报返回实体
message WeatherResponse {
string reason = 1;
Result result = 2;
int64 error_code = 3;
}
//天气预报请求实体
message WeatherRequest{
string city = 1;
string key = 2;
string province = 3;
}
生成的服务端代码
package main
import (
"context"
"encoding/json"
"fmt"
"google.golang.org/grpc"
"io"
"io/ioutil"
"juhe.cn.weather_report/pb"
"log"
"net"
"net/http"
"strconv"
"time"
)
const key = "2d1b16a202************"
func main() {
listen, err := net.Listen("tcp", ":8080")
if err != nil {
log.Fatalf("failed to listen:%v", err)
}
s := grpc.NewServer()
pb.RegisterQueryServer(s, &weatherServer{})
log.Printf("server listening at %v", listen.Addr())
if err := s.Serve(listen); err != nil {
log.Fatalf("failed to server:%v", err)
}
}
/**
* @author micro.cloud.fly
* @date 2022/3/25 3:08 下午
* @desc 天气预报服务端
*/
type weatherServer struct {
pb.UnimplementedQueryServer
}
type WeaResp struct {
Reason string `json:"reason"`
Result struct {
City string `json:"city"`
Realtime struct {
Temperature string `json:"temperature"`
Humidity string `json:"humidity"`
Info string `json:"info"`
Wid string `json:"wid"`
Direct string `json:"direct"`
Power string `json:"power"`
Aqi string `json:"aqi"`
} `json:"realtime"`
Future []struct {
Date string `json:"date"`
Temperature string `json:"temperature"`
Weather string `json:"weather"`
Wid struct {
Day string `json:"day"`
Night string `json:"night"`
} `json:"wid"`
Direct string `json:"direct"`
} `json:"future"`
} `json:"result"`
ErrorCode int64 `json:"error_code"`
}
//客户端通过流的方式发送数据过来,那么此时服务端,需要不断的读取客户端发送来
//的数据,等全部收到之后,一次行把数据返回给客户端
func (ws *weatherServer) GetByStream(qgs pb.Query_GetByStreamServer) error {
var respArr []*pb.WeatherResponse
for {
recv, err := qgs.Recv()
if err == io.EOF {
return qgs.SendAndClose(&pb.StreamResp{Results: respArr})
}
if err != nil {
fmt.Println(err)
return err
}
//不断取得从客户端发来的数据,不断调用接口
log.Println("收到:", recv.GetCity())
resp := httpGet(recv.GetCity())
log.Println("聚合返回:", resp)
var weaResp WeaResp
_ = json.Unmarshal([]byte(resp), &weaResp)
respArr = append(respArr, &pb.WeatherResponse{
Reason: weaResp.Reason,
Result: &pb.Result{
City: weaResp.Result.City,
Realtime: &pb.Realtime{Aqi: weaResp.Result.Realtime.Aqi},
},
ErrorCode: weaResp.ErrorCode,
})
}
}
func (ws *weatherServer) GetByName(ctx context.Context, weaRequest *pb.WeatherRequest) (*pb.WeatherResponse, error) {
log.Println("收到:", weaRequest.City)
resp := httpGet(weaRequest.GetCity())
var weaResp WeaResp
err := json.Unmarshal([]byte(resp), &weaResp)
fu := &pb.Future{
Date: weaResp.Result.Future[0].Date,
Temperature: weaResp.Result.Future[0].Temperature,
Weather: weaResp.Result.Future[0].Weather,
Direct: weaResp.Result.Future[0].Direct,
}
fuArr := []*pb.Future{fu}
return &pb.WeatherResponse{
Reason: weaResp.Reason,
Result: &pb.Result{
City: weaResp.Result.City,
Realtime: &pb.Realtime{Aqi: weaResp.Result.Realtime.Aqi},
Future: fuArr,
},
ErrorCode: weaResp.ErrorCode,
}, err
}
//客户端一次发送一个省份名字,服务端通过流的方式,每次查到这个省份的一个城市后,就写入流中
//返回给客户端
func (ws *weatherServer) ReturnByStream(request *pb.CityRequest, qrs pb.Query_ReturnByStreamServer) error {
//取出客户端发送来省份名
jiangsu_city := []string{"徐州", "苏州", "南京", "镇江"}
zhejiang_city := []string{"宁波", "舟山", "杭州", "温州"}
if request.GetProvince() == "江苏" {
for _, s := range jiangsu_city {
err := qrs.Send(&pb.CityResp{Cityname: s})
if err != nil {
return err
}
time.Sleep(time.Second * 2)
}
} else {
for _, s := range zhejiang_city {
err := qrs.Send(&pb.CityResp{Cityname: s})
if err != nil {
return err
}
time.Sleep(time.Second * 2)
}
}
return nil
}
//客户端和服务端都是使用的流,客户端发送一个,服务端就返回一个,直到结束
func (ws *weatherServer) BidirectionalStream(stream pb.Query_BidirectionalStreamServer) error {
for {
req, err := stream.Recv()
if err == io.EOF {
//此时表示客户端发送结束了
return nil
}
if err != nil {
//此时表示真正有错误了
return err
}
//此时接收到一个请求,服务端就返回一个请求
fmt.Println("收到请求:",req.Id)
err = stream.Send(&pb.Product{
Id: req.Id,
Name: strconv.Itoa(int(req.Id)) + "name",
})
fmt.Println("回复客户端:",req.Id)
if err != nil {
log.Fatal(err)
}
time.Sleep(time.Second * 5)
}
return nil
}
func (ws *weatherServer) GetById(ctx context.Context, weaRequest *pb.WeatherRequest) (*pb.WeatherResponse, error) {
log.Println("收到:", weaRequest.GetCity())
resp := httpGet(weaRequest.GetCity())
log.Println("聚合返回:", resp)
var weaResp WeaResp
err := json.Unmarshal([]byte(resp), &weaResp)
fu := &pb.Future{
Date: weaResp.Result.Future[0].Date,
Temperature: weaResp.Result.Future[0].Temperature,
Weather: weaResp.Result.Future[0].Weather,
Direct: weaResp.Result.Future[0].Direct,
}
fuArr := []*pb.Future{fu}
return &pb.WeatherResponse{
Reason: weaResp.Reason,
Result: &pb.Result{
City: weaResp.Result.City,
Realtime: &pb.Realtime{Aqi: weaResp.Result.Realtime.Aqi},
Future: fuArr,
},
ErrorCode: weaResp.ErrorCode,
}, err
}
func httpGet(cityName string) string {
url := "http://apis.juhe.cn/simpleWeather/query?key=" + key + "&city=" + cityName
log.Println(url)
res, _ := http.Get(url)
defer res.Body.Close()
body, _ := ioutil.ReadAll(res.Body)
return string(body)
}
四种客户端代码
简单模式
simple_rpc.go
package main
import (
"context"
"google.golang.org/grpc"
"juhe.cn.weather_report/pb"
"log"
)
/**
* @author micro.cloud.fly
* @date 2022/3/25 3:54 下午
* @desc
*/
func main() {
dial, err := grpc.Dial("localhost:8080", grpc.WithInsecure())
if err != nil {
log.Fatal(err)
}
defer dial.Close()
client := pb.NewQueryClient(dial)
/* 客户端和服务端是同步的*/
//--------|客户端|----------|服务端|
//-------|一次发送|---------|同步返回|
pinyin, err := client.GetById(context.Background(), &pb.WeatherRequest{
City: "北京",
Key: "",
})
log.Println("返回:", pinyin)
log.Println("错误:", err)
}
客户端段流模式
client_side_stream_rpc.go
package main
import (
"context"
"fmt"
"google.golang.org/grpc"
"juhe.cn.weather_report/pb"
"log"
"time"
)
/**
* @author micro.cloud.fly
* @date 2022/3/25 3:54 下午
* @desc
*/
func main() {
dial, err := grpc.Dial("localhost:8080", grpc.WithInsecure())
if err != nil {
log.Fatal(err)
}
defer dial.Close()
client := pb.NewQueryClient(dial)
/*客户端是流,服务是一次性返回 */
//--------|客户端|----------|服务端|
//-------|流|----------- |接收完一次同步返回|
//客户端通过流的方式发送三个数据过去----start
names, err := client.GetByStream(context.Background())
city := []string{"苏州", "上海", "青岛"}
for i := 0; i < 3; i++ {
if err := names.Send(&pb.WeatherRequest{
City: city[i],
Key: "",
}); err != nil {
log.Fatal(err)
}
time.Sleep(time.Second * 2)
}
//关闭发送,让服务端知道客户端已经发送完毕
recv, err := names.CloseAndRecv()
fmt.Println(recv, err)
//----------------end-------
}
服务端流模式
server_side_stream_rpc.go
package main
import (
"context"
"fmt"
"google.golang.org/grpc"
"io"
"juhe.cn.weather_report/pb"
"log"
)
/**
* @author micro.cloud.fly
* @date 2022/3/25 3:54 下午
* @desc
*/
func main() {
dial, err := grpc.Dial("localhost:8080", grpc.WithInsecure())
if err != nil {
log.Fatal(err)
}
defer dial.Close()
client := pb.NewQueryClient(dial)
/*客户端一次性发送过去数据,而服务端通过流的方式返回*/
//--------|客户端|----------|服务端|
//--------|一次发送|-----------|流返回|
//客户端端一次发送一个省份,服务端通过流的方式返回这个省份的所有城市
stream, err := client.ReturnByStream(context.Background(), &pb.CityRequest{Province: "江苏"})
//由于服务端是流的方式返回数据,所以此时要从流中循环读取返回数据
var city []string
for {
recv, err := stream.Recv()
if err == nil {
fmt.Println("服务端返回:", recv.Cityname)
city = append(city, recv.Cityname)
}
if err == io.EOF {
fmt.Println("服务端已经全部返回,客户端接受完毕!")
break
}
if err != nil {
log.Fatal(err)
}
}
log.Println("江苏所有的城市是:", city)
}
双向流模式
bidirectional_stream.go
package main
import (
"context"
"fmt"
"google.golang.org/grpc"
"io"
"juhe.cn.weather_report/pb"
"log"
)
/**
* @author micro.cloud.fly
* @date 2022/3/25 3:54 下午
* @desc
*/
func main() {
dial, err := grpc.Dial("localhost:8080", grpc.WithInsecure())
if err != nil {
log.Fatal(err)
}
defer dial.Close()
client := pb.NewQueryClient(dial)
stream, err := client.BidirectionalStream(context.Background())
if err!=nil {
log.Fatal(err)
}
for i := 0; i < 5; i++ {
err := stream.Send(&pb.Product{Id: int64(i)})
if err!=nil {
log.Fatal(err)
}
fmt.Println("发送商品:",i)
recv, err := stream.Recv()
if err==io.EOF {
//表示接收此次流接收结束
break
}
if err!=nil {
log.Fatal(err)
continue
}
fmt.Println("收到商品:",recv.GetId(),recv.GetName())
}
}