Redis Getting Started - Introduction, installation, configuration

A, Redis Introduction

Redis is completely free open source, BSD comply with the agreement, it is a high-performance key-value database.

Redis and other key - value caching product has the following three characteristics:
1.Redis support data persistence, data in memory can be saved to disk, reboot to load when you can be reused.
2.Redis only supports simple key-value data types, while also providing a storage list, set, zset, hash and other data structures.
3.Redis support for backup data, namely data backup master-slave mode.

Two, Redis using background

In our daily Java Web development, all are using the database to store data, due to the general system tasks typically do not exist in the case of high concurrency, so this seems to be no problem, but when it comes to large amounts of data demand for some commodities such as buying the scene, or home visits moment when the larger, single-use database to store system data because of problems facing the disk, disk read / write speed is relatively slow and serious performance drawbacks, thousands of instant request comes in, the system needed to complete thousands of read / write operations in a very short period of time, this time more often than not be able to withstand the database, the database system is extremely easy to cause paralysis, eventually leading service dang serious production problems machine.

In order to overcome the above problems, Java Web projects often introduce NoSQL technology, which is a memory-based database, and provide some persistence function.
Redis and MongoDB is currently the most widely used NoSQL, and it Redis technology, its performance is excellent, can support hundreds of thousands per second read / write operations, its performance far exceeds the database, and also supports clusters, distributed style, master-slave synchronization configuration can be unlimited expansion on principle, so that more data is stored in memory, even more reassuring is that it also supports the ability of certain transactions , which guarantees the safety of the scene under high concurrency and data consistency.

Three, Redis advantage

1. extremely high performance - Redis can read as fast as 110,000 times / s, write speed is 81000 times / s.
2. Rich data types - Redis supports binary case Strings, Lists, Hashes, Sets and Ordered Sets the data type of the operation.
3. Atomic - Redis all operations are atomic, and atomic Redis also supports the implementation of a full and after several operations.
4. The feature-rich - Redis also supports publish / subscribe, notification, key expiration and so on characteristics.

Four, Redis NoSQL storage and other different

1.Redis has a more complex data structure and provide atomic operations on them , which is different from the other databases evolutionary path. Meanwhile Redis data types are based on the basic data structure transparent to the programmer, without the need for additional abstraction.
2.Redis running in memory, but can be persisted to disk , so the trade-off at the time of high-speed memory read and write different data sets because the data can not be greater than the amount of hardware memory. Another advantage of in-memory databases are, compared to the same complex data structures, operate in a very simple memory on the disk, so you can do a lot of internal Redis highly complex matter. Meanwhile, in terms of their compact disk format to generate additional way, because they do not require random access.

V. Application of Redis in JavaWeb

Redis in Java Web there are two main scenarios:
1. caching - storing frequently used data;
2. high-speed read / write - use it fast read / write;

1. Cache

In daily access to the database, the number of read operations to write operations far more than the proportion of about 1: 9-3: 7, so the possibility is likely to be read than to write much of. When we use the SQL statement to read and write to the database, the database will go to the disk to get back the data corresponding to the index, which is a relatively slow process.

If we put the data in Redis, that is placed directly into memory, let the server directly to read the data in memory, because the memory read and write speed of the disk than quickly, so it will read and write speeds significantly faster a lot of pressure, and will greatly reduce the database, but the use of memory for data storage overhead is relatively large because of limited cost, in general we just use some common and major Redis data store, such as user login information.

In general when using Redis storage, we need to consider the following aspects:
1. Business Data used it? How hits? If the hit rate is very low, there is no need to write caching;
2. The multi-operation business data is read or write operation and more? If the write operation and more frequent need to write to the database, there is no need to use caching;
3. How does the business data size? If you want to store hundreds of megabytes of files, the cache will bring a lot of pressure, so there is no need;
After considering these issues, if you feel the need to use the cache, then use it!

Redis used as a read logical register as shown below:
Here Insert Picture Description
From the graph we can know the following two points:

When first reading data, the read data Redis fails, then the program reads the database is triggered, the data is read out and written in Redis;
when the second and subsequent need to read data, it will directly read Redis, read the data after the end of the process, so speed is greatly improved.
From the above analysis can be known, much greater than the possibility of read operation is a write operation, the data processing routine using Redis need to frequently read the speed increase will be apparent, while also reducing dependence on the database, so that database the pressure is greatly reduced.

Analysis of logical reads, let's take a look at the process writes:
Here Insert Picture Description
As can be seen from the process, update or write operation, the operation requires multiple Redis, if the actual application scenario, the business data is much larger than the number of read write the number of times there is no need to use Redis.

2. High-speed read / write applications

In today's Internet, the situation is more and more the presence of high concurrency, the most common way to power systems business scene spike goods, such as Lynx double 11, to grab Li concert tickets, etc., these occasions are there are thousands in an instant request arrives at the server, if the mere use of the database for processing, if not collapse, will be very slow, ranging from causing poor user experience loss of users, while in the database paralyzed, service dang machine, but such occasions are not allowed!

