Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/myeonghan-nim/database-sharding
π Study: database sharding
https://github.com/myeonghan-nim/database-sharding
database-sharding django python
Last synced: 28 days ago
JSON representation
π Study: database sharding
- Host: GitHub
- URL: https://github.com/myeonghan-nim/database-sharding
- Owner: myeonghan-nim
- Created: 2024-11-15T05:53:43.000Z (about 1 month ago)
- Default Branch: main
- Last Pushed: 2024-11-15T06:41:51.000Z (about 1 month ago)
- Last Synced: 2024-11-15T07:30:12.535Z (about 1 month ago)
- Topics: database-sharding, django, python
- Language: Python
- Homepage:
- Size: 8.79 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# database sharding
## μ€λ©
λ°μ΄ν°λ² μ΄μ€λ₯Ό μ¬λ¬ κ°λ‘ λλλ κ²μΌλ‘ κ° μ€λλ μλ‘ λ€λ₯Έ 물리μ μλ²μ μ‘΄μ¬ κ°λ₯. κ° μ€λλ λ 립μ μΌλ‘ μλνλ©° λ°μ΄ν°λ₯Ό μ½μ ν λ λ°μ΄ν° λΆν¬ κ·μΉμ λ°λΌ νΉμ μ€λμ μ μ₯. μ€λ©μ ꡬννλ λ°λ λ€μν μ λ΅μ΄ μμΌλ©° κ·Έμ€ κ°μ₯ λ§μ΄ μ¬μ©λλ κ²μ΄ **ν΄μ κΈ°λ° μ€λ©**μΌλ‘ μ΄ λ°©λ²μ νΉμ ν€(μ: μ¬μ©μ ID)μ λν ν΄μ κ°μ κ³μ°νμ¬ λ°μ΄ν°λ₯Ό μ΄λ€ μ€λμ μ μ₯ν μ§ κ²°μ .
### μμ
```python
# settings.py
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": BASE_DIR / "default.sqlite3",
},
"shard1": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": BASE_DIR / "shard1.sqlite3",
},
"shard2": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": BASE_DIR / "shard2.sqlite3",
},
}DATABASE_ROUTERS = ["path.to.db_router.ShardRouter"]
# db_router.py
import hashlibclass HashShardRouter:
SHARDS = ["shard1", "shard2"]# ν΄μ κΈ°λ°μΌλ‘ μ€λλ₯Ό μ ν
def get_shard(self, user_id):
# SHA256 ν΄μ μ¬μ© ν 10μ§μλ‘ λ³ν
hash_val = int(hashlib.sha256(str(user_id).encode()).hexdigest(), 16)
# μ€λ κ°μλ‘ λλ λλ¨Έμ§ μ°μ°μ ν΅ν΄ μ€λ μ ν
shard_index = hash_val % len(self.SHARDS)
return self.SHARDS[shard_index]# λ°μ΄ν°λ₯Ό μ μ₯ν λ°μ΄ν°λ² μ΄μ€λ₯Ό κ²°μ νλ λ‘μ§
def db_for_write(self, model, **hints):
if hasattr(model, "user_id"):
return self.get_shard(model.user_id)
return "default"# λ°μ΄ν°λ₯Ό μ½μ λ°μ΄ν°λ² μ΄μ€λ₯Ό κ²°μ νλ λ‘μ§
def db_for_read(self, model, **hints):
if hasattr(model, "user_id"):
return self.get_shard(model.user_id)
return "default"```
μμ κ°μ΄ μ¬λ¬ μ€λλ₯Ό μ€λΉνκ³ κ°κ°μ μ μ₯ λ° λΆλ¬μ€κΈ°κ° κ°λ₯