Redis基础使用

Redis基础使用

一. 简介

​ Redis是一个开源的使用ANSI C语言编写、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库,并提供多种语言的API。从2010年3月15日起,Redis的开发工作由VMware主持。从2013年5月开始,Redis的开发由Pivotal赞助。

​ 下载地址:https://github.com/microsoftarchive/redis/releases

二. Redis的优势

:Redis非常快,每秒可执行大约110000次的设置(SET)操作,每秒大约可执行81000次的读取/获取(GET)操作。

支持丰富的数据类型:Redis支持开发人员常用的大多数数据类型,例如列表,集合,排序集和散列等等。这使得Redis很容易被用来解决各种问题,因为我们知道哪些问题可以更好使用地哪些数据类型来处理解决。

操作的原子性:所有Redis操作都是原子操作,这确保如果两个客户端并发访问,Redis服务器能接收更新的值。

很多使用工具:Redis是一个多实用工具,可用于多种用例,如:缓存,消息队列(Redis本地支持发布/订阅),应用程序中的任何短期数据,例如,web应用程序中的会话,网页命中计数等。

三. 数据类型

A. 字符串类型 (字符串的值,最大长度为512M)

B. 散列类型(Hash) (map)

C. 列表类型(List) (列表的最大长度为2^32 -1个元素,大概40亿)

D. 集合类型(Set)

E. 有序集合类型(zset)

四. 常用数据类型的操作

keys * : 获取数据库的所有的键。

exists key: 判断某个键是否存在,返回表示存在,0表示部存在。

type key: 获取键的类型(string,hash,list,set,zset)

4.1 字符串的常用操作
set key value: 设置或者覆盖值。
incr key : 将对应的键的值,递增1.
decr key : 将对应的键的值,递减1.
get key:  根据键取值。
del key [key1, key2,,]: 删除某个键。
expire key 时间(秒):设置key的存活时间,单位为秒。  
ttl code: 查看存活时间。 (TTL  Time To Live)
4.2 列表的操作
lpush key value: 往左侧中设置值。
rpush key value: 往右侧插入值。
lrange start end: 取集合中索引在[start, end]之间的值。
例:lrange aa 0 2   lrange aa 0 -1
llen key: 获取集合的长度。
lpop key: 移除并返回首元素。
rpop key: 移除并返回尾元素。
lrem key count value: 移除列表中count个值为value的数据。当count为0,移除所有。(了解)
ltrim key start end: 保留指定区域的元素,其他全部删除。
lset key index value: 设置索引为index的值为value.
lindex key index: 获取索引为index的元素。
4.3 集合的操作
sadd key member [memerb..]: 往集合中添加元素,返回添加成功的个数。
smembers key: 返回集合中所有的元素。
srem key member: 删除元素。
sismember key member: 判断member是否存在, 存在返回1,不存在返回0。
scard key: 返回集合中的个数。
srandmember key: 从集合中随机返回一个值。
spop key: 移除并返回一个随机的member.
smove src destination member: 将一个元素移动到另外一个集合中。
sinter key key: 对集合求交集。
sunion key key: 对两个集合求并集。
sdiffstore destination key1 key2:  差集运算并存储到集合中。
sinterstore destination key1 key2: 交集存储到集合中。
sunionstore destionation key1 key2: 并集存储到集合中。
4.4 Hash操作
hset key field value: 设置值, 如果存在相同的Key,对应的值会覆盖之前的。
hmset key field value filed value: 设置多个值。
hget key field: 取值。
hexists key field: 是否存在。
hgetall key: 获取集合中所有的元素。
hdel key field: 删除字段。
hkeys key: 获取所有的key。
hvals key: 获取所有的字段值。
hlen key: 获取字段的数量。
hsetnx key field value : 不存在的时候设置值。
4.5 有序集合
zadd key score value [score1 value1]: 添加。
zscore key value: 获取分数。
zrange key start end: 获取索引从start开始,到end结束的所有的元素。
zrange key start end withscores: 查询索引从start开始,到end结束的所有元素名和分数。
zcard key: 获取元素的个数。
zcount key min max: 获取在指定分数范围内的元素的个数。闭区间[min, max]
zrem key value1 [value2]: 删除元素。
zrank key value: 返回value在key中的下标。
zrangebyscore key begin end: 查询分数在[begin,end]区间的所有值,根据分数排序。
zrangebyscore key min max limit index length;  这个是在分数范围(min,max)根据索引和数据条进行分页,与sql相似
zrevrange key 2 3: 倒序排列,然后去取下标在[2, 3]区间的元素。
zremrangebyscore key min max:  移除分数在[min,max]之间的数据,返回移除的个数。
zremrangebyrank key begin end: 移除索引在[begin,end]之间的数据。

