@@ -190,6 +190,7 @@ func (router *ScoreBasedRouter) RedirectConnections() error {
190190 connWrapper .phase = phaseRedirectNotify
191191 // we dont care the results
192192 _ = connWrapper .Redirect (backend )
193+ connWrapper .redirectingBackend = backend
193194 }
194195 }
195196 }
@@ -263,18 +264,25 @@ func (router *ScoreBasedRouter) onRedirectFinished(from, to string, conn Redirec
263264 router .adjustBackendList (toBe , true )
264265 connWrapper .phase = phaseRedirectFail
265266 }
267+ connWrapper .redirectingBackend = nil
266268 addMigrateMetrics (from , to , succeed , connWrapper .lastRedirect )
267269}
268270
269271// OnConnClosed implements ConnEventReceiver.OnConnClosed interface.
270272func (router * ScoreBasedRouter ) OnConnClosed (addr string , conn RedirectableConn ) error {
271273 router .Lock ()
272274 defer router .Unlock ()
273- // OnConnClosed is always called after processing ongoing redirect events,
274- // so the addr passed in is the right backend.
275275 be := router .ensureBackend (addr , true )
276- be .Value .connScore --
277- router .removeConn (be , router .getConnWrapper (conn ))
276+ connWrapper := router .getConnWrapper (conn )
277+ redirectingBackend := connWrapper .Value .redirectingBackend
278+ // If this connection is redirecting, decrease the score of the target backend.
279+ if redirectingBackend != nil {
280+ redirectingBackend .connScore --
281+ connWrapper .Value .redirectingBackend = nil
282+ } else {
283+ be .Value .connScore --
284+ }
285+ router .removeConn (be , connWrapper )
278286 return nil
279287}
280288
@@ -375,6 +383,7 @@ func (router *ScoreBasedRouter) rebalance(maxNum int) {
375383 conn .phase = phaseRedirectNotify
376384 conn .lastRedirect = curTime
377385 conn .Redirect (idlestBackend )
386+ conn .redirectingBackend = idlestBackend
378387 }
379388}
380389
0 commit comments