赞
踩
proto/laptop_service.proto
CreateLaptopRequest
消息,它只包含一个字段:我们要创建的笔记本电脑message CreateLaptopRequest {
Laptop laptop = 1;
}
CreateLaptopResponse
消息也只有 1 个字段:创建的笔记本电脑的 IDmessage CreateLaptopResponse {
string id = 1;
}
service LaptopService {
rpc CreateLaptop(CreateLaptopRequest) returns (CreateLaptopResponse) {};
}
service/laptop_server.go
文件LaptopServer
结构和一个NewLaptopServer()
函数来返回它的一个新实例type LaptopServer struct {
pb.UnimplementedLaptopServiceServer
}
func NewLaptopServer() *LaptopServer {
return &LaptopServer{}
}
laptop_service.proto
中定义了一个CreateLaptop
一元服务,在此go文件中需要去定义一个CreateLaptop
函数实现服务func (server *LaptopServer) CreateLaptop(ctx context.Context, req *pb.CreateLaptopRequest) (*pb.CreateLaptopResponse, error) {
return nil, nil
}
GetLaptop
函数从请求中获取笔记本电脑对象func (server *LaptopServer) CreateLaptop(ctx context.Context, req *pb.CreateLaptopRequest) (*pb.CreateLaptopResponse, error) {
laptop := req.GetLaptop()
log.Printf("receive a create-laptop request with id: %s", laptop.Id)
return nil, nil
}
go get github.com/google/uuid
,uuid.Parse()
函数来解析笔记本电脑的 ID。if len(laptop.Id) > 0 {
_, err := uuid.Parse(laptop.Id)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "laptop ID is not a valid UUID: %v", err)
}
}
uuid.NewRandom()
命令生成它。else {
id, err := uuid.NewRandom()
if err != nil {
return nil, status.Errorf(codes.Internal, "cannot generate a new laptop ID: %v", err)
}
laptop.Id = id.String()
}
service/laptop_store.go
type LaptopStore interface {
save(laptop *pb.Laptop) error
}
type InMemoryLaptopStore struct {
mutex sync.RWMutex
data map[string]*pb.Laptop
}
NewInMemoryLaptopStore
来返回一个新的 InMemoryLaptopStore
,并初始化其中的数据映射func NewInMemoryLaptopStore() *InMemoryLaptopStore {
return &InMemoryLaptopStore{
data: make(map[string]*pb.Laptop),
}
}
InMemoryLaptopStore
结构体的save功能
func (store *InMemoryLaptopStore) Save(laptop *pb.Laptop) error {
store.mutex.Lock()
defer store.mutex.Unlock()
if store.data[laptop.Id] != nil {
return errors.New("record already exists")
}
other,_ := deepCopy(laptop)
store.data[other.Id] = other
return nil
}
go get github.com/jinzhu/copier
func deepCopy(laptop *pb.Laptop) (*pb.Laptop, error) {
other := &pb.Laptop{}
err := copier.Copy(other, laptop)
if err != nil {
return nil, fmt.Errorf("cannot copy laptop data: %w", err)
}
return other, nil
}
LaptopServer
type LaptopServer struct {
pb.UnimplementedLaptopServiceServer
laptopStore LaptopStore
}
CreateLaptop()
函数中,我们可以调用server.laptopStore.Save()
将输入的笔记本电脑保存到商店
errors.Is()
函数检查是否存在err := server.laptopStore.save(laptop)
if err != nil {
code := codes.Internal
if errors.Is(err, errors.New("record already exists")) {
code = codes.AlreadyExists
}
return nil, status.Errorf(code, "cannot save laptop to the store: %v", err)
}
log.Printf("saved laptop with id: %s", laptop.Id)
res := &pb.CreateLaptopResponse{
Id: laptop.Id,
}
func (server *LaptopServer) CreateLaptop(ctx context.Context, req *pb.CreateLaptopRequest) (*pb.CreateLaptopResponse, error) { laptop := req.GetLaptop() log.Printf("receive a create-laptop request with id: %s", laptop.Id) if len(laptop.Id) > 0 { _, err := uuid.Parse(laptop.Id) if err != nil { return nil, status.Errorf(codes.InvalidArgument, "laptop ID is not a valid UUID: %v", err) } } else { id, err := uuid.NewRandom() if err != nil { return nil, status.Errorf(codes.Internal, "cannot generate a new laptop ID: %v", err) } laptop.Id = id.String() } err := server.laptopStore.save(laptop) if err != nil { code := codes.Internal if errors.Is(err, errors.New("record already exists")) { code = codes.AlreadyExists } return nil, status.Errorf(code, "cannot save laptop to the store: %v", err) } log.Printf("saved laptop with id: %s", laptop.Id) res := &pb.CreateLaptopResponse{ Id: laptop.Id, } return res, nil }
cmd/server/main.go
文件与cmd/client/main.go
文件server:
go run cmd/server/main.go
client:
go run cmd/client/main.go
func main() {
laptopServer := service.NewLaptopServer(service.NewInMemoryLaptopStore())
grpcServer := grpc.NewServer()
pb.RegisterLaptopServiceServer(grpcServer, laptopServer)
listener, _ := net.Listen("tcp", ":8888")
grpcServer.Serve(listener)
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。