So we need to use Redis to deal with such a high concurrency requirements of the occasion, we take a look at a flowchart request to:
Here Insert Picture Description
We further illustrate this process:

When a request arrives at the server, only the service data (stock product spike) carried on Redis reader, the database without any operation, so can greatly improve the speed of reading and writing, to meet the needs of high-speed response;
but the cached data is still required persistence, which is stored in the database, so a read operation is complete Redis request / write later, it will go to determine whether the high-speed read / write operations end, the judge will usually spike stock is zero, the amount of red envelopes 0:00 establishment, if not established, it will not operate the database; if true, the trigger event will be cached Redis data into the database in the form of a batch of one-time, thus completing the persistent work .

Six, Redis installation

1.Window under installation

Download: https://github.com/MSOpenTech/redis/releases

Redis supports 32-bit and 64-bit. This according to the actual circumstances of your system platform selection, here we Redis-x64-xxx.zip download archive to the C drive, unzip the folder renamed Redis .
Here Insert Picture Description
Open the folder, as follows:
Here Insert Picture Description
Open a cmd window using the cd command to change the directory to C: \ redis run:

redis-server.exe redis.windows.conf

如果想方便的话,可以把 redis 的路径加到系统的环境变量里,这样就省得再输路径了,后面的那个 redis.windows.conf 可以省略,如果省略,会启用默认的。输入之后,会显示如下界面:
Here Insert Picture Description
上图的提示信息告诉了我们:① Redis 当前的版本为 3.0.100/位数为64 位;② Redis 运行在 6379 端口;③ Redis 进程的 PID 为 15292;

至此,Redis服务端就启动完成了。接下来进行Redis客户端的启动。

Redis目录下有一个redis-cli.exe 文件,这是 Redis 自带的一个客户端工具,它可以用来连接到我们当前的 Redis 服务器。
启动客户端需要另启一个 cmd 窗口,原来的服务端窗口不要关闭,不然就无法访问服务端了。
切换到 redis 目录下运行:

redis-cli.exe -h 127.0.0.1 -p 6379

设置键值对:

set myKey abc

取出键值对:

get myKey

Here Insert Picture Description
至此,我们便在 Windows 的环境下安装好了 Redis。

2.Linux环境下安装

下载地址: http://redis.io/download,下载最新稳定版本。

本教程使用的最新文档版本为 2.8.17,下载并安装:

$ wget http://download.redis.io/releases/redis-2.8.17.tar.gz
$ tar xzf redis-2.8.17.tar.gz
$ cd redis-2.8.17
$ make

make完后 redis-2.8.17目录下会出现编译后的redis服务程序redis-server,还有用于测试的客户端程序redis-cli,两个程序位于安装目录 src 目录下:

下面启动redis服务.

$ cd src
$ ./redis-server

注意这种方式启动redis 使用的是默认配置。 也可以通过启动参数告诉redis使用指定配置文件使用下面命令启动。

$ cd src
$ ./redis-server ../redis.conf

redis.conf 是一个默认的配置文件。我们可以根据需要使用自己的配置文件。

启动redis服务进程后,就可以使用测试客户端程序redis-cli和redis服务交互了。 比如:

$ cd src
$ ./redis-cli
redis> set foo bar
OK
redis> get foo
"bar"

七、Redis 配置

Redis 的配置文件位于 Redis 安装目录下,文件名为 redis.conf(Windows 名为 redis.windows.conf)。

你可以通过 CONFIG 命令查看或设置配置项。
语法

Redis CONFIG 命令格式如下:

redis 127.0.0.1:6379> CONFIG GET CONFIG_SETTING_NAME
实例
redis 127.0.0.1:6379> CONFIG GET loglevel

1) "loglevel"
2) "notice"

使用 * 号获取所有配置项:

实例
redis 127.0.0.1:6379> CONFIG GET *

"dbfilename"
"dump.rdb"
"requirepass"
""
"masterauth"
""
"unixsocket"
""
"logfile"
""
"pidfile"
"/var/run/redis.pid"
"maxmemory"
"0"
"maxmemory-samples"
"3"
"timeout"
"0"
"tcp-keepalive"
"0"
"auto-aof-rewrite-percentage"
"100"
"auto-aof-rewrite-min-size"
"67108864"
"hash-max-ziplist-entries"
"512"
"hash-max-ziplist-value"
"64"
"list-max-ziplist-entries"
"512"
"list-max-ziplist-value"
"64"
"set-max-intset-entries"
"512"
"zset-max-ziplist-entries"
"128"
"zset-max-ziplist-value"
"64"
"hll-sparse-max-bytes"
"3000"
"lua-time-limit"
"5000"
"slowlog-log-slower-than"
"10000"
"latency-monitor-threshold"
"0"
"slowlog-max-len"
"128"
"port"
"6379"
"tcp-backlog"
"511"
"databases"
"16"
"repl-ping-slave-period"
"10"
"repl-timeout"
"60"
"repl-backlog-size"
"1048576"
"repl-backlog-ttl"
"3600"
"maxclients"
"4064"
"watchdog-period"
"0"
"slave-priority"
"100"
"min-slaves-to-write"
"0"
"min-slaves-max-lag"
"10"
"hz"
"10"
"no-appendfsync-on-rewrite"
"no"
"slave-serve-stale-data"
"yes"
"slave-read-only"
"yes"
"stop-writes-on-bgsave-error"
"yes"
"daemonize"
"no"
"rdbcompression"
"yes"
"rdbchecksum"
"yes"
"activerehashing"
"yes"
"repl-disable-tcp-nodelay"
"no"
"aof-rewrite-incremental-fsync"
"yes"
"appendonly"
"no"
"dir"
"/home/deepak/Downloads/redis-2.8.13/src"
"maxmemory-policy"
"volatile-lru"
"appendfsync"
"everysec"
"save"
"3600 1 300 100 60 10000"
"loglevel"
"notice"
"client-output-buffer-limit"
"normal 0 0 0 slave 268435456 67108864 60 pubsub 33554432 8388608 60"
"unixsocketperm"
"0"
"slaveof"
""
"notify-keyspace-events"
""
"bind"
""
编辑配置

