mac redis客户端_2018-12-5 django-redis 的使用

9aa6a3eba8445821ebb69501f0bec9a9.png

mac 安装Redis


brew install redis

直接运行: redis-server /usr/local/etc/redis.conf

django-redis


参考链接:

中文:https://django-redis-chs.readthedocs.io/zh_CN/latest/#

英文:https://niwinz.github.io/django-redis/latest/#_raw_client_access

django-redis是什么?


使django支持Redis cache/session后端的全功能组件

为什么用?

  1. 持续更新
  2. 支持永不超时设置
  3. 原生进入 redis 客户端/连接池支持
  4. 高可配置

安装


pip install django-redis
or
pipenv install django-redis

cache backend使用配置


settings.py中添加:

CACHES 

某些环境中使用OPTIONS配置连接密码:

CACHES 

使用django-redis进行测试:


模拟实现redis API进行测试

[fakerdis](https://github.com/jamesls/fakeredis)

[mockredis](https://github.com/locationlabs/mockredis)

import 

测试完毕,清理数据

def 

django-redis 使用pickle序列化几乎所有数据

from 

压缩支持(todo:之后再查如何使用)


django-redis 支持压缩, 但默认是关闭的. 激活

CACHES 

使用lzma压缩

import 

memecached异常行为


一些情况,redis常作为缓存使用,当关闭时不希望触发异常,配置如下:

CACHES 

全局配置:

DJANGO_REDIS_IGNORE_EXCEPTIONS 

日志忽略异常

DJANGO_REDIS_LOG_IGNORED_EXCEPTIONS 

永不超时设置


参数:

  • timeout=0 立即过期
  • timeout=None 永不超时
cache

通过值 (value) 获取 ttl (time to live)


参数:

  • 0 key 不存在 或已过期
  • None key 存在但没有设置过期.
  • ttl 任何有超时设置的 key 的超时值.
from 

expire & persist


persist:让一个值永久存在

expire:指定一个新的过期时间

cache

locks 锁


django-redis 支持 redis 分布式锁

with 

扫描 & 删除键 (keys)


django-redis 支持使用全局通配符的方式来检索或者删除键.

通配符搜索(不试用于大数据量)

from 

使用iter_keys,返回迭代器

from 

删除键 delete_pattern

from 

Redis 本地命令


django-redis 有限制的支持一些 Redis 原子操作, 例如 SETNX 和 INCR 命令.

set() 方法中加上 nx 参数使用来使用 SETNX 命令

参数:

  • nx: 只在键不存在时,才对键进行设置操作
  • SETNX:将 key 的值设为 value ,当且仅当 key 不存在
  • incr: key中储存的数字值加一
  • decr: key中储存的数字值减一

例子:

from 

当值 (value) 有合适的键 (key) 时, incr 和 decr 也可以使用 Redis 原子操作

原生客户端使用(get_redis_connection)


注:不是所有的扩展客户端都支持这个特性.

在某些情况下应用需要进入原生 Redis 客户端使用一些 django cache 接口没有暴露出来的进阶特性.

为了避免储存新的原生连接所产生的另一份设置, django-redis 提供了法 get_redis_connection(alias) 获得可重用的连接字符串.

from 

其它: [官方文档(https://django-redis-chs.readthedocs.io/zh_CN/latest/#)]

How can I use redis with Django?


Don't start using Redis or any other cache until you need the speed - don't prematurely optimize.

参考链接:How can I use redis with Django?

how do you check that the cache on redis needs updating? Do you compare record count or is there better way?


setting a TTL for the key:redis.io/commands/ttl

If the key expires, you must go to the DB. So if the key is in redis, then you use it.

Note that the simple implementation of this causes some problems:

  1. when a popular key expires you have en.wikipedia.org/wiki/Thundering_herd_problem,
  2. you want to use en.wikipedia.org/wiki/Negative_cache,
  3. and your DB needs en.wikipedia.org/wiki/Admission_control

监控redis内存:


using https://github.com/erussell/django-redis-status to monitor cache - works a charm. (Configure maxmemory on redis or the results aren't so very useful).

Reduce Django serialization time


参考链接:https://stackoverflow.com/questions/53484282/reduce-django-serialization-time

A Side By Side comparison between DRF Serializer and Django Serializer:

08f8cb77b6f0a50700d18e782dffd8b6.png

Storing/Retrieving 100K rows in redis also takes fairly less time then DB Query(about 2 seconds)

7823d7eca13002e07918a41022f79e68.png

读取过程:

  1. First, store the Json Data in Redis with a timeout. So after a certain time, the redis data will be erased and loaded from DB again.
  2. When An API is called, first check if it exists in Redis, if it is, then serve from Redis
  3. Else, serve from Seralizer and Store the JSON again in Redis.
import 

异步、celery:https://stackoverflow.com/a/53567797/10267639

使用装饰器对视图进行缓存


参考链接:

https://www.django-rest-framework.org/api-guide/caching/

https://docs.djangoproject.com/en/2.1/topics/class-based-views/intro/#decorating-the-class

https://stackoverflow.com/questions/33710689/how-can-you-use-the-cache-page-decorator-with-django-class-based-views

from 

Fastest Redis configuration for Django


参考链接:https://www.peterbe.com/plog/fastest-redis-optimization-for-django

微服务架构下静态数据通用缓存机制


参考链接:

https://mp.weixin.qq.com/s/5tKVY10gQeVMXngHh48JDg

https://mp.weixin.qq.com/s/-9wHpKGf7aJSbtShpCcoVg

什么是静态数据


静态数据:不发生变化或变化频率比较低的数据,操作频率较低的数据

静态数据要求:准确率高、实时性强、禁止丢失、错误、过长时间陈旧读

缓存的目的:提高数据查询效率 静态数据存储:保存在关系型数据库,IO效率不高 缓存(内存缓存):提升读操作的吞吐量,KV类缓存,无复杂的关系操作,O(1)

016bbbfb65292acc905f528d474cfcc5.png

业务服务:业务数据的操作接口,增删改查服务
持久化队列:可独立部署的队列程序,支持数据持久化(rabbitMQ、RocketMQ)
关系数据库:若干表持久化业务数据
缓存数据库(Redis):支持持久化的缓存数据库,这里直接选了Redis
缓存处理程序:从队列接收数据,然后写入缓存
数据一致处理程序:负责检查缓存数据库和关系数据库中的数据是否一致,不一致(关系数据库进行更新缓存数据库中的数据) 数据生产者:业务静态数据的来源(前端的功能、模块)
数据消费者:需要使用的业务静态数据的服务或者系统

为什么需要业务服务?


多个终端,同一数据多种不同的业务需要,使用接口形式提供数据,避免数据不一致、代码冗余

为什么不是进程内缓存?


很多开发语言都提供了进程内缓存的支持,即使没有提供直接操作缓存的包或库,也可以通过静态变量的方式来实现。对数据的查询请求直接在进程内存完成,效率可以说是杠杠滴了。但是进程内缓存存在两个问题:

  1. 缓存数据的大小:受系统内存大小限制,处理不了大量数据的缓存
  2. 缓存雪崩:缓存大量过期或进程重启,可能产生大量缓存穿透,太多的请求打到关系数据库上,导致关系数据库的崩溃,引发大问题。

为什么使用Redis?


可以解决进程内缓存的问题(缓存数据的大小、缓存雪崩):

  1. 独立部署,不影响其它业务,可集群,内存扩容方便
  2. 支持数据持久化,即使Redis重启,缓存的数据可快速恢复
  3. Redis提供了很好的读写性能,水平扩容能力,支持多种常用数据结构,使用方便。

为什么不用缓存过期机制?


缓存过期机制:不需要缓存处理程序和数据一致检查,从redis查询数据,存在返回,不存在在关系数据库查询,写入redis,再返回

缓存的过期时间存在的问题: 1. 缓存时间过长,数据陈旧,增加缓存穿透的概率 通过业务权衡缓存缓存方案

settings.py文件缓存配置:https://github.com/adoggie/django-learning/blob/3227ac5a6d3a82776bf60117c354b96163febd23/doc/django/cache.py

settings.py中缓存、日志、异常处理配置:https://github.com/GitFebruary/meiduo/blob/master/meiduo_mall/meiduo_mall/settings/dev.py

how to combine values from Redis and Django-rest-framework


参考链接:https://stackoverflow.com/questions/36995128/how-to-combine-values-from-redis-and-django-rest-framework

直接看代码:

from 

改进应用:

def 

Cached Instances for Django REST Framework Documentation


参考链接:

https://drf-cached-instances.readthedocs.io/en/latest/usage.html

https://media.readthedocs.org/pdf/drf-cached-instances/stable/drf-cached-instances.pdf

  • Usage
    • Create an app-specific cache strategy
    • Use the cache in views
    • Add signal hooks to update the cache
    • Handling cascading cache updates

Web API performance: profiling Django REST framework


都是好文章(好香):

https://www.dabapps.com/blog/author/tom-christie/

https://www.dabapps.com/blog/api-performance-profiling-django-rest-framework/

Summary

1. Get your ORM lookups right.


Given that database lookups are the slowest part of the view it's tremendously important that you get your ORM queries right. Use .select_related() and .prefetch_related() on the .queryset attribute of generic views where necessary. If your model instances are large, you might also consider using defer() or only() to partially populate the model instances.


关键词:select_related() prefetch_related() on the queryset

2. Your database lookups will be the bottleneck.


If your API is struggling to cope with the number of requests it's receiving your first code improvement should be to cache model instances appropriately.

You might want to consider using Django Cache Machine or Johnny Cache. Alternatively, write the caching behavior into the view level, so that both the lookup and the serialization are cached.

关键词:cache model instances appropriately

cache-machine:https://cache-machine.readthedocs.io/en/latest/

johnny cache: 支持django1.2 1.3 (过时了)

class 

3. Work on performance improvements selectively.


Remember that premature optimization is the root of all evil. Don't start trying to improve the performance of your API until you're in a position to start profiling the usage characteristics that your API clients exhibit. Then work on optimizing your views selectively, targeting the most critical endpoints first.

One of the nice things about REST framework is that because it uses regular Django views, you can easily start to optimize and strip down individual views, while still getting the benefits of working with a proper API framework instead of just using plain Django.

总结:不要过早的优化,django 和 django rest 可以配合使用,不要仅使用django

4. You don't always need to use serializers.


For performance critical views you might consider dropping the serializers entirely and simply use .values() in your database queries. If you're using hyperlinked representations or other complex fields you might find you also need to do some post processing on the data structures before returning them in the response. REST framework is designed to make this easy.

总结:并不总是需要使用序列化,可以在view中直接返回数据库中查询的值

5. Final words (结语)


To build high-performance Web APIs, focus on the right things. Use a mature, well supported, well tested and fully featured Web API framework such as REST framework, and work on improving on your API's architecture rather than the details of the framework code. Proper caching of serialized model instances and optimal usage of HTTP caching and server side caches will see huge performance gains when measured against spending time trying to slim down the server framework you're using.


Want to learn more? DabApps offers Django REST framework support and training, as well as bespoke API development services. To find out more, get in touch.


关键词: high-performance Web APIs well supported, well tested and fully featured Web API framework

总结:构建高性能的Web API,使用成熟的、支持良好的、经过良好测试的和功能齐全的Web API框架,并致力改进API的结构体系,而不是框架代码的细节。

正确缓存序列化的模型实例,以及HTTP缓存和服务器端缓存的最佳使用,将会看到巨大的性能提升,

而不是试图缩小您正在使用的服务器框架。

django缓存优化(针对的django版本比较低django1.8)

http://www.maiziedu.com/wiki/django/optimize/

django_redis源码分析


参考链接:

https://blog.csdn.net/u013210620/article/details/80022625

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值