五. Redis配置

redis的核心配置文件为redis的解压目录下名为redis.windows-service.conf的模板文件,拷贝一份重命名为redis.conf文件。

默认是redis.windows-service.conf,这里设置一个新的是为了方便,启动时一般都是使用命令行redis-server +conf地址启动

5.1 安全登录

编辑redis.conf
1.绑定ip,只允许指定ip连接(可弄可不弄)

################################## NETWORK #####################################

# By default, if no "bind" configuration directive is specified, Redis listens
# for connections from all the network interfaces available on the server.
# It is possible to listen to just one or multiple selected interfaces using
# the "bind" configuration directive, followed by one or more IP addresses.
#
# Examples:
#
bind ip1
bind ip2

2.配置密码

################################## SECURITY ###################################

# Require clients to issue AUTH <PASSWORD> before processing any other
# commands.  This might be useful in environments in which you do not trust
# others with access to the host running redis-server.
#
# This should stay commented out for backward compatibility and because most
# people do not need auth (e.g. they run their own servers).
#
# Warning: since Redis is pretty fast an outside user can try up to
# 150k passwords per second against a good box. This means that you should
# use a very strong password otherwise it will be very easy to break.
#
requirepass 你的密码

3.配置日志

# Specify the log file name. Also 'stdout' can be used to force
# Redis to log on the standard output.
logfile "日志保存位置"

# To enable logging to the Windows EventLog, just set 'syslog-enabled' to
# yes, and optionally update the other syslog parameters to suit your needs.
# If Redis is installed and launched as a Windows Service, this will
# automatically be enabled.
syslog-enabled yes

主要配置logfilesyslog-enabled

4.端口

# Accept connections on the specified port, default is 6379 (IANA #815344).
# If port 0 is specified Redis will not listen on a TCP socket.
port 6379
  1. 启动
    server
redis-server redis.conf

client

redis-cli -h 你的ip -p redis端口 -a 刚配置的密码
5.2 数据的持久化

1.设置保存规则

################################ SNAPSHOTTING  ################################
#
# Save the DB on disk:
#
#   save <seconds> <changes>
#
#   Will save the DB if both the given number of seconds and the given
#   number of write operations against the DB occurred.
#
#   In the example below the behaviour will be to save:
#   after 900 sec (15 min) if at least 1 key changed
#   after 300 sec (5 min) if at least 10 keys changed
#   after 60 sec if at least 10000 keys changed
#
#   Note: you can disable saving completely by commenting out all "save" lines.
#
#   It is also possible to remove all the previously configured save
#   points by adding a save directive with a single empty string argument
#   like in the following example:
#
#   save ""

save 900 1
save 300 10
save 60 10000

使用save配置,第一个参数为秒,第二个参数为数据条,意思是如果在n秒内有m条数据就进行持久化
2.持久化地址

# The filename where to dump the DB
dbfilename dump.rdb
# The working directory.
#
# The DB will be written inside this directory, with the filename specified
# above using the 'dbfilename' configuration directive.
#
# The Append Only File will also be created inside this directory.
#
# Note that you must specify a directory here, not a file name.
dir ./
  • dbfilename 表示持久化的文件名,在符合持久化的规则时会生成一个dump.rdb文件,默认是RDB方式
  • dir 持久化路径