你可以通过修改 redis.conf 文件或使用 CONFIG set 命令来修改配置。

语法

CONFIG SET 命令基本语法:

redis 127.0.0.1:6379> CONFIG SET CONFIG_SETTING_NAME NEW_CONFIG_VALUE

实例

redis 127.0.0.1:6379> CONFIG SET loglevel "notice"
OK
redis 127.0.0.1:6379> CONFIG GET loglevel

"loglevel"
"notice"
Redis配置具体参数说明:https://www.cnblogs.com/jianmingyuan/p/11089406.html

Redis持久化配置

redis有两种持久化方式:RDBAOF
具体差别跟优缺点可参考redis数据的两种持久化方式对比

RDB配置方式

默认情况下,是快照RDB的持久化方式,将内存中的数据以快照的方式写入二进制文件中,默认的文件名是dump.rdb

redis.conf默认配置:

save 900 1
save 300 10
save 60 10000

配置含义:

900秒内,如果超过1个key被修改,则发起快照保存

300秒内,如果超过10个key被修改,则发起快照保存

60秒内,如果1万个key被修改,则发起快照保存

默认配置不方便看效果,可将快照频率设大一点,在redis.conf中增加一行:

save 10 1

保存后,启动redis服务端和客户端。在客户端输入命令:
Here Insert Picture Description
输入完,发现dump.rdb文件的修改日期变了,并且redis服务端增加了保存日志:
Here Insert Picture Description
接下来,重启redis服务端和客户端,看数据是否真的持久化了:
Here Insert Picture Description
取到对应key的value值与之前设置的相同,说明使用RDB快照持久化成功了。

AOF 配置方式

redis.conf默认配置:

appendonly no

配置文件中的appendonly修改为yes,开启AOF持久化。 开启后,启动redis服务端,发现多了一个appendonly.aof文件
Here Insert Picture Description
使用AOF做持久化,每一个命令以 Redis 协议的格式来保存,新命令会被追加到文件的末尾。 Redis 还可以在后台对 AOF 文件进行重写,使得 AOF文件的体积不会超出保存数据集状态所需的实际大小。实际上,AOF持久化并不会立即将命令写入到硬盘文件中,而是写入到硬盘缓存,在接下来的策略中,配置多久来从硬盘缓存写入到硬盘文件。所以在一定程度一定条件下,还是会有数据丢失,不过你可以大大减少数据损失。

appendfsync always
appendfsync everysec
appendfsync no

配置含义:

always: 每次操作都会立即写入aof文件中

everysec: 每秒持久化一次(默认配置)

no: 不主动进行同步操作,默认30s一次

当然always一定是效率最低的,个人认为everysec就够用了,数据安全性能又高。Redis也允许我们同时使用两种方式,再重启redis后会从AOF中恢复数据,因为AOF比RDB数据损失小。

Once configured, start redis client, enter the command:
Here Insert Picture Description
Final flushall is to clear all the keys. Appendonly.aof open the file, you can see:
Here Insert Picture Description
remove the rearmost flushall (command can also be increased in accordance with redis agreement), restart the client and server to see if the data is really persistence:
Here Insert Picture Description
get to the value previously set value Like, instructions AOF persistence are successful.

Summary: two kinds of persistent modes, a RDB model specifies the frequency of persistence, when satisfied, the data stored on disk; AOF and command each operation mode are stored in the disk cache, then the configuration item appendfsync to specify how often a collection of disk cache synchronization commands to disk storage. Relatively speaking, the volume will be greater than a RDB AOF file, but the lost data recovery less.

Since the AOF save the file in an orderly manner all write operations performed on the database, the write operation to save the format Redis protocol, if you are not careful implementation of FLUSHALL command, but as long as AOF file has not been overwritten, so long as the server is stopped remove FLUSHALL command AOF end of the file, and restart Redis, you can restore the data set to the state before FLUSHALL execution.

Reference links:

Redis Tutorial - Tutorial rookie
Redis [entry] on this one!

Released five original articles · won praise 2 · Views 592

Guess you like

Origin blog.csdn.net/qq_42230770/article/details/104101633