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条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥30 这是哪个作者做的宝宝起名网站
    • ¥60 版本过低apk如何修改可以兼容新的安卓系统
    • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
    • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
    • ¥50 有数据,怎么用matlab求全要素生产率
    • ¥15 TI的insta-spin例程
    • ¥15 完成下列问题完成下列问题
    • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
    • ¥15 YoloV5 第三方库的版本对照问题
    • ¥15 请完成下列相关问题!