gRPC Servisi Oluşturma: Protocol Buffers ile Başlama
gRPC, Google tarafından geliştirilen yüksek performanslı RPC framework'üdür. Protocol Buffers (protobuf) ile veri serileştirmesi yaparak HTTP/2 üzerinden iletişim sağlar. REST API'den çok daha hızlı ve verimlidi; microservices mimarisinde sıkça kullanılır.
İlk gRPC servisinizi Go ile oluşturalım. Önce gerekli araçları kurun.
1go install google.golang.org/protobuf/cmd/protoc-gen-go@latest2go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latestProtocol Buffer tanım dosyasını oluşturun. `hello.proto` adıyla kaydettikten sonra servis ve mesaj yapılarını tanımlayın.
1syntax = "proto3";23package hello;45option go_package = "hello/pb";67message HelloRequest {8string name = 1;9}1011message HelloReply {12string message = 1;13}1415service Greeter {16rpc SayHello(HelloRequest) returns (HelloReply);17}Proto dosyasından Go kodunu üretin.
1protoc --go_out=. --go-grpc_out=. hello.protoBu komut `pb` klasöründe `hello.pb.go` ve `hello_grpc.pb.go` dosyalarını oluşturur. Şimdi sunucu implementasyonunu yazın. `server.go` dosyasını oluşturun.
1package main23import (4"context"5"fmt"6"net"7"google.golang.org/grpc"8"hello/pb"9)1011type server struct {12pb.UnimplementedGreeterServer13}1415func (s *server) SayHello(ctx context.Context, req *pb.HelloRequest) (*pb.HelloReply, error) {16return &pb.HelloReply{Message: fmt.Sprintf("Merhaba, %s!", req.Name)}, nil17}1819func main() {20lis, _:= net.Listen("tcp", ":50051")21s:= grpc.NewServer()22pb.RegisterGreeterServer(s, &server{})23fmt.Println("Sunucu 50051 portunda çalışıyor...")24s.Serve(lis)25}26[/cod]2728İstemci kodu oluşturun. `client.go` dosyasına yazın.2930[kod]31package main3233import (34"context"35"fmt"36"google.golang.org/grpc"37"google.golang.org/grpc/credentials/insecure"38"hello/pb"39)4041func main() {42conn, _:= grpc.Dial("localhost:50051", grpc.WithTransportCredentials(insecure.NewCredentials()))43defer conn.Close()4445c:= pb.NewGreeterClient(conn)46resp, _:= c.SayHello(context.Background(), &pb.HelloRequest{Name: "Ahmet"})47fmt.Println(resp.Message)48}Sunucuyu ve istemciyi çalıştırın.
1go run server.go2go run client.goBeklenen çıktı: `Merhaba, Ahmet!`
Sık yapılan hata: protoc komutlarında path yanlış veya modül tanımlanmamışsa `go mod init hello` komutuyla Go modülünü başlatın. gRPC bağlantı sırasında sunucunun çalışmadığı durumlarda bağlantı hatası alırsınız; sunucuyu önce başlatmayı unutmayın.
0 yorum