经过几天的搜索,我发现nginx load banlancing似乎是解决方案,但我不确定。
我在服务器A(外部ip 120.25.x.200)上运行了带有uwsgi和nginx的django app mydomain
。其nginx.conf
和uwsgi.ini
为here。我使用redis 2.8进行缓存会话:
# /apps/mydomain/proj/settings.py
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/1",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
}
}
}
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
SESSION_CACHE_ALIAS = "default"
我使用Posrgresql作为数据库:
# /apps/mydomain/proj/settings.py
DATABASES = {'default': {
'ENGINE' : 'django.db.backends.postgresql_psycopg2',
'NAME' : 'muser',
'USER' : 'postgres',
'PASSWORD': '*****',
'HOST' : '127.0.0.1',
'PORT' : '5432',
}}
使用uwsgi /apps/mydomain/uwsgi.ini
和service nginx start
,该应用在服务器A上运行良好。
如果我想再添加两台服务器B(120.25.x.201)和C(120.25.x.202)以及A来为应用mydomain
提供服务,我可以按照以下步骤进行操作:
# step 1:change the nginx.conf file on server A ---
# change the server block's `location /` in http block, others remain same
http {
upstream mydomain {
server 120.25.x.200:80;
server 120.25.x.201:80;
server 120.25.x.202:80;
}
server {
# ...
location / {
uwsgi_pass http://mydomain;
include /apps/mydomain/uwsgi_params;
}
# ...
}
}
# step 2:on server B and C, I make a copy of the `mydomain` app environment
# in the same path.
# step 3:on server B and C, I change the cache and database settings
# in /apps/mydomain/proj/settings.py like this(just replace
# the local ip 127.0.0.1 with A's ip):
CACHES = {
"default": {
# ...
"LOCATION": "redis://120.25.x.200:6379/1",
# ...
}
}
DATABASES = {'default': {
# ...
'HOST' : '120.25.x.200',
# ...
}}
# step 4:on server B and C,use `uwsgi /apps/mydomain/uwsgi.ini` to start the app.
# step 5:on server A, start the app with nginx and uwsgi as usual.
3。问题
我猜对了吗?可以在服务A,B和C中共享redis缓存的会话数据和Postgresql数据库吗?
或者,对我的目标有更好的解决方案吗?
答案 0 :(得分:1)
是的,这是正确的解决方案,但请考虑是否有必要。也许你的瓶颈不是django app而是数据库。可能更好的方法是将数据库移动到另一台服务器,因此它将拥有所有可用资源。