Redis简介与安装
Redis 简介
1、基本信息
Redis(Remote Dictionary Server)
Redis 是一个开源(BSD 许可)的,内存中的数据结构存储系统,它可以用作数据库、缓存和消息中间件。 它支持多种类型的数据结构,如 字符串(strings), 散列(hashes), 列表(lists), 集合(sets), 有序集合(sorted sets) 与范围查询, bitmaps, hyperloglogs 和 地理空间(geospatial) 索引半径查询。 Redis 内置了 复制(replication),LUA 脚本(Lua scripting), LRU 驱动事件(LRU eviction),事务(transactions) 和不同级别的 磁盘持久化(persistence), 并通过 Redis 哨兵(Sentinel)和自动 分区(Cluster)提供高可用性(high availability)
2、应用场景
①Redis 的典型应用场景:
[1]缓存
使用 Redis 可以建立性能非常出色的缓存服务器,查询请求先在 Redis 中查找所需要的数据,如果能够查询到(命中)则直接返回,大大减轻关系型数据库的压力。
[2]数据临时存储位置
使用 token(令牌)作为用户登录系统时的身份标识,这个 token 就可以在 Redis 中临时存储。
[3]分布式环境下解决 Session 不一致问题时的 Session 库
Spring 提供了一种技术,用来解决分布式环境下 Session 不一致问题,叫 SpringSession。
而 Redis 就可以为 SpringSession 提供一个数据存储空间。
[4]流式数据去重
在 Redis 中有一种数据类型是 set,和 Java 中的 Set 集合很像,不允许存储重复数据。借助这个特性我们可以在 Redis 中使用 set 类型存储流式数据达到去重的目的。
②Redis 不适用的场景
[1]直接查询 value
Redis 是一个严格的 Key-value 数据库,所有数据都必须通过 key 去找到 value,Redis 没有提供直接根据查询条件匹配 value 的方法。
[2]用多键一值表示特定关系
Redis 中一个 key 对应一个 value,没有多个 key 对应同一个 value 的情况。
[3]事务中回滚
Redis 不支持回滚。如果一个命令在加入队列时没有检测出问题,那么队列执行时不会因为某一条命令失败而回滚。
Redis 安装
1、上传并解压
redis-4.0.2.tar.gz
2、安装 C 语言编译环境
1 | yum install -y gcc-c++ |
3、修改安装位置
编辑 redis 解压目录下的 /src/Makefile 文件
安装路径 PREFIX?=/usr/local 修改为 PREFIX?=/usr/local/redis
目的:防止以后安装其它程序产生冲突
# PREFIX?=/usr/local > PREFIX?=/usr/local/redis
INSTALL_BIN=$(PREFIX)/bin
INSTALL=install
4、编译安装
编译:进入 Redis 解压目录 执行 make 命令
1 | make install |
5、定制配置项启动
[1]准备配置文件
复制 redis 解压目录下的 redis.conf 文件到 /usr/local/redis/ 目录下
1 | cp /opt/redis-4.0.2/redis.conf /usr/local/redis/ |
[2]修改配置项
配置项名称 | 作用 | 取值 |
---|---|---|
daemonize | 控制是否以守护进程形式运行 Redis 服务器 | yes |
logfile | 指定日志文件位置 | “/var/logs/redis.log” |
dir | Redis 工作目录 | /usr/local/redis |
注意:/var/logs 目录需要我们提前创建好
1 | cd /var |
1 | vim /usr/local/redis/redis.conf |
一般模式下输入 :set nu 显示行号,输入 / 进入搜索关键词的指令模式
分别搜索daemonize,logfile,dir 三个关键词进行修改。
(1)控制是否以守护进程形式运行 Redis 服务器
134 # By default Redis does not run as a daemon. Use ‘yes’ if you need it.
135 # Note that Redis will write a pid file in /var/run/redis.pid when daemoniz ed.
136 # daemonize no
137 daemonize yes
(2)指定日志文件位置
169 # Specify the log file name. Also the empty string can be used to force
170 # Redis to log on the standard output. Note that if you use standard
171 # output for logging but daemonize, logs will be sent to /dev/null
172 logfile “/var/logs/redis.log”
(3)Redis 工作目录
256 # The working directory.
257 #
258 # The DB will be written inside this directory, with the filename specified
259 # above using the ‘dbfilename’ configuration directive.
260 #
261 # The Append Only File will also be created inside this directory.
262 #
263 # Note that you must specify a directory here, not a file name.
264 #dir ./
265 dir /usr/local/redis
[3]让 Redis 根据指定的配置文件启动
redis-server 文件路径 redis.conf 文件路径
1 | /usr/local/redis/bin/redis-server /usr/local/redis/redis.conf |
命令运行之后,Redis 服务器就启动了。
[4]客户端登录
1 | /usr/local/redis/bin/redis-cli |