dongmaobeng7145 2019-09-09 14:57
浏览 99

如何安全地将布尔字段添加到gRPC服务器结构?

I'm looking to add what's essentially a "status" boolean field to my gRPC Server. The idea is that the state of the server could be set when certain conditions are met, so when any new gRPC requests come in, the response would be tailored accordingly.

I have a server struct that I'm using, and for this example, I've added a HappyHour bool field. I have a goroutine that runs when the server is started, and every minute it checks the time of day. If the time of day is between 5-7pm, HappyHour gets set to true. Otherwise, it gets set to false.

type server struct {
    HappyHour bool
    mu     sync.RWMutex
}

func (s *server) OrderDrink(ctx context.Context, req *bar.DrinkRequest) (*flatbuffers.Builder, error) {

    drink := string(req.drink())
    qty := req.qty()


    // Code here to look up the price of the drink in the database
    total := price*qty

    // Use a mutex to check HappyHour status 
    s.mu.RLock()
    defer mu.RLock()
    if s.HappyHour == true {
        total=total/2
    }

    b := flatbuffers.NewBuilder(0)
    // Serialize the response and send it to the client
}


func main() {
    lis, err := net.Listen("tcp", "0.0.0.0:50051")
    if err != nil {
        log.Fatal(err)
    }

    s := grpc.NewServer(grpc.CustomCodec(flatbuffers.FlatbuffersCodec{}))

    var srv server
    bar.RegisterBARServer(s, &srv) 

    // Monitor happy hour
    go happyHour(&srv)
}

Things seem to be working from my initial testing, but I'm quite new to gRPC, and am a bit worried about using a mutex on the server struct.

Will there be negative performance impacts if there are many clients connecting to the server? If I'm reading or updating HappyHour, and the lock has been acquired, would this impact new users connecting or sending requests? Or would this only impact the actual HappyHour field?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 C++ 头文件/宏冲突问题解决
    • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
    • ¥50 安卓adb backup备份子用户应用数据失败
    • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
    • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
    • ¥30 python代码,帮调试
    • ¥15 #MATLAB仿真#车辆换道路径规划
    • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
    • ¥15 数据可视化Python
    • ¥15 要给毕业设计添加扫码登录的功能!!有偿