锐英源软件
第一信赖

精通

英语

开源

擅长

开发

培训

胸怀四海 

第一信赖

当前位置:锐英源 / 开源技术 / C语言开源技术 / Redis、Redis开源社区、Redis配置和Redis维护
联系方式
固话:0371-63888850

手机:138-0381-0136

Q Q:396806883
微信:ryysoft

Redis


最近几年PC装机要配置固态硬盘,原理就是内存速度比硬盘快,能加快机器运行速度,这个原理也在软件领域得到了拓展。

什么是Redis? Redis是开放源代码(BSD许可)的内存数据结构存储,用作数据库、缓存和消息代理。

您可以将其视为No-SQL数据库,该数据库将数据作为键值对存储在系统内存中。如果需要,Redis也支持磁盘持久数据存储。

Redis支持存储多种数据结构和数据类型,包括字符串、列表、哈希、集合和排序集合。受支持的数据结构为Redis提供了许多用例的多功能性。

在需要在最短时间内检索数据并将其交付给客户端的情况下,Redis是最佳选择。

Redis用例

Redis最受欢迎的用例之一是缓存。

什么是缓存机制?

缓存机制是将数据副本存储在内存缓存中以允许应用程序更快地访问和检索数据的过程。缓存的目的是比数据库或远程服务器所允许的速度更好地加快数据访问操作。昂贵的(及时的)操作尤其如此。

作为后端开发人员,我们的任务是尽快完成客户的请求。有时,查询需要执行多项操作,例如从数据库中检索数据,执行计算,从其他服务中检索其他数据等,这些操作都会降低我们的性能。

在这里缓存非常出色,因为我们可以处理一次数据,将其存储在缓存中,然后稍后直接从缓存中检索数据,而无需执行所有那些昂贵的操作。然后,我们将定期更新缓存,以便用户可以查看更新的信息。

缓存和Redis

由于Redis是内存数据库,因此它的数据访问操作比任何其他磁盘绑定数据库都能提供的快。它使Redis成为缓存的理想选择。它的键值数据存储是另一个优点,因为它使数据存储和检索更加简单。

实时分析

Redis承诺进行亚毫秒级的长时间数据处理操作。它使Redis成为依赖实时数据分析的应用程序的理想之选。

例如,在实施实时欺诈检测服务时,可以使用Redis存储用户身份及其交易详细信息。 Redis甚至提供了AI支持的更快的交易评分系统和更快的统计模型,以更好地执行此用例。

实时分析中的其他用例包括实时库存管理系统和游戏排行榜。

如果您的应用程序使用会话来跟踪经过身份验证的用户并管理特定于用户的数据,则Redis非常适合用作会话存储。使用Redis可以显着提高系统的性能,同时使处理用户数据(包括凭据,最近的活动,甚至是购物车之类的系统)更加容易。

Redis作为队列

您可以使用Redis将需要很长时间才能完成的应用程序任务排队。您可以实施FIDO(先进先出)队列,也可以创建延迟的队列以将任务实施延迟到预定的时间。

 

Redis开源社区

这里推出锐英源的国外内容翻译文章、Redis使用技巧和Redis代码理解文档,欢迎同行交流。

 
Exe2Srvc启动Redis服务且C#直接控制服务
用MySQL引导Redis入门
  
Redis配置

Redis安装

您可以使用以下命令下载二进制文件并轻松编译它们。

wget https://download.redis.io/releases/redis-6.0.0.tar.gz
          tar xzf redis-6.0.9.tar.gz
          cd redis-6.0.9
          make
          make install

要确保Redis服务器正常运行,请使用redis-cli向服务器发送ping命令。

redis-cli ping

如果收到pong作为响应,则Redis服务器正在成功运行。

如果出现问题,请阅读官方的快速入门指南以获取更好的主意。

 

通过对名为redis.conf的配置文件进行更改来配置Redis。可以在安装Redis的目录的根目录下找到此文件。如果您只是要测试Redis,则无需编辑配置文件,但是如果您在生产服务器上使用它,则应确保已针对您的使用对配置进行了优化。 redis.conf文件包含可帮助您在编辑文件时对其进行配置的文档。我们将向您展示如何进入redis.conf文件,然后浏览文件中列出的前五个设置,以使您适应该文件。

这些说明要求将Redis安装在VPS或专用服务器上,并且需要使用SSH对服务器进行root访问。

