我正在尝试使用循环方法在Django中进行implement
负载平衡。起初,我创建了一个模型,其中保存了所有实例和每个实例的序列。
我的型号:
class Load_Balancing(models.Model):
id = models.AutoField(primary_key=True)
instance = models.CharField(max_length=100)
sequence = models.IntegerField()
不要试图在应用程序级别实现负载平衡,因为这毫无意义。您的数据库将成为解决方案的瓶颈。
使用适当的HTTP服务器/反向代理大多数都有完善的负载平衡支持,例如:nginx、apache
不知道在视图中获取实例并对其执行任何进一步操作的意图,下面可能是实现这一点的简单PoC。
然而,我强烈建议您采用iklinac的解决方案,并重新考虑您的架构设计。
您可以创建一个模型作为计数器。注意,这也可以使用像pickle
这样的内存内持久性解决方案来完成,但我更喜欢这样做。
创建一个充当计数器的表
class InstanceSq(models.Model):
sequence_id = models.IntegerField()
此模型的表将始终只包含1行。
把它放在你的视野中。py如下:
try:
sequence_id = InstanceSq.objects.get(id=1).sequence_id
except InstanceSq.DoesNotExist:
#This is when it runs first time
instance_row = InstanceSq(sequence_id = 1)
instance_row.save()
sequence_id = 1
#..
#Here you get the current instance as:
instance_ip = Load_Balancing.objects.filter(sequence=sequence_id)
#Use your instance here and do whatever you want to do
#.. and then
# Rotation logic
new_id = sequence_id % 4 + 1
current = InstanceSq.objects.select_for_update().get(id=1) #to avoid race conditions
current.sequence_id = new_id
current.save()