Skip to content

Commit

Permalink
redis mutex added.
Browse files Browse the repository at this point in the history
  • Loading branch information
EralpB committed May 23, 2020
1 parent 508653a commit 4b04400
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 5 deletions.
17 changes: 14 additions & 3 deletions bookshop/models.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,31 @@
from django.db import models
from django.core.cache import cache
import time
import redis

r = redis.Redis(host='localhost', port=6379, db=0)


class Author(models.Model):
name = models.CharField(max_length=255)

# _ indicates this function is for internal use only
def _get_top_books(self):
time.sleep(5) # make the calculation slower for the sake of argument
return list(Book.objects.order_by('-purchase_count')[:10])

def get_top_books(self):
cache_key = 'Author:get_top_books:{}'.format(self.id)
lock_key = 'Lock:{}'.format(cache_key)
cache_value = cache.get(cache_key)
if cache_value is not None:
return list(Book.objects.filter(id__in=cache_value))
try:
with r.lock(lock_key, timeout=60, blocking_timeout=0):
books = self._get_top_books()
except redis.exceptions.LockError:
raise Exception('ColdCacheException')

time.sleep(5) # make the calculation slower for the sake of argument
books = list(Book.objects.order_by('-purchase_count')[:10])
# cache.set(cache_key, books, 4 * 60 * 60) # cache for 4 hours
cache.set(cache_key, [book.id for book in books], 4 * 60 * 60) # cache for 4 hours
return books

Expand Down
4 changes: 2 additions & 2 deletions bookshop/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ def author_detail_view(request, pk):


def index_view(request):
authors = Author.objects.all()
books = Book.objects.all()
authors = Author.objects.all()[:50]
books = Book.objects.all()[:50]
return render(request, 'bookshop/index.html', {
'books': books,
'authors': authors
Expand Down
5 changes: 5 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
asgiref==3.2.7
Django==2.2
pytz==2020.1
redis==3.5.2
sqlparse==0.3.1

0 comments on commit 4b04400

Please sign in to comment.