如何编辑Redis配置文件– redis.conf可以在终端编辑器(如vim)中修改Redis配置文件,并在文件中提供有关其选项的许多文档。我们还将使用的配置文件也可以从Redis获得(我们使用的是4.0版本)。 redis.conf文件使用以下格式:

关键字arguments1 arguments2 ... argumentsN
您的命令将以关键字开头,然后是该设置的配置选项或参数,然后是下一个参数的空格。

redis.conf文件的位置取决于安装方式,但通常,它位于安装Redis的文件夹的根目录下。例如:

root@vps99999 [~] # cd redis-stable
root@vps99999 [~/redis-stable] ls
./ 00-RELEASENOTES CONTRIBUTING deps/ INSTALL MANIFESTO redis.conf runtest-cluster* runtest-sentinel* src/ utils/
../ BUGS COPYING .gitignore Makefile README.md runtest* runtest-moduleapi* sentinel.conf tests/

您可以看到redis.conf文件位于安装的根目录中。首次登录终端时,使用cd命令更改为安装Redis的文件夹。在这种情况下,文件夹是“redis-stable”。完成操作后,运行编辑器命令以输入文件。如果您使用的是vim,则它将如下所示:

 root@vps99999 [~/redis-stable] vim redis.config

Redis配置设置

您会发现每个配置设置都记录在redis.conf文件中。我们将列出您在文件中看到的内容的副本,并简要描述每个命令。请注意,“#”会使其后的文本成为注释。要使设置生效,您只需要添加一行没有“#”符号的文本即可。我们将在Redis配置文件中列出前20个选项中的前5个,以使您了解设置的期望。请记住,您始终可以在配置文件中查找有关设置的说明以及应如何设置选项的示例。

包括

################################## INCLUDES ###################################
# Include one or more other config files here. This is useful if you
# have a standard template that goes to all Redis servers but also need
# to customize a few per-server settings. Include files can include
# other files, so use this wisely.
#
# Notice option "include" won't be rewritten by command "CONFIG REWRITE"
# from admin or Redis Sentinel. Since Redis always uses the last processed
# line as value of a configuration directive, you'd better put includes
# at the beginning of this file to avoid overwriting config change at runtime.
#
# If instead you are interested in using includes to override configuration
# options, it is better to use include as the last line.
#
# include /path/to/local.conf
# include /path/to/other.conf

正如他们在上面的文本中所建议的那样,请确保所有包含项都应位于配置文件的顶部。如果您以相同的方式管理多个Redis服务器,则此设置特别有用。

模块

################################## MODULES #####################################
# Load modules at startup. If the server is not able to load modules
# it will abort. It is possible to use multiple loadmodule directives.
#
# loadmodule /path/to/my_module.so
# loadmodule /path/to/other_module.so

如果要添加现有模块,则可以转到“ Redis模块”页面。列出的每个模块都有一个指向其相应GitHub存储库的链接。确保阅读您要使用的模块的文档。 Redis模块允许您添加Redis的功能。例如,用于Redis的较流行的模块之一是RediSearch,它允许在Redis上进行全文本搜索。

网络

############################ 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 192.168.1.100 10.0.0.1
# bind 127.0.0.1 ::1
#
# ~~~ WARNING ~~~ If the computer running Redis is directly exposed to the
# internet, binding to all the interfaces is dangerous and will expose the
# instance to everybody on the internet. So by default we uncomment the
# following bind directive, that will force Redis to listen only into
# the IPv4 lookback interface address (this means Redis will be able to
# accept connections only from clients running into the same computer it
# is running).
#
# IF YOU ARE SURE YOU WANT YOUR INSTANCE TO LISTEN TO ALL THE INTERFACES
# JUST COMMENT THE FOLLOWING LINE.
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
bind 127.0.0.1 # Protected mode is a layer of security protection, in order to avoid that
# Redis instances left open on the internet are accessed and exploited.
#
# When protected mode is on and if:
#
# 1) The server is not binding explicitly to a set of addresses using the
# "bind" directive.
# 2) No password is configured.
#
# The server only accepts connections from clients connecting from the
# IPv4 and IPv6 loopback addresses 127.0.0.1 and ::1, and from Unix domain
# sockets.
#
# By default protected mode is enabled. You should disable it only if
# you are sure you want clients from other hosts to connect to Redis
# even if no authentication is configured, nor a specific set of interfaces
# are explicitly listed using the "bind" directive.
protected-mode yes # 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
# TCP listen() backlog.
#
# In high requests-per-second environments you need an high backlog in order
# to avoid slow clients connections issues. Note that the Linux kernel
# will silently truncate it to the value of /proc/sys/net/core/somaxconn so
# make sure to raise both the value of somaxconn and tcp_max_syn_backlog
# in order to get the desired effect.
tcp-backlog 511