5.3 主从备份(灾备)(Master-Slave)

################################# REPLICATION #################################

# Master-Slave replication. Use slaveof to make a Redis instance a copy of
# another Redis server. A few things to understand ASAP about Redis replication.
#
# 1) Redis replication is asynchronous, but you can configure a master to
#    stop accepting writes if it appears to be not connected with at least
#    a given number of slaves.
# 2) Redis slaves are able to perform a partial resynchronization with the
#    master if the replication link is lost for a relatively small amount of
#    time. You may want to configure the replication backlog size (see the next
#    sections of this file) with a sensible value depending on your needs.
# 3) Replication is automatic and does not need user intervention. After a
#    network partition slaves automatically try to reconnect to masters
#    and resynchronize with them.
#
slaveof ip port

# If the master is password protected (using the "requirepass" configuration
# directive below) it is possible to tell the slave to authenticate before
# starting the replication synchronization process, otherwise the master will
# refuse the slave request.
#
masterauth admin

设置好与主机的连接,一般用来主从备份。默认是已注释的,视情况而配

六. Redis 持久化之RDB和AOF

​ Redis 有两种持久化方案,RDB(Redis DataBase)和 AOF (Append Only File).

6.1 RDB存储

​ RDB 是 Redis 默认的持久化方案。在指定的时间间隔内,执行指定次数的写操作,则会将内存中的数据写入到磁盘中。即在指定目录下生成一个dump.rdb文件。Redis 重启会通过加载dump.rdb文件恢复数据。在5.2小结已经涉及到该存储的方式。

6.2 AOF存储

​ Redis 默认不开启。它的出现是为了弥补RDB的不足(数据的不一致性),所以它采用日志的形式来记录每个写操作,并追加到文件中。Redis 重启的会根据日志文件的内容将写指令从前到后执行一次以完成数据的恢复工作。

开启AOF储存

############################## APPEND ONLY MODE ###############################

# By default Redis asynchronously dumps the dataset on disk. This mode is
# good enough in many applications, but an issue with the Redis process or
# a power outage may result into a few minutes of writes lost (depending on
# the configured save points).
#
# The Append Only File is an alternative persistence mode that provides
# much better durability. For instance using the default data fsync policy
# (see later in the config file) Redis can lose just one second of writes in a
# dramatic event like a server power outage, or a single write if something
# wrong with the Redis process itself happens, but the operating system is
# still running correctly.
#
# AOF and RDB persistence can be enabled at the same time without problems.
# If the AOF is enabled on startup Redis will load the AOF, that is the file
# with the better durability guarantees.
#
# Please check http://redis.io/topics/persistence for more information.

appendonly yes

# The name of the append only file (default: "appendonly.aof")
appendfilename "appendonly.aof"

将appendonly 改为yes,则其数据库会将你的操作保存到appendonly.aof文件中,再次启动数据库,它就会执行aof文件上你保存的操作

# The fsync() call tells the Operating System to actually write data on disk
# instead of waiting for more data in the output buffer. Some OS will really flush
# data on disk, some other OS will just try to do it ASAP.
#
# Redis supports three different modes:
#
# no: don't fsync, just let the OS flush the data when it wants. Faster.
# always: fsync after every write to the append only log. Slow, Safest.
# everysec: fsync only one time every second. Compromise.
#
# The default is "everysec", as that's usually the right compromise between
# speed and data safety. It's up to you to understand if you can relax this to
# "no" that will let the operating system flush the output buffer when
# it wants, for better performances (but if you can live with the idea of
# some data loss consider the default persistence mode that's snapshotting),
# or on the contrary, use "always" that's very slow but a bit safer than
# everysec.
#
# More details please check the following article:
# http://antirez.com/post/redis-persistence-demystified.html
#
# If unsure, use "everysec".

# appendfsync always
appendfsync everysec
# appendfsync no

