centos中安装redis

Centos中安装配置redis缓存数据库

1.检查gcc

gcc -v
没有则进行安装: yum install -y gcc

2.下载redis安装包

wget http://download.redis.io/releases/redis-5.0.3.tar.gz

服务操作命令

systemctl start redis.service #启动redis服务

systemctl stop redis.service #停止redis服务

systemctl restart redis.service #重新启动服务

systemctl status redis.service #查看服务当前状态

systemctl enable redis.service #设置开机自启动

systemctl disable redis.service #停止开机自启动

Django的缓存配置 settings.py

CACHES = {
“default”: {
“BACKEND”: “django_redis.cache.RedisCache”,
“LOCATION”: “redis://127.0.0.1:6379”,
“OPTIONS”: {
“CLIENT_CLASS”: “django_redis.client.DefaultClient”,
}
}
}

视图中使用

from django_redis import get_redis_connection
from django.core.cache import cache

设置redis缓存

key value timeout

cache.set(‘index_page_data’, context, 3600)

获取用户的历史浏览记录

from redis import StrictRedis

sr = StrictRedis(host=‘127.0.0.1’, port=‘6379’, db=9)

con = get_redis_connection(‘default’)

history_key = ‘history_%d’%user.id

获取用户最新浏览的5个商品的id

sku_ids = con.lrange(history_key, 0, 4) # [2,3,1]

存:

添加用户的历史记录

conn = get_redis_connection(‘default’)
history_key = ‘history_%d’%user.id

移除列表中的goods_id

conn.lrem(history_key, 0, goods_id)

把goods_id插入到列表的左侧

conn.lpush(history_key, goods_id)

只保存用户最新浏览的5条信息

conn.ltrim(history_key, 0, 4)

取:
con = get_redis_connection(‘default’)
history_key = ‘history_%d’%user.id

获取用户最新浏览的5个商品的id

sku_ids = con.lrange(history_key, 0, 4) # [2,3,1]

创建缓存表

python manage.py createcachetable

检查cache过期时间

在 redis 中, 你可以获取任何 key 的 ttl, django-redis 也支持获取 ttl 的函数:

它返回:
0 key 不存在 (或已过期).
None key 存在但没有设置过期.
ttl 任何有超时设置的 key 的超时值.

cache.ttl(‘v’)
2998
通配符搜索:
cache.keys(“foo_*”)

timeout=0 立即过期
timeout=None 永不超时
cache.set(“key”, “value”, timeout=None)

2021-01-12

django队列用法

django中消息message

列表:
lpush左侧追加
rpush右侧追加

import redis

r = redis.Redis(host = ‘localhost’, port = 6379, db = 0)
r.set(‘k1’, ‘v1’)
r.set(‘k2’, ‘v2’)
print(r.get(‘k1’))
print(r.keys()) # 打印当前所有的keys
print(r.dbsize()) # 查看当前有多少keys
r.delete(‘k2’)#删除k2
print(r.keys())
print(r.dbsize())
print(dir®) # 查看redis对应的方法

列表

llen 元素的个数
rpush 右添加
lpush 左添加

键不能重复,重复会出错
redis.exceptions.ResponseError: WRONGTYPE Operation against a key holding the wrong kind of value
列表中删除,name, value, num:0所有,-1后往前,1前往后

r.lrem(name, json.dumps(datas), 0)

lpop(name) 删除一个,返回第一个值

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值