python操作redis分布式锁
- django 主项目下views层代码
前提:
数据库中有数据表User,数据表中有字段username,score
启动了两个django客户端,端口分别为8000,8001,用户模拟分布式处理用户请求
主路由绑定test(request)视图函数
from django.http import JsonResponse
def test(request):
r = redis.Redis(host='127.0.0.1',port=6379,db=0)
while True:
try:
with r.lock('123',blocking_timeout=3) as lock:
u = User.objects.get(username='Terry')
u.score += 1
u.save()
break
except Exception as e:
print('Local failed')
return JsonResponse({'code':200,'data':{})
- 模拟客户端对服务端(django)发请求的代码
from threading import Thread
import random
import requests
def get_request():
url = 'http://127.0.0.1:8000/test/'
url2 = 'http://127.0.0.1:8001/test/'
get_url = random.choice([url,url2])
request.get(get_url)
t_list = []
for i in range(30):
t = Thread(target=get_request)
t_list.append(t)
t.start()
for t in t_list:
t.join()