Use gRPC to transfer database data immediately after table changes

WBOY
Release: 2024-02-05 11:49:31
forward
460 people have browsed it

表更改后立即使用 gRPC 传输数据库数据

Question content

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;
}

Copy after login

// postgres table structure

create table task (
  id integer not null primary key,
  name varchar(10) not null
);
Copy after login

// 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
}

Copy after login


Correct answer


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
}
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!