Redis 学习

 
 公司使用redis 进行发布消息队列,以及写入缓存。特学习做此笔记
Redis:
为数据结构服务器,一种key-value存储系统,value可以是String、Map、list、sets
Redis配置:
Redis 的配置文件位于 Redis 安装目录下,文件名为 redis.conf。
你可以通过 CONFIG 命令查看或设置配置项。
127.0.0.1:6379> config get *
Redis 数据类型:
1、String 字符串
127.0.0.1:6379> set name "test"
OK
127.0.0.1:6379> get name
"test"
127.0.0.1:6379> del name
(integer) 1
127.0.0.1:6379> get name
(nil)
注意:一个键最大能存储512MB。
2、Hash
一个键值对集合
Redis hash 是一个 string 类型的 field 和 value 的映射表,hash 特别适合用于存储对象。
127.0.0.1:6379> HMSET myhash mytest1 "hahha" mytest2 "lalala"
OK
127.0.0.1:6379> HGET mytest1
(error) ERR wrong number of arguments for 'hget' command
127.0.0.1:6379> HGET myhash mytest1
"hahha"
127.0.0.1:6379> HGET myhash mytest2
"lalala"
 
3、List
简单的字符串列表,按顺序插入
列表最多可存储 232 - 1 元素 (4294967295, 每个列表可存储40多亿)。
127.0.0.1:6379> lpush mytest test1
(integer) 1
127.0.0.1:6379> lpush mytest test2
(integer) 2
127.0.0.1:6379> lpush mytest3 test3
(integer) 1
127.0.0.1:6379> rpush mytest test3
(integer) 3
127.0.0.1:6379> lrange mytest 0 10
1) "test2"
2) "test1"
3) "test3"
4、Set
集合是通过哈希表实现的,所以添加,删除,查找的复杂度都是O(1)。
127.0.0.1:6379> sadd key test1
(integer) 1
127.0.0.1:6379> sadd key test2
(integer) 1
127.0.0.1:6379> sadd key test3
(integer) 1
127.0.0.1:6379> smembers key
1) "test1"
2) "test3"
3) "test2"
添加一个 string 元素到 key 对应的 set 集合中,成功返回1,如果元素已经在集合中返回 0,如果 key 对应的 set 不存在则返回错误。
5、zset
Redis命令:
redis-cli 启动客户端
在远程服务器上执行命令:redis-cli -h host -p port -a password
Redis 键(KEY)
基本语法:
command key_name
例:
DUMP key 序列化给定key 
DEL key
EXISTS key .  检查是否存在
6、Redis HyperLogLog
 
Redis 发布订阅
Redis 发布订阅(pub/sub)是一种消息通信模式:发送者(pub)发送消息,订阅者(sub)接收消息。
Redis 客户端可以订阅任意数量的频道。
订阅者先订阅了频道channel ,当有新消息通过PUBLISH命令发送给频道时,这些消息就会发送到订阅它的客户端
例:
客户端订阅频道消息:
SUBSCRIBE redisChat
Reading messages... (press Ctrl-C to quit)
通过PUBLISH发送新消息:
127.0.0.1:6379> PUBLISH redisChat "Redis is a great caching technique"
(integer) 1
127.0.0.1:6379> PUBLISH redisChat "hahahah"
(integer) 1
127.0.0.1:6379>
客户端接收到频道:
127.0.0.1:6379> SUBSCRIBE redisChat
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "redisChat"
3) (integer) 1
1) "message"
2) "redisChat"
3) "Redis is a great caching technique"
1) "message"
2) "redisChat"
3) "hahahah"
Redis 事务
可以一次执行多个命令,批量操作发生EXEC命令前被放入队列换成,
收到EXEC命令黄埔进入事务执行,
在事务执行过程,其他客户端提交的命令请求不会插入到事务执行命令序列中。
 
事务从开始到执行会经历以下三个阶段:
开始事务
命令入列
执行事务
 
栗子:
以MULTI开始一个事务,然后将多个命令入队到事务中,最后由EXEC 触发事务
127.0.0.1:6379> MULTI
OK
127.0.0.1:6379> SET test "hahahaha"
QUEUED
127.0.0.1:6379> GET test
QUEUED
127.0.0.1:6379> SADD tag "test1" "test2"
QUEUED
127.0.0.1:6379> SMEMBERS tag
QUEUED
127.0.0.1:6379> EXEC
1) OK
2) "hahahaha"
3) (integer) 2
4) 1) "test1"
2) "test2"
Redis脚本
Redis连接
检查是否连接上
127.0.0.1:6379> PING
PONG
断开连接
127.0.0.1:6379> QUIT
获取Redis服务器版本信息
127.0.0.1:6379> INFO
Redis数据备份与恢复
 
 
 
 

原文地址:https://www.cnblogs.com/LinxiHuang/p/10052943.html