I am making a task list using go, grpc and postgres.
How to automatically stream data when calling postitem
to insert new data? Do I need to subscribe to postgres or can this be done without a subscribe or publish subscribe?
//protobuf architecture
syntax = "proto3"; package tasklist; import "google/protobuf/empty.proto"; service todolist { rpc gettasks(google.protobuf.empty) returns (stream gettasksresponse) {} rpc postitem(postitemrequest) returns (posttaskrequest) {} } message task { int64 id = 1; string name = 2; } message gettasksresponse { task task = 1; } message posttaskrequest { task task = 1; } message postitemresponse { bool result = 1; }
// postgres table structure
create table task ( id integer not null primary key, name varchar(10) not null );
// continue
func (s *server) GetTasks(_ *empty.Empty, stream pb.TaskList_GetTasksServer) error { // How can I steam data as soon as `PostTask` is called to update db? <- <- for _, r := range s.requests { // stream data } } func (s *server) PostTask(ctx context.Context, r *pb.PostTaskRequest) (*pb.PostTaskResponse, error) { // update Postgres here return &pb.PostItemResponse{Result: true}, nil }
I guess s.requests
is similar to chan task
. So after successfully // update postgres here
you can send your request in chan.
func (s *server) PostTask(ctx context.Context, r *pb.PostTaskRequest) (*pb.PostTaskResponse, error) { postTask := toDomain(r) err := s.service.UpdateTask(ctx, postTask) if err != nil { return nil, status.Error(codes.Internal, err.Error()) } s.requests <- postTask return &pb.PostItemResponse{Result: true}, nil }
The above is the detailed content of Use gRPC to transfer database data immediately after table changes. For more information, please follow other related articles on the PHP Chinese website!