【发布时间】:2016-09-20 15:53:07
【问题描述】:
我正在尝试使用两个数据库(1 个主数据库,1 个只读副本)运行我的 Django 应用程序。我的问题是,如果我在写完代码后立即尝试阅读,代码就会爆炸。例如:
- p = Product.objects.create()
- Product.objects.get(id=p.id)
或
- 如果用户被重定向到产品的 详情页
代码运行速度比只读副本快得多。如果读取操作使用副本,代码会崩溃,因为它没有及时更新。
有什么办法可以避免这种情况吗?例如,要读取的数据库是由请求而不是操作选择的?
我的路由器与 Django 的文档相同:
import random
class PrimaryReplicaRouter(object):
def db_for_read(self, model, **hints):
"""
Reads go to a randomly-chosen replica.
"""
return random.choice(['replica1', 'replica2'])
def db_for_write(self, model, **hints):
"""
Writes always go to primary.
"""
return 'primary'
def allow_relation(self, obj1, obj2, **hints):
"""
Relations between objects are allowed if both objects are
in the primary/replica pool.
"""
db_list = ('primary', 'replica1', 'replica2')
if obj1._state.db in db_list and obj2._state.db in db_list:
return True
return None
def allow_migrate(self, db, app_label, model_name=None, **hints):
"""
All non-auth models end up in this pool.
"""
return True
【问题讨论】: