Cara Menyambung ke Pelayan gRPC Selepas Penggunaan Semula
Dalam gRPC, kod clientconn.go menguruskan penyambungan semula secara automatik. Walau bagaimanapun, jika pod pelayan dikitar semula, strim akan pecah dan perlu diwujudkan semula. Untuk menangani isu ini, ikut langkah berikut:
Proses Permintaan
func (grpcclient *gRPCClient) ProcessRequests() error { defer grpcclient.Close() go grpcclient.process() for { select { case <-grpcclient.reconnect: if !grpcclient.waitUntilReady() { return errors.New("failed to establish a connection within the defined timeout") } go grpcclient.process() case <-grpcclient.done: return nil } } }
Proses Permintaan:
func (grpcclient *gRPCClient) process() { reqclient := GetStream() // Get a new stream after reconnecting for { request, err := reqclient.stream.Recv() log.Info("Request received") if err == io.EOF { grpcclient.done <- true return } if err != nil { grpcclient.reconnect <- true return } else { // Process requests } } }
Semak Keadaan Sambungan
func (grpcclient *gRPCClient) waitUntilReady() bool { ctx, cancel := context.WithTimeout(context.Background(), 300*time.Second) // Define the timeout for waiting defer cancel() currentState := grpcclient.conn.GetState() stillConnecting := true for currentState != connectivity.Ready && stillConnecting { // Wait for state change stillConnecting = grpcclient.conn.WaitForStateChange(ctx, currentState) currentState = grpcclient.conn.GetState() log.WithFields(log.Fields{"state: ": currentState, "timeout": timeoutDuration}).Info("Attempting reconnection. State has changed to:") } if stillConnecting == false { log.Error("Connection attempt has timed out.") return false } return true }
Pengubahsuaian ini akan membenarkan klien gRPC mewujudkan semula strim secara automatik dan meneruskan pemprosesan permintaan selepas pelayan diatur semula.
Atas ialah kandungan terperinci Bagaimana untuk Mengendalikan Penyambungan Semula Pelayan gRPC Selepas Pemindahan Semula?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!