# Unix socket.
#
# Specify the path for the Unix socket that will be used to listen for
# incoming connections. There is no default, so Redis will not listen
# on a unix socket when not specified.
#
# unixsocket /tmp/redis.sock
# unixsocketperm 700

# Close the connection after a client is idle for N seconds (0 to disable)
# timeout 0
# TCP keepalive.
#
# If non-zero, use SO_KEEPALIVE to send TCP ACKs to clients in absence
# of communication. This is useful for two reasons:
#
# 1) Detect dead peers.
# 2) Take the connection alive from the point of view of network
# equipment in the middle.
#
# On Linux, the specified value (in seconds) is the period used to send ACKs.
# Note that to close the connection the double of the time is needed.
# On other kernels the period depends on the kernel configuration.
#
# A reasonable value for this option is 300 seconds, which is the new
# Redis default starting with Redis 3.2.1.
tcp-keepalive 300

Redis配置文件的network部分包含许多Redis使用的网络连接选项。在这里您可以看到一些未注释掉的实时命令:绑定127.0.0.1,端口6379和tcp-keepalive300。如果您不熟悉任何网络设置,我们强烈建议您与主机的技术团队联系。

通用

################################# GENERAL ##################################### 
# By default Redis does not run as a daemon. Use 'yes' if you need it.
# Note that Redis will write a pid file in /var/run/redis.pid when daemonized.
daemonize no # If you run Redis from upstart or systemd, Redis can interact with your
# supervision tree. Options:
# supervised no - no supervision interaction
# supervised upstart - signal upstart by putting Redis into SIGSTOP mode
# supervised systemd - signal systemd by writing READY=1 to $NOTIFY_SOCKET
# supervised auto - detect upstart or systemd method based on
# UPSTART_JOB or NOTIFY_SOCKET environment variables
# Note: these supervision methods only signal "process is ready."
# They do not enable continuous liveness pings back to your supervisor.
supervised no # If a pid file is specified, Redis writes it where specified at startup
# and removes it at exit.
#
# When the server runs non daemonized, no pid file is created if none is
# specified in the configuration. When the server is daemonized, the pid file
# is used even if not specified, defaulting to "/var/run/redis.pid".
#
# Creating a pid file is best effort: if Redis is not able to create it
# nothing bad happens, the server will start and run normally.
pidfile /var/run/redis_6379.pid

# Specify the server verbosity level.
# This can be one of:
# debug (a lot of information, useful for development/testing)
# verbose (many rarely useful info, but not a mess like the debug level)
# notice (moderately verbose, what you want in production probably)
# warning (only very important / critical messages are logged)
loglevel notice

# Specify the log file name. Also the empty string can be used to force
# Redis to log on the standard output. Note that if you use standard
# output for logging but daemonize, logs will be sent to /dev/null
logfile ""

# To enable logging to the system logger, just set 'syslog-enabled' to yes,
# and optionally update the other syslog parameters to suit your needs.
# syslog-enabled no

# Specify the syslog identity.
# syslog-ident redis

# Specify the syslog facility. Must be USER or between LOCAL0-LOCAL7.
# syslog-facility local0

# Set the number of databases. The default database is DB 0, you can select
# a different one on a per-connection basis using SELECT <dbid> where
# dbid is a number between 0 and 'databases'-1
databases 16 # By default Redis shows an ASCII art logo only when started to log to the
# standard output and if the standard output is a TTY. Basically this means
# that normally a logo is displayed only in interactive sessions.
#
# However it is possible to force the pre-4.0 behavior and always show a
# ASCII art logo in startup logs by setting the following option to yes.
always-show-logo yes

常规部分包含许多选项,包括能够作为“守护程序”或后台进程运行。您还可以在此处设置日志文件的位置,日志文件的详细程度以及影响您的Redis服务器的许多其他设置。

快照

################################ 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