appendfsync 有三个设置方式,

  • always:同步持久化,每时每刻都存入磁盘里,性能较差,但是保证数据完整
  • everysec:每秒存一次,并发时,可能会造成数据丢失
  • no: 不同步
6.3 总结
  1. Redis 默认开启RDB持久化方式,在指定的时间间隔内,执行指定次数的写操作,则将内存中的数据写入到磁盘中。
  2. RDB 持久化适合大规模的数据恢复,但它的数据一致性和完整性较差。
  3. Redis 需要手动开启AOF持久化方式,默认是每秒将写操作日志追加到AOF文件中。
  4. AOF 的数据完整性比RDB高,但记录内容多了,会影响数据恢复的效率。
  5. Redis 针对 AOF文件大的问题,提供重写的瘦身机制。
  6. 若只打算用Redis 做缓存,可以关闭持久化。
  7. 若打算使用Redis 的持久化。建议RDB和AOF都开启。其实AOF更适合做数据的备份,留一后手。RDB出问题了,还有AOF。

七. 虚拟机docker上的Redis安装

这里使用docker三剑客的docker-compose
虚拟机上编写docker-compose.yml

  redis:
    image: redis
    container_name: redis
    ports:
      - 6375:6375
    volumes:
     - ./redis:/etc/redis
    tty: true

保存后输入

docker-compose up -d
# 完成后
docker ps # 可看到redis容器

八. Redis集群

A. 在redis的解压目录下新建rediscluster文件夹,将redis的解压目录下的redis.conf文件拷贝到rediscluster目录下,将该文件复制六份,名字分别为:

  • redis-6379.conf
  • redis-6380.conf
  • redis-6381.conf
  • redis-6382.conf
  • redis-6383.conf
  • redis-6384.conf

B. 以redis-6379.conf文件为例,修改其中的内容,修改部分内容如下:

port 6379
cluster-enabled yes
cluster-config-file /redis/nodes/nodes-6379.conf  #文件夹需要创建
cluster-node-timeout 15000

C. 分别启动六个redis服务,命令如下:

src/redis-server ../rediscluster/redis-6379.conf &
src/redis-server ../rediscluster/redis-6380.conf &
src/redis-server ../rediscluster/redis-6381.conf &
src/redis-server ../rediscluster/redis-6382.conf &
src/redis-server ../rediscluster/redis-6383.conf &
src/redis-server ../rediscluster/redis-6384.conf &

在这里插入图片描述

D. 配置集群,进入到redis的src目录下,执行如下命令:

./redis-cli --cluster create 127.0.0.1:6379 127.0.0.1:6380 127.0.0.1:6381 127.0.0.1:6382 127.0.0.1:6383 127.0.0.1:6384 --cluster-replicas 1

在这里插入图片描述

E. shell脚本启动,脚本内容如下:

#!/bin/bash
`/redis/redis-5.0.5/src/redis-server /redis/rediscluster/redis-6379.conf > /dev/null &` &&
`/redis/redis-5.0.5/src/redis-server /redis/rediscluster/redis-6380.conf > /dev/null &` &&
`/redis/redis-5.0.5/src/redis-server /redis/rediscluster/redis-6381.conf > /dev/null &` &&
`/redis/redis-5.0.5/src/redis-server /redis/rediscluster/redis-6382.conf > /dev/null &` &&
`/redis/redis-5.0.5/src/redis-server /redis/rediscluster/redis-6383.conf > /dev/null &` &&
`/redis/redis-5.0.5/src/redis-server /redis/rediscluster/redis-6384.conf > /dev/null &`

sleep 3s

`/redis/redis-5.0.5/src/redis-cli --cluster create 127.0.0.1:6379 127.0.0.1:6380 127.0.0.1:6381 127.0.0.1:6382 127.0.0.1:6383 127.0.0.1:6384 --cluster-replicas 1 > /dev/null &`

到此就把基本redis使用给讲完,是不是很简单呀。redis引用场景有很多,做缓存、做数据保存等等…看待具体场景来使用就好。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值