如何从protobuf消息类转换/广播到我的C ++类模型?

时间:2019-07-25 20:34:51

标签: c++ protocol-buffers grpc proto protobuf-c

我正在使用grpc和protobuf的c ++后端中工作,我只想使用protobuf作为消息来获取对前端的请求和响应,并且不将protobuf生成的类用作我的业务逻辑的一部分,因为如果将来,如果想/需要用rest / json或其他来替换grpc / protobuf,我不需要只更改通信层即可更改服务。

那么...有没有一种形式可以将protobuf对象请求转换为具有几乎相同属性的我自己的类?

例如,这是我的PROTO UserCreateRequest

message UserCreateRequest{
    string name = 2;
    Gender gender = 3;
    string lastName = 4;
    string birthday = 5;
    string email = 6;
    string userName = 7;
    string password = 8;
    string profileImageUrl = 9;
}


message UserResponse {
    string id = 1;
    string name = 2;
    Gender gender = 3;
    string lastName = 4;
    string birthday = 5;
    string email = 6;
    string userName = 7;
    string profileImageUrl = 8;
    UserType type = 9;
    repeated protoModel.Role roles = 10;
    bool enabled = 11;
    string creationDate = 12;
    string modificationDate =13;
}

这是我的c ++用户类



class User : public Base {
    std::string name;
    std::string lastName;
    Gender gender;
    Date birthday;
    std::string email;
    std::string username;
    std::string password;
    std::string profileImageUrl;
    std::set<Role> roles;
    UserType type;
    bool enabled = true;

现在,当我收到使用Setter创建我的用户模型并将其发送给我的服务的UserCreateRequest时:

        User user;
        user.setName(request->name());
        user.setLastName(request->lastname());
        user.setEmail(request->email());
        user.setUsername(request->username());
        user.setPassword(request->password());
        user.setBirthday(Date(request->birthday()));

        UserService::save(user);

对于响应,我进行保存,但反之亦然,即从班级到答复

        reply->set_id(user.getId());
        reply->set_name(user.getName());
        reply->set_lastname(user.getLastName());
        reply->set_email(user.getEmail());
        reply->set_username(user.getUsername());
        reply->set_lastname(user.getLastName());
        reply->set_birthday(user.getBirthday().toString());

**是否有任何形式可以执行此操作而没有设置器,并且可以从protobuf转换为myclass,反之亦然,从myclass转换为protobuf消息响应,例如java反射或protobufmessage。 / p>

非常感谢。

0 个答案:

没有答案