# By default Redis will stop accepting writes if RDB snapshots are enabled
# (at least one save point) and the latest background save failed.
# This will make the user aware (in a hard way) that data is not persisting
# on disk properly, otherwise chances are that no one will notice and some
# disaster will happen.
#
# If the background saving process will start working again Redis will
# automatically allow writes again.
#
# However if you have setup your proper monitoring of the Redis server
# and persistence, you may want to disable this feature so that Redis will
# continue to work as usual even if there are problems with disk,
# permissions, and so forth.
stop-writes-on-bgsave-error yes

# Compress string objects using LZF when dump .rdb databases?
# For default that's set to 'yes' as it's almost always a win.
# If you want to save some CPU in the saving child set it to 'no' but
# the dataset will likely be bigger if you have compressible values or keys.
rdbcompression yes

# Since version 5 of RDB a CRC64 checksum is placed at the end of the file.
# This makes the format more resistant to corruption but there is a performance
# hit to pay (around 10%) when saving and loading RDB files, so you can disable it
# for maximum performances.
#
# RDB files created with checksum disabled have a checksum of zero that will
# tell the loading code to skip the check.
rdbchecksum yes

# 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 ./

 

 

 
Redis维护

mysql技巧

 

这是某种分布式数据管理问题,这是分布式数据管理以及DDD和微服务领域中的一个热门话题。 第一件事是您现有的方法无法保证两个数据库之间的一致性,因为您不能在两个分离的数据库之间执行2PC(两个短语提交)。从Sagas到Event Sourcing,可以找到许多模式,您可以检查一下它们,但是我想说长话,并尝试提供一些实用的东西。尝试将订单的日志存储在mysql DB的单独表中,然后将日志插入try短语内的mysql DB中。因为mysql本身处理这两个动作,所以它是原子的。 然后编写一个脚本来定期处理日志以更新redis数据并插入扣除数据(可能带有重试策略)或反向顺序,以防万一失败之前存储在mysql中。

 

 

心跳和基于时间的事件日志

这是一种常见的模式,它使用数字时间戳来对ZSET中的成员进行排名。我将在节点控制台中显示它,以说明可选参数的完成方式。

> var r = require('redis').createClient();
          // and I'll define these utility functions just for this example
> function now() { return (new Date()).getTime() / 1000 }
> function print(err, results) { console.log(JSON.stringify(results, null, 2)) }

每当有人登录我的网站时,我都会在“ last-login” zset中记录他们。我将模拟一些登录,如下所示:

> r.zadd('last-login', now(), 'lloyd');
> r.zadd('last-login', now(), 'jparsons');
> r.zadd('last-login', now(), 'zarter');
> r.zadd('last-login', now(), 'lloyd'); // he logged in again! w00t!

这是zset现在包含的内容:

> r.zrange('last-login', 0, -1, print); // remember, I defined 'print' above
["jparsons", "zcarter", "lloyd"]

由于这是一个集合,因此lloyd仅显示一次,并且具有更新的登录时间戳.ZRANGE按照分数的顺序从起始偏移量到结束偏移量为您提供zset中的所有内容。 (从前面开始为0,从结尾开始为-1。)您可以看到,分数按从小到大的顺序排序。要获取最新消息,可以使用ZREVRANGE:

> r.zrevrange('last-login', 0, -1, print);
["lloyd", "zcarter", "jparsons"]

要查看分数,请使用可选的WITHSCORES参数。通常,可选参数的名称在节点函数调用中以字符串形式给出。

> r.zrevrange('last-login', 0, -1, 'WITHSCORES', print);
["lloyd", "1339627441.115",
"zcarter", "1339627437.7579999",
"jparsons", "1339627432.928"]

太棒了除了按元素在ZSET中的排名来获取元素外,您还可以按分数来获取它们。例如,要查看最近一个小时内登录的每个人,可以执行以下操作:

> var an_hour_ago = now() - (60 * 60);
> r.zrevrangebyscore('last-login', an_hour_ago, Infinity, print);

有两种获取最后登录者的方法:

> r.zrevrange('last-login', 0, 0, print);
["lloyd"]
> r.zrevrangebyscore('last-login', Infinity, 0, 'WITHSCORES', 'LIMIT', 0, 1, print);
["lloyd", "1339627441.115"]
 
友情链接
版权所有 Copyright(c)2004-2021 锐英源软件
公司注册号:410105000449586 豫ICP备08007559号 最佳分辨率 1024*768
地址:郑州大学北校区院(文化路97号院)内