2017-11-20 27 views
0

私は、マスターリモートのMySQLデータベースサーバーと、そのレプリカを私のDjangoアプリケーション用のスレーブデータベースとして設定しました。どちらもamazon ubuntu ec2インスタンス上で動作します。マスターデータベースがダウンしている場合に自動的にスレーブデータベースにアクセスするようにDjangoを設定するには?Django内の複数のデータベースサーバを自動的に切り替える方法。

+1

[スレーブがダウンしている場合の[Django Multiple Databases Fallback to Master]]の重複可能性(https://stackoverflow.com/questions/26608906/django-mult ips-databases-fall-to-master-if-slave-is-down) – kmcodes

+0

[この解決方法]を確認してください(https://stackoverflow.com/questions/26608906/django-multiple-databases-fallback-to-master- if-slave-is-down)を指定します。あなたの質問のより詳細なバージョンです。 – kmcodes

答えて

1

Djangorは、私はあなたの例を与える 、この疑問を解決するために、DBのルータを使用します。

class DBRouter(object): 
""" 
A router to control all database operations on models in the 
auth application. 
""" 
def db_for_read(self, model, **hints): 
    """ 
    Attempts to read auth models go to auth_db. 
    """ 
    if model._meta.app_label == 'xxx': 
     return 'salvedb' # this name you defined in settings of django project 
    return None 

def db_for_write(self, model, **hints): 
    """ 
    Attempts to write auth models go to auth_db. 
    """ 
    if model._meta.app_label == 'xxx': 
     return 'salvedb' 
    return None 

def allow_relation(self, obj1, obj2, **hints): 
    """ 
    Allow relations if a model in the auth app is involved. 
    """ 
    #if obj1._meta.app_label == 'auth' or \ 
    # obj2._meta.app_label == 'auth': 
    # return True 
    return None 

def allow_migrate(self, db, app_label, model_name=None, **hints): 
    """ 
    Make sure the auth app only appears in the 'auth_db' 
    database. 
    """ 
    #if app_label == 'auth': 
    # return db == 'auth_db' 
    return None 

とあなたの設定にこのルータを追加します。

DATABASE_ROUTERS = ['path.routers.DBRouter'] 

か、ジャンゴのドキュメントを読むことができます公式サイト:https://docs.djangoproject.com/en/1.11/topics/db/multi-db/#automatic-database-routing

+0

あなたのソリューションは別々のDBに別々のモデルデータを格納するためのものだと思います。私は別のアプリケーション用に別々のDBを使用していません。私はすべてのアプリのデータをマスタDBとスレーブDBに同期して保存しています。私が望むのは、マスターが失敗した場合、DjangoはスレーブDBから読み書きする必要があることです。 – albinantony143

+0

書き込みと読み取りの分離は、django db routerで行うことができます。私はSwitch of MasterとSlaveをDevOpsで実行できると思います。 – Hayden

関連する問題