开发者社区> 问答> 正文

Django使用AliyunRDS只读实例,实现读写分离.

前几天为了上读写分离功能, MySQL5.1直接升到5.6  (而且5.1也不维护了)。。

新增的只读实例 找了半天才在管理控制台看到  常规实例点开+号,展开才能看到。 不是类型筛选(筛选只有一个选项常规实例)

自定义了django db router:
import random


class MasterSlaveRouter(object):
    
    def db_for_read(self, model, **hints):
        return random.choice(['slave1', 'slave2', 'slave3'])

    def db_for_write(self, model, **hints):
        return 'default'

    def allow_relation(self, obj1, obj2, **hints):
        return True

    def allow_syncdb(self, db, model):
        return True


settings.py 添加的配置如下:
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'xxxxxxx',                      # Or path to database file if using sqlite3.
        'USER': 'xxxxxx',                      # Not used with sqlite3.
        'PASSWORD': 'xxxxxx',                  # Not used with sqlite3.
        'HOST': 'xxxxx.mysql.rds.aliyuncs.com',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
        'OPTIONS': {
            'use_unicode': 'utf-8',
            'init_command': 'SET storage_engine=INNODB',
        }
    },
    'slave1': {
        'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'xxxx',                      # Or path to database file if using sqlite3.
        'USER': 'xxxxx',                      # Not used with sqlite3.
        'PASSWORD': 'xxxxxx',                  # Not used with sqlite3.
        'HOST': 'xxxxxxxxx.mysql.rds.aliyuncs.com',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
        'OPTIONS': {
            'use_unicode': 'utf-8',
            'init_command': 'SET storage_engine=INNODB',
        }
    }
}

DATABASE_ROUTERS = ['epub360.db_router.MasterSlaveRouter']

搞定, 这个功能对django版本好像是>=1.2 ,应该都能用吧,还是挺方便的。    python代码贴出来,格式就不对了。复制了还要自己改真心麻烦。

展开
收起
epub360 2014-11-18 15:58:18 16018 0
7 条回答
写回答
取消 提交回答
  • ReDjango使用AliyunRDS只读实例,实现读写分离.
    学习了
    2014-12-16 16:15:40
    赞同 展开评论 打赏
  •   
    2014-12-13 12:34:28
    赞同 展开评论 打赏
  • ReDjango使用AliyunRDS只读实例,实现读写分离.
    2014-12-07 10:26:15
    赞同 展开评论 打赏
  • ReDjango使用AliyunRDS只读实例,实现读写分离.
    为何这么牛
    2014-11-28 23:01:47
    赞同 展开评论 打赏
  • ReDjango使用AliyunRDS只读实例,实现读写分离.
    谢谢 rds-pd 的奖励,, 话说bbs的消息提醒太不明显。。今天刚看到。。
    2014-11-28 16:31:24
    赞同 展开评论 打赏
  • 2014-11-24 23:11:49
    赞同 展开评论 打赏
  • 阿里云数据库产品团队,为用户构建最好用的数据库产品
    必须加分啊

    -------------------------

    我们看能不能优化下,@xiaofanqie

    2014-11-21 11:17:42
    赞同 展开评论 打赏
滑动查看更多
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载