# 负载均衡策略之最少连接

## 最少连接 (Least Connection)¶

```class Node:
def __init__(self, name):
self.name = name
self.connections = 0

def __repr__(self):
return '<Node: {}, conn: {}>'.format(self.name, self.connections)

class LC:

def __init__(self, nodes):
self.nodes = nodes

def select(self):
best = None

for node in self.nodes:
if best is None or node.connections < best.connections:
best = node

best.connections += 1
return best

def release(self, node):
node.connections -= 1
```

## 带权重的最少连接 (Weighted Least Connection)¶

• 假设用 C 表示连接数、W 表示权重、S 表示被选中的节点、Sn 表示未被选中的节点
• 那么 S 必须满足 C(S) / W(S) < C(Sn) / W(Sn) ，这个条件也可以表示为 C(S) * W(Sn) < C(Sn) * W(S)

```class Node:
def __init__(self, name, weight):
self.name = name
self.weight = weight
self.connections = 0

def __repr__(self):
return '<Node: {}, weight: {}, conn: {}>'.format(
self.name, self.weight, self.connections)

class LC:

def __init__(self, nodes):
self.nodes = nodes

def select(self):
best = None

for node in self.nodes:
if best is None or (
node.connections * best.weight
) < (best.connections * node.weight):
best = node

best.connections += 1
return best

def release(self, node):
node.connections -= 1
```