Skip to content

Commit

Permalink
update least connections host
Browse files Browse the repository at this point in the history
  • Loading branch information
allnash committed Nov 20, 2024
1 parent cf8d49e commit 5fa79f1
Showing 1 changed file with 12 additions and 8 deletions.
20 changes: 12 additions & 8 deletions fast-server/handlers/proxy_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,9 @@ func getLeastConnHost(hosts []string) string {
minConns := int64(math.MaxInt64)

for _, host := range hosts {
conns, _ := activeConnections.LoadOrStore(host, int64(0))
currentConns := conns.(int64)
// Initialize with 0 if not exists
connsValue, _ := activeConnections.LoadOrStore(host, int64(0))
currentConns := connsValue.(int64)
if currentConns < minConns {
minConns = currentConns
selectedHost = host
Expand Down Expand Up @@ -104,12 +105,15 @@ func HandleProxy(c echo.Context, domain config.Domain) error {

// Increment active connections for the selected host if using least_conn
if proxyConfig.LoadBalanceMethod == LoadBalanceMethodLeastConn {
var conns int64
actual, _ := activeConnections.LoadOrStore(selectedHost, &conns)
connPtr := actual.(*int64)
atomic.AddInt64(connPtr, 1)
defer atomic.AddInt64(connPtr, -1)
c.Logger().Debugf("Active connections for host %s: %d", selectedHost, atomic.LoadInt64(connPtr))
connsValue, _ := activeConnections.LoadOrStore(selectedHost, int64(0))
currentConns := connsValue.(int64)
activeConnections.Store(selectedHost, currentConns+1)
defer func() {
connsValue, _ := activeConnections.Load(selectedHost)
currentConns := connsValue.(int64)
activeConnections.Store(selectedHost, currentConns-1)
}()
c.Logger().Debugf("Active connections for host %s: %d", selectedHost, currentConns+1)
}

targetScheme := proxyConfig.Protocol
Expand Down

0 comments on commit 5fa79f1

Please sign in to comment.