1、常用命令
set hello word (默认hello是key,word是value值)
插入列表类型键值对
rpush mylist a b c d e f
数据库键值总数:dbsize;
检查键值存在否:exists java,存在返回1,否则0
删除键值:del key {key。。。}
键过期:expire key seconds
如:set hello word
expire hello 10(10秒)
键数据类:type a
type返回实际的当前键的数据结构类型:string hash list set zset(有序集合)
2、单线程框架:
client--发送命令--执行命令--返回结果
其他--命令2--命令(队列)//所有命令在一个队列力排队等待
单线程快的原因:
(1)纯内存访问,redis数据在内存中,响应时间为100ns(纳秒)
(2)非阻塞i/o,使用epoll作为I/O多路复用技术实现,加上事件处理模型
(3)单线程避免线程切换和竞态产生的消耗
缺点:命令执行过长,造成其他命令阻塞
3、字符串
setnx只有一个客户端设置成功,setnx为分布式锁的实现方案
获取值:get hello
批量设置值:mset key value[key value...]
如:一次设置4个键值对
mset m 1 b 2 g 4 h 6 表示m值为1,b值为2,,,
批量获取值:mget m b g h
计数:incr key 对值作自增
4、典型使用场景
(1)缓存
能加速读写和降低后端压力作用
1)获取用户的信息:
UserInfo getUserInfo(long id){
userRedisKey = "user:info:"+id
value= redis.get(userRedisKey)
if(value != null){
userInfo = deserialize(value);//反序列化返回结果
}else{//为空从数据库获取,并将写过写进redis,1小时过期
userInfo = mysql.get(id);
if(userInfo !=null)
redis.setex(userRedisKey,3600,serialize(userInfo))
}
return userInfo
}
(2)计数
如:视频播放数使用redis,用户播放一次就增加
long incrVideoCounter(long id){
key = "vedio:playCount:"+id;
return redis.incr(key)
}
(3)共享session
使用redis管理可避免用户每次刷新导致重新登录、
(4)限速
短信验证码避免访问短信接口,限制一分钟重新获取验证码
哈希
字符串与hash类型对比:
字符串:key(name) value(tom) value
hash:key(user1) name tom
age "28"
field value
今日学习了这小部分,接下来学习后继续分享~