zoukankan      html  css  js  c++  java
  • NoSQL介绍

    转自:http://blog.csdn.net/wangmuming/article/details/53188834

    NoSQL,Not Only SQL,是非关系型的数据库。传统的关系数据库不能满足超大规模和高并发的应用。其是以Key-Value的形式存储,不一定遵循传统数据库的一些基本要求,比如SQL标准、ACID属性(Atomicity/ Consistency/Isolation/Durability)、表结构等。主要有以下的特点:非关系型的、分步式的、开源的、水平可扩展的(指能够连接多个软硬件的特性)。

        NoSQL适用场景:

            1)、High performance - 对数据高并发读写

            2)、Huge storage - 对海量数据的高效率存储和访问

            3)、High scalability && HighAvailability - 对数据的高可扩展性和高可用性

    常见的Nosql产品有: RedisHbase,Couchbase,LevelDB,MongoDB,Cassandra等。

    Redis的介绍

    redis是一个Key-Value存储系统。它支持存储的value类型有:string(字符串),list(链表), set(无序集合),zset(sorted set有序集合)和hash(哈希),也可以把redis看成一个数据结构服务器。这些数据类型都支持push/pop、add/remove及取交集、并集和差集运算,Redis支持各种不同方式的排序。数据都是缓存在内存中的,它也可以周期性的把更新的数据写入磁盘或者把修改操作写入追加的记录文件,并实现了master-slave(主从)同步。

             Redis从3.0版本后增加集群的支持(主从式集群),目前最新的版本是3.2.5版本。

    Redis提供的API语言包括C、C++、C#、JavaJavaScript、Lua、Objective-C、Perl、PHPPython、Ruby、Go、Tcl等。

    Redis应用

       Redis有库无表无字段无行列。应用场合:

                  1. 取最新N个数据的操作

                  2. 排行榜应用

                  3. 需要精确设定过期时间的应用

                  4. 自增主键(唯一性)、计数器应用

                  5. unique操作,获取某段时间所有数据排重值

                  6. 实时系统,反垃圾系统

                  7. Pub/Sub构建实时消息系统

                  8. 构建队列系统

                  9. 缓存

                  10. 存储关系数据(点赞、关注等)

                  ……

    Redis的安装

    官网地址

    官网:http://redis.io

    图1:

    下载地址

    http://download.redis.io/releases/redis-3.2.5.tar.gz

    编译源代码

             tar–zxvf redis-3.2.5.tar.gz

      cd redis-3.2.5

     make && make install

    注:完成后,有产生可执行文件:

      redis-server:redis服务器的启动程序

      redis-cli:redis命令行工具,也可为客户端

      redis-benchmark:redis性能测试工具(读写)

      redis-stat:redis状态检测工具(状态参数延迟)

    移动文件,方便运维管理

    mkdir –p /usr/local/redis/bin

    mkdir –p/usr/local/redis/etc

       mv redis-2.4.17/redis.conf/usr/local/redis/etc

    mv redis-clishutdownredis-benchmark redis-stat  redis-cli redis-server /usr/lcoal/redis/bin

    修改redis.conf配置文件信息

    # redis 配置文件示例

    # Redis configuration file example.

    #

    # Note that in order to read theconfiguration file, Redis must be

    # started with the file path as firstargument:

    参考的启动脚本

    # ./redis-server /path/to/redis.conf 

    # Note on units: when memory size isneeded, it is possible to specify

    # it in the usual form of 1k 5GB 4M and soforth:

    #

    # 1k => 1000 bytes

    # 1kb => 1024 bytes

    # 1m => 1000000 bytes

    # 1mb => 1024*1024 bytes

    # 1g => 1000000000 bytes

    # 1gb => 1024*1024*1024 bytes

    #

    # units are case insensitive so 1GB 1Gb 1gBare all the same.

    ################################## INCLUDES###################################

    # Include one or more other config fileshere.  This is useful if you

    # have a standard template that goes to allRedis servers but also need

    # to customize a few per-serversettings.  Include files can include

    # other files, so use this wisely.

    #

    # Notice option "include" won'tbe rewritten by command "CONFIG REWRITE"

    # from admin or Redis Sentinel. Since Redisalways uses the last processed

    # line as value of a configurationdirective, you'd better put includes

    # at the beginning of this file to avoidoverwriting config change at runtime.

    #

    # If instead you are interested in usingincludes to override configuration

    # options, it is better to use include as thelast line.

    #

    # include /path/to/local.conf

    # include /path/to/other.conf

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

    # By default, if no "bind"configuration directive is specified, Redis listens

    # for connections from all the networkinterfaces available on the server.

    # It is possible to listen to just one ormultiple selected interfaces using

    # the "bind" configurationdirective, 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 runningRedis is directly exposed to the

    # internet, binding to all the interfacesis dangerous and will expose the

    # instance to everybody on the internet. Soby default we uncomment the

    # following bind directive, that will forceRedis to listen only into

    # the IPv4 lookback interface address (thismeans Redis will be able to

    # accept connections only from clientsrunning into the same computer it

    # is running).

    #

    # IF YOU ARE SURE YOU WANT YOUR INSTANCE TOLISTEN TO ALL THE INTERFACES

    # JUST COMMENT THE FOLLOWING LINE.

    #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    #指定Redis可接收请求的IP地址,不设置将处理所有请求,建议生产环境中设置

    bind 127.0.0.1

    # Protected mode is a layer of securityprotection, in order to avoid that

    # Redis instances left open on the internetare accessed and exploited.

    #

    # When protected mode is on and if:

    #

    # 1) The server is not binding explicitlyto a set of addresses using the

    #   "bind" directive.

    # 2) No password is configured.

    #

    # The server only accepts connections fromclients connecting from the

    # IPv4 and IPv6 loopback addresses127.0.0.1 and ::1, and from Unix domain

    # sockets.

    #

    # By default protected mode is enabled. Youshould disable it only if

    # you are sure you want clients from otherhosts 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 notlisten on a TCP socket.

    端口

    port 6379

    # TCP listen() backlog.

    #

    # In high requests-per-second environmentsyou 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 ofsomaxconn and tcp_max_syn_backlog

    # in order to get the desired effect.

    tcp-backlog 511

    # Unix socket.

    #

    # Specify the path for the Unix socket thatwill be used to listen for

    # incoming connections. There is nodefault, so Redis will not listen

    # on a unix socket when not specified.

    #

    # unixsocket /tmp/redis.sock

    # unixsocketperm 700

    # Close the connection after a client isidle for N seconds (0 to disable)

    timeout 0

    # TCP keepalive.

    #

    # If non-zero, use SO_KEEPALIVE to send TCPACKs to clients in absence

    # of communication. This is useful for tworeasons:

    #

    # 1) Detect dead peers.

    # 2) Take the connection alive from thepoint of view of network

    #   equipment in the middle.

    #

    # On linux, the specified value (inseconds) is the period used to send ACKs.

    # Note that to close the connection thedouble of the time is needed.

    # On other kernels the period depends onthe kernel configuration.

    #

    # A reasonable value for this option is 300seconds, which is the new

    # Redis default starting with Redis 3.2.1.

    tcp-keepalive 300

    ################################# GENERAL#####################################

    # By default Redis does not run as adaemon. Use 'yes' if you need it.

    # Note that Redis will write a pid file in/var/run/redis.pid when daemonized.

    Redis默认不是以守护进程的方式运行,可以通过该配置项修改,使用yes启用守护进程

    daemonize no

    # If you run Redis from upstart or systemd,Redis can interact with your

    # supervision tree. Options:

    #  supervised no      - nosupervision interaction

    #  supervised upstart - signal upstart by putting Redis into SIGSTOP mode

    #  supervised systemd - signal systemd by writing READY=1 to $NOTIFY_SOCKET

    #  supervised auto    - detectupstart or systemd method based on

    #                        UPSTART_JOB orNOTIFY_SOCKET environment variables

    # Note: these supervision methods onlysignal "process is ready."

    #      They do not enable continuous liveness pings back to your supervisor.

    supervised no

    # If a pid file is specified, Redis writesit where specified at startup

    # and removes it at exit.

    #

    # When the server runs non daemonized, nopid file is created if none is

    # specified in the configuration. When theserver is daemonized, the pid file

    # is used even if not specified, defaultingto "/var/run/redis.pid".

    #

    # Creating a pid file is best effort: ifRedis is not able to create it

    # nothing bad happens, the server willstart and run normally.

    #当 Redis以守护进程的方式运行的时候,Redis默认会把 pid文件放在/var/run/redis.pid

    #可配置到其他地址,当运行多个 redis服务时,需要指定不同的 pid文件和端口

    pidfile /var/run/redis_6379.pid

    # Specify the server verbosity level.

    # This can be one of:

    # debug (a lot of information, useful fordevelopment/testing)

    # verbose (many rarely useful info, but nota mess like the debug level)

    # notice (moderately verbose, what you wantin production probably)

    # warning (only very important / criticalmessages are logged)

    日志记录等级,上面提供了4个可选值

    loglevel notice

    # Specify the log file name. Also the emptystring can be used to force

    # Redis to log on the standard output. Notethat if you use standard

    # output for logging but daemonize, logswill be sent to /dev/null

    #配置 log文件地址,daemonize为yes /dev/null屏蔽日志

    logfile ""

    # To enable logging to the system logger,just set 'syslog-enabled' to yes,

    # and optionally update the other syslogparameters to suit your needs.

    # 要想把日志记录到系统日志,就把它改成 yes,

    # 也可以可选择性的更新其他的syslog参数以达到你的要求

    # syslog-enabled no

    # Specify the syslog identity.

    # 设置 syslog的 identity。

    # syslog-ident redis

    # Specify the syslog facility. Must be USERor between LOCAL0-LOCAL7.

    # 设置 syslog的 facility,必须是 USER或者是 LOCAL0-LOCAL7 之间的值

    # syslog-facility local0

    # Set the number of databases. The defaultdatabase is DB 0, you can select

    # a different one on a per-connection basisusing SELECT <dbid> where

    # dbid is a number between 0 and'databases'-1

    # 设置数据库的数目。

    # 默认数据库是 DB 0,你可以在每个连接上使用 select <dbid>命令选择一个不同的数据库,

    # 但是 dbid必须是一个介于 0到 databasees - 1之间的值

    databases 16

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

    ################################ 快照################################

    #

    # 存 DB到磁盘:

    #

    #   格式:save <间隔时间(秒)> <写入次数>

    #

    #   根据给定的时间间隔和写入次数将数据保存到磁盘

    #

    #   下面的例子的意思是:

    #   900 秒内如果至少有 1个 key的值变化,则保存

    #   300 秒内如果至少有 10个 key的值变化,则保存

    #   60 秒内如果至少有 10000个 key的值变化,则保存

    #

    #   注意:你可以注释掉所有的 save行来停用保存功能。

    #   也可以直接一个空字符串来实现停用:

    #   save ""

    save 900 1

    save 300 10

    save 60 10000

    # By default Redis will stop acceptingwrites if RDB snapshots are enabled

    # (at least one save point) and the latestbackground save failed.

    # This will make the user aware (in a hardway) that data is not persisting

    # on disk properly, otherwise chances arethat no one will notice and some

    # disaster will happen.

    #

    # If the background saving process willstart working again Redis will

    # automatically allow writes again.

    #

    # However if you have setup your propermonitoring of the Redis server

    # and persistence, you may want to disablethis feature so that Redis will

    # continue to work as usual even if thereare problems with disk,

    # permissions, and so forth.

    # 默认情况下,如果 redis最后一次的后台保存失败,redis将停止接受写操作,

    # 这样以一种强硬的方式让用户知道数据不能正确的持久化到磁盘,

    # 否则就会没人注意到灾难的发生。

    #

    # 如果后台保存进程重新启动工作了,redis也将自动的允许写操作。

    #

    # 然而你要是安装了靠谱的监控,你可能不希望 redis这样做,那你就改成 no好了。

    stop-writes-on-bgsave-error yes

    # Compress string objects using LZF whendump .rdb databases?

    # For default that's set to 'yes' as it'salmost always a win.

    # If you want to save some CPU in thesaving child set it to 'no' but

    # the dataset will likely be bigger if youhave compressible values or keys.

    # 是否在 dump .rdb数据库的时候使用 LZF压缩字符串

    # 默认都设为 yes

    # 如果你希望保存子进程节省点 cpu,你就设置它为 no,

    # 不过这个数据集可能就会比较大

    rdbcompression yes

    # Since version 5 of RDB a CRC64 checksumis placed at the end of the file.

    # This makes the format more resistant tocorruption but there is a performance

    # hit to pay (around 10%) when saving andloading RDB files, so you can disable it

    # for maximum performances.

    #

    # RDB files created with checksum disabledhave a checksum of zero that will

    # tell the loading code to skip the check.

    # 加载rdb文件时是否校验rdb文件

    rdbchecksum yes

    # The filename where to dump the DB

    # 设置 dump的文件位置

    dbfilename dump.rdb

    # The working directory.

    #

    # The DB will be written inside thisdirectory, with the filename specified

    # above using the 'dbfilename'configuration directive.

    #

    # The Append Only File will also be createdinside this directory.

    #

    # Note that you must specify a directoryhere, not a file name.

    # 工作目录

    # 例如上面的 dbfilename只指定了文件名,

    # 但是它会写入到这个目录下。这个配置项一定是个目录,而不能是文件名。

    dir ./

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

    # Master-Slave replication. Use slaveof tomake a Redis instance a copy of

    # another Redis server. A few things tounderstand ASAP about Redis replication.

    #

    # 1) Redis replication is asynchronous, butyou 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 apartial 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 thenext

    #   sections of this file) with a sensible value depending on your needs.

    # 3) Replication is automatic and does notneed user intervention. After a

    #   network partition slaves automatically try to reconnect to masters

    #   and resynchronize with them.

    #

    ################################# 主从复制#################################

     

    # 主从复制。使用 slaveof来让一个 redis实例成为另一个reids实例的副本。

    # 注意这个只需要在 slave上配置。

    # slaveof <masterip><masterport>

    # If the master is password protected(using the "requirepass" configuration

    # directive below) it is possible to tellthe slave to authenticate before

    # starting the replication synchronizationprocess, otherwise the master will

    # refuse the slave request.

    #

    # 如果 master需要密码认证,就在这里设置

    # masterauth <master-password>

    # When a slave loses its connection withthe master, or when the replication

    # is still in progress, the slave can actin two different ways:

    #

    # 1) if slave-serve-stale-data is set to'yes' (the default) the slave will

    #   still reply to client requests, possibly with out of date data, or the

    #   data set may just be empty if this is the first synchronization.

    #

    # 2) if slave-serve-stale-data is set to'no' the slave will reply with

    #   an error "SYNC with master in progress" to all the kind ofcommands

    #   but to INFO and SLAVEOF.

    #

    # 当一个 slave与 master失去联系,或者复制正在进行的时候,

    # slave 可能会有两种表现:

    #

    # 1) 如果为 yes,slave仍然会应答客户端请求,但返回的数据可能是过时,

    #    或者数据可能是空的在第一次同步的时候

    #

    # 2) 如果为 no,在你执行除了 info he salveof之外的其他命令时,

    #    slave 都将返回一个 "SYNC withmaster in progress"的错误,

    slave-serve-stale-data yes

    # You can configure a slave instance toaccept writes or not. Writing against

    # a slave instance may be useful to storesome ephemeral data (because data

    # written on a slave will be easily deletedafter resync with the master) but

    # may also cause problems if clients arewriting to it because of a

    # misconfiguration.

    #

    # Since Redis 2.6 by default slaves areread-only.

    #

    # Note: read only slaves are not designedto be exposed to untrusted clients

    # on the internet. It's just a protectionlayer against misuse of the instance.

    # Still a read only slave exports bydefault all the administrative commands

    # such as CONFIG, DEBUG, and so forth. To alimited extent you can improve

    # security of read only slaves using'rename-command' to shadow all the

    # administrative / dangerous commands.

    # 你可以配置一个 slave实体是否接受写入操作。

    # 通过写入操作来存储一些短暂的数据对于一个 slave实例来说可能是有用的,

    # 因为相对从 master重新同步数而言,据数据写入到 slave会更容易被删除。

    # 但是如果客户端因为一个错误的配置写入,也可能会导致一些问题。

    #

    # 从 redis 2.6版起,默认 slaves都是只读的。

    # 注意:只读的 slaves没有被设计成在 internet上暴露给不受信任的客户端。

    # 它仅仅是一个针对误用实例的一个保护层。

    slave-read-only yes

    # Replication SYNC strategy: disk orsocket.

    #

    # -------------------------------------------------------

    # WARNING: DISKLESS REPLICATION ISEXPERIMENTAL CURRENTLY

    #-------------------------------------------------------

    #

    # New slaves and reconnecting slaves thatare not able to continue the replication

    # process just receiving differences, needto do what is called a "full

    # synchronization". An RDB file istransmitted from the master to the slaves.

    # The transmission can happen in twodifferent ways:

    #

    # 1) Disk-backed: The Redis master createsa new process that writes the RDB

    #                 file on disk. Later the fileis transferred by the parent

    #                 process to the slavesincrementally.

    # 2) Diskless: The Redis master creates anew process that directly writes the

    #              RDB file to slave sockets,without touching the disk at all.

    #

    # With disk-backed replication, while theRDB file is generated, more slaves

    # can be queued and served with the RDBfile as soon as the current child producing

    # the RDB file finishes its work. Withdiskless replication instead once

    # the transfer starts, new slaves arrivingwill be queued and a new transfer

    # will start when the current oneterminates.

    #

    # When diskless replication is used, themaster waits a configurable amount of

    # time (in seconds) before starting thetransfer in the hope that multiple slaves

    # will arrive and the transfer can beparallelized.

    #

    # With slow disks and fast (largebandwidth) networks, diskless replication

    # works better.

    repl-diskless-sync no

    # When diskless replication is enabled, itis possible to configure the delay

    # the server waits in order to spawn thechild that transfers the RDB via socket

    # to the slaves.

    #

    # This is important since once the transferstarts, it is not possible to serve

    # new slaves arriving, that will be queuedfor the next RDB transfer, so the server

    # waits a delay in order to let more slavesarrive.

    #

    # The delay is specified in seconds, and bydefault is 5 seconds. To disable

    # it entirely just set it to 0 seconds andthe transfer will start ASAP.

    repl-diskless-sync-delay 5

    # Slaves send PINGs to server in apredefined interval. It's possible to change

    # this interval with therepl_ping_slave_period option. The default value is 10

    # seconds.

    #

    # Slaves 在一个预定义的时间间隔内发送 ping命令到 server。

    # 你可以改变这个时间间隔。默认为 10秒。

    # repl-ping-slave-period 10

    # The following option sets the replicationtimeout for:

    #

    # 设置主从复制过期时间

    # 1) Bulk transfer I/O during SYNC, fromthe point of view of slave.

    # 2) Master timeout from the point of viewof slaves (data, pings).

    # 3) Slave timeout from the point of viewof masters (REPLCONF ACK pings).

    #

    # It is important to make sure that thisvalue is greater than the value

    # specified for repl-ping-slave-periodotherwise a timeout will be detected

    # every time there is low traffic betweenthe master and the slave.

    #这个值一定要比 repl-ping-slave-period大

    # repl-timeout 60

    # Disable TCP_NODELAY on the slave socketafter SYNC?

    #

    # If you select "yes" Redis willuse a smaller number of TCP packets and

    # less bandwidth to send data to slaves.But this can add a delay for

    # the data to appear on the slave side, upto 40 milliseconds with

    # Linux kernels using a defaultconfiguration.

    #

    # If you select "no" the delayfor data to appear on the slave side will

    # be reduced but more bandwidth will beused for replication.

    #

    # By default we optimize for low latency,but in very high traffic conditions

    # or when the master and slaves are manyhops away, turning this to "yes" may

    # be a good idea.

    repl-disable-tcp-nodelay no

    # Set the replication backlog size. Thebacklog is a buffer that accumulates

    # slave data when slaves are disconnectedfor some time, so that when a slave

    # wants to reconnect again, often a fullresync is not needed, but a partial

    # resync is enough, just passing theportion of data the slave missed while

    # disconnected.

    #

    # 设置主从复制容量大小。这个 backlog是一个用来在 slaves被断开连接时

    # 存放 slave数据的 buffer,所以当一个 slave想要重新连接,通常不希望全部重新同步,

    # 只是部分同步就够了,仅仅传递 slave在断开连接时丢失的这部分数据。

    #

    # The bigger the replication backlog, thelonger the time the slave can be

    # disconnected and later be able to performa partial resynchronization.

    #

    # 这个值越大,salve可以断开连接的时间就越长。

    # The backlog is only allocated once thereis at least a slave connected.

    #

    # repl-backlog-size 1mb

    # After a master has no longer connectedslaves for some time, the backlog

    # will be freed. The following optionconfigures the amount of seconds that

    # need to elapse, starting from the timethe last slave disconnected, for

    # the backlog buffer to be freed.

    #

    # 在某些时候,master不再连接 slaves,backlog将被释放。

    # A value of 0 means to never release thebacklog.

    # 如果设置为 0,意味着绝不释放 backlog。

    #

    # repl-backlog-ttl 3600

    # The slave priority is an integer numberpublished by Redis in the INFO output.

    # It is used by Redis Sentinel in order toselect a slave to promote into a

    # master if the master is no longer workingcorrectly.

    #

    # A slave with a low priority number isconsidered better for promotion, so

    # for instance if there are three slaveswith priority 10, 100, 25 Sentinel will

    # pick the one with priority 10, that isthe lowest.

    #

    # However a special priority of 0 marks theslave as not able to perform the

    # role of master, so a slave with priorityof 0 will never be selected by

    # Redis Sentinel for promotion.

    #

    # By default the priority is 100.

    # 当 master不能正常工作的时候,Redis Sentinel会从 slaves 中选出一个新的 master,

    # 这个值越小,就越会被优先选中,但是如果是 0,那是意味着这个 slave不可能被选中。

    #

    # 默认优先级为 100。

    slave-priority 100

    # It is possible for a master to stopaccepting writes if there are less than

    # N slaves connected, having a lag less orequal than M seconds.

    #

    # The N slaves need to be in"online" state.

    #

    # The lag in seconds, that must be <=the specified value, is calculated from

    # the last ping received from the slave,that is usually sent every second.

    #

    # This option does not GUARANTEE that Nreplicas will accept the write, but

    # will limit the window of exposure forlost writes in case not enough slaves

    # are available, to the specified number ofseconds.

    #

    # For example to require at least 3 slaveswith a lag <= 10 seconds use:

    #

    # min-slaves-to-write 3

    # min-slaves-max-lag 10

    #

    # Setting one or the other to 0 disablesthe feature.

    #

    # By default min-slaves-to-write is set to0 (feature disabled) and

    # min-slaves-max-lag is set to 10.

    # A Redis master is able to list theaddress and port of the attached

    # slaves in different ways. For example the"INFO replication" section

    # offers this information, which is used,among other tools, by

    # Redis Sentinel in order to discover slaveinstances.

    # Another place where this info isavailable is in the output of the

    # "ROLE" command of a masteer.

    #

    # The listed IP and address normallyreported by a slave is obtained

    # in the following way:

    #

    #  IP: The address is auto detected by checking the peer address

    #  of the socket used by the slave to connect with the master.

    #

    #  Port: The port is communicated by the slave during the replication

    #  handshake, and is normally the port that the slave is using to

    #  list for connections.

    #

    # However when port forwarding or NetworkAddress Translation (NAT) is

    # used, the slave may be actually reachablevia different IP and port

    # pairs. The following two options can beused by a slave in order to

    # report to its master a specific set of IPand port, so that both INFO

    # and ROLE will report those values.

    #

    # There is no need to use both the optionsif you need to override just

    # the port or the IP address.

    #

    # slave-announce-ip 5.5.5.5

    # slave-announce-port 1234

    ################################## 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 runningredis-server.

    #

    # This should stay commented out forbackward compatibility and because most

    # people do not need auth (e.g. they runtheir own servers).

    #

    # Warning: since Redis is pretty fast anoutside user can try up to

    # 150k passwords per second against a goodbox. This means that you should

    # use a very strong password otherwise itwill be very easy to break.

    #

    # 设置认证密码

    #设置客户端连接后进行任何其他指定前需要使用的密码

    #redis速度相当快,一个外部用户在一秒钟进行150K次密码尝试,需指定强大的密码来防止暴力破解

    # requirepass foobared

    # Command renaming.

    #

    # It is possible to change the name ofdangerous commands in a shared

    # environment. For instance the CONFIGcommand may be renamed into something

    # hard to guess so that it will still beavailable for internal-use tools

    # but not available for general clients.

    #

    # Example:

    #

    # rename-command CONFIGb840fc02d524045429941cc15f59e41cb7be6c52

    #

    # It is also possible to completely kill acommand by renaming it into

    # an empty string:

    #

    # rename-command CONFIG ""

    #

    # Please note that changing the name ofcommands that are logged into the

    # AOF file or transmitted to slaves maycause problems.

    ################################### LIMITS####################################

    ################################### 限制 ####################################

    # Set the max number of connected clientsat the same time. By default

    # this limit is set to 10000 clients,however if the Redis server is not

    # able to configure the process file limitto allow for the specified limit

    # the max number of allowed clients is setto the current file limit

    # minus 32 (as Redis reserves a few filedescriptors for internal uses).

    #

    # Once the limit is reached Redis willclose all the new connections sending

    # an error 'max number of clients reached'.

    #

    # 一旦达到最大限制,redis将关闭所有的新连接

    # 并发送一个‘max number of clients reached’的错误。

    # maxclients 10000

    # Don't use more memory than the specifiedamount of bytes.

    # When the memory limit is reached Rediswill try to remove keys

    # according to the eviction policy selected(see maxmemory-policy).

    #

    # If Redis can't remove keys according tothe policy, or if the policy is

    # set to 'noeviction', Redis will start toreply with errors to commands

    # that would use more memory, like SET,LPUSH, and so on, and will continue

    # to reply to read-only commands like GET.

    #

    # 如果你设置了这个值,当缓存的数据容量达到这个值, redis将根据你选择的

    # eviction 策略来移除一些 keys。

    #

    # 如果 redis不能根据策略移除 keys,或者是策略被设置为‘noeviction’,

    # redis 将开始响应错误给命令,如 set,lpush等等,

    # 并继续响应只读的命令,如 get

    # This option is usually useful when usingRedis as an LRU cache, or to set

    # a hard memory limit for an instance(using the 'noeviction' policy).

    #

    # WARNING: If you have slaves attached toan instance with maxmemory on,

    # the size of the output buffers needed tofeed the slaves are subtracted

    # from the used memory count, so thatnetwork problems / resyncs will

    # not trigger a loop where keys areevicted, and in turn the output

    # buffer of slaves is full with DELs ofkeys evicted triggering the deletion

    # of more keys, and so forth until thedatabase is completely emptied.

    #

    # In short... if you have slaves attachedit is suggested that you set a lower

    # limit for maxmemory so that there is somefree RAM on the system for slave

    # output buffers (but this is not needed ifthe policy is 'noeviction').

    #

    # 最大使用内存

    # maxmemory <bytes>

    # MAXMEMORY POLICY: how Redis will selectwhat to remove when maxmemory

    # is reached. You can select among fivebehaviors:

    #

    # 最大内存策略,你有 5个选择。

    # volatile-lru -> remove the key with anexpire set using an LRU algorithm

    # volatile-lru -> 使用 LRU算法移除包含过期设置的 key。

    # allkeys-lru -> remove any keyaccording to the LRU algorithm

    # allkeys-lru -> 根据 LRU算法移除所有的 key。

    # volatile-random -> remove a random keywith an expire set

    # allkeys-random -> remove a random key,any key

    # volatile-ttl -> remove the key withthe nearest expire time (minor TTL)

    # noeviction -> don't expire at all,just return an error on write operations

    # noeviction -> 不让任何 key过期,只是给写入操作返回一个错误

    #

    # Note: with any of the above policies,Redis will return an error on write

    #      operations, when there are no suitable keys for eviction.

    #

    #      At the date of writing these commands are: set setnx setex append

    #      incr decr rpush lpush rpushx lpushx linsert lset rpoplpush sadd

    #      sinter sinterstore sunion sunionstore sdiff sdiffstore zadd zincrby

    #      zunionstore zinterstore hset hsetnx hmset hincrby incrby decrby

    #      getset mset msetnx exec sort

    #

    # The default is:

    #

    # maxmemory-policy noeviction

    # LRU and minimal TTL algorithms are notprecise algorithms but approximated

    # algorithms (in order to save memory), soyou can tune it for speed or

    # accuracy. For default Redis will checkfive keys and pick the one that was

    # used less recently, you can change thesample size using the following

    # configuration directive.

    #

    # The default of 5 produces good enoughresults. 10 Approximates very closely

    # true LRU but costs a bit more CPU. 3 isvery fast but not very accurate.

    #

    # maxmemory-samples 5

    ############################## APPEND ONLYMODE ###############################

    # By default Redis asynchronously dumps thedataset on disk. This mode is

    # good enough in many applications, but anissue with the Redis process or

    # a power outage may result into a fewminutes of writes lost (depending on

    # the configured save points).

    #

    # The Append Only File is an alternativepersistence mode that provides

    # much better durability. For instanceusing the default data fsync policy

    # (see later in the config file) Redis canlose just one second of writes in a

    # dramatic event like a server poweroutage, or a single write if something

    # wrong with the Redis process itselfhappens, but the operating system is

    # still running correctly.

    #

    # AOF and RDB persistence can be enabled atthe same time without problems.

    # If the AOF is enabled on startup Rediswill load the AOF, that is the file

    # with the better durability guarantees.

    #

    # Please checkhttp://redis.io/topics/persistence for more information.

    #redis 默认每次更新操作后会在后台异步的把数据库镜像备份到磁盘,但该备份非常耗时,且备份不宜太频繁

    #redis 同步数据文件是按上面save条件来同步的

    #如果发生诸如拉闸限电、拔插头等状况,那么将造成比较大范围的数据丢失

    #所以redis提供了另外一种更加高效的数据库备份及灾难恢复方式

    #开启append only模式后,redis将每一次写操作请求都追加到appendonly.aof文件中

    #redis重新启动时,会从该文件恢复出之前的状态。

    #但可能会造成 appendonly.aof文件过大,所以redis支持BGREWRITEAOF指令,对appendonly.aof重新整理

    appendonly no

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

    #更新日志文件名,默认值为appendonly.aof

    appendfilename "appendonly.aof"

    # The fsync() call tells the OperatingSystem to actually write data on disk

    # instead of waiting for more data in theoutput buffer. Some OS will really flush

    # data on disk, some other OS will just tryto do it ASAP.

    #

    # Redis supports three different modes:

    #

    # no: don't fsync, just let the OS flushthe data when it wants. Faster.

    # always: fsync after every write to theappend only log. Slow, Safest.

    # everysec: fsync only one time everysecond. Compromise.

    #

    # The default is "everysec", asthat's usually the right compromise between

    # speed and data safety. It's up to you tounderstand if you can relax this to

    # "no" that will let theoperating system flush the output buffer when

    # it wants, for better performances (but ifyou can live with the idea of

    # some data loss consider the defaultpersistence 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 followingarticle:

    #http://antirez.com/post/redis-persistence-demystified.html

    #

    # If unsure, use "everysec".

    #设置对 appendonly.aof文件进行同步的频率

    #always 表示每次有写操作都进行同步,everysec表示对写操作进行累积,每秒同步一次。

    #no表示等操作系统进行数据缓存同步到磁盘,都进行同步,everysec表示对写操作进行累积,每秒同步一次

    # appendfsync always

    appendfsync everysec

    # appendfsync no

    # When the AOF fsync policy is set toalways or everysec, and a background

    # saving process (a background save or AOFlog background rewriting) is

    # performing a lot of I/O against the disk,in some Linux configurations

    # Redis may block too long on the fsync()call. Note that there is no fix for

    # this currently, as even performing fsyncin a different thread will block

    # our synchronous write(2) call.

    #

    # In order to mitigate this problem it'spossible to use the following option

    # that will prevent fsync() from beingcalled in the main process while a

    # BGSAVE or BGREWRITEAOF is in progress.

    #

    # This means that while another child issaving, the durability of Redis is

    # the same as "appendfsync none".In practical terms, this means that it is

    # possible to lose up to 30 seconds of login the worst scenario (with the

    # default Linux settings).

    #

    # If you have latency problems turn this to"yes". Otherwise leave it as

    # "no" that is the safest pickfrom the point of view of durability.

    #如果该参数设置为no,是最安全的方式,不会丢失数据,但是要忍受阻塞的问题。如果设#置为yes呢?这就相当于将appendfsync设置为no,这说明并没有执行磁盘操作,只是写#入了缓冲区,因此这样并不会造成阻塞(因为没有竞争磁盘),但是如果这个时候redis挂#掉,就会丢失数据。丢失多少数据呢?在linux的操作系统的默认设置下,最多会丢失30s##的数据。

    #因此,如果应用系统无法忍受延迟,而可以容忍少量的数据丢失,则设置为yes。如果应#用系统无法忍受数据丢失,则设置为no

    no-appendfsync-on-rewrite no

    # Automatic rewrite of the append onlyfile.

    # Redis is able to automatically rewritethe log file implicitly calling

    # BGREWRITEAOF when the AOF log size growsby the specified percentage.

    #

    # This is how it works: Redis remembers thesize of the AOF file after the

    # latest rewrite (if no rewrite has happenedsince the restart, the size of

    # the AOF at startup is used).

    #

    # This base size is compared to the currentsize. If the current size is

    # bigger than the specified percentage, therewrite is triggered. Also

    # you need to specify a minimal size forthe AOF file to be rewritten, this

    # is useful to avoid rewriting the AOF fileeven if the percentage increase

    # is reached but it is still pretty small.

    #

    # Specify a percentage of zero in order todisable the automatic AOF

    # rewrite feature.

    auto-aof-rewrite-percentage 100

    auto-aof-rewrite-min-size 64mb

    # An AOF file may be found to be truncatedat the end during the Redis

    # startup process, when the AOF data getsloaded back into memory.

    # This may happen when the system whereRedis is running

    # crashes, especially when an ext4filesystem is mounted without the

    # data=ordered option (however this can'thappen when Redis itself

    # crashes or aborts but the operatingsystem still works correctly).

    #

    # Redis can either exit with an error whenthis happens, or load as much

    # data as possible (the default now) andstart if the AOF file is found

    # to be truncated at the end. The followingoption controls this behavior.

    #

    # If aof-load-truncated is set to yes, atruncated AOF file is loaded and

    # the Redis server starts emitting a log toinform the user of the event.

    # Otherwise if the option is set to no, theserver aborts with an error

    # and refuses to start. When the option isset to no, the user requires

    # to fix the AOF file using the"redis-check-aof" utility before to restart

    # the server.

    #

    # Note that if the AOF file will be foundto be corrupted in the middle

    # the server will still exit with an error.This option only applies when

    # Redis will try to read more data from theAOF file but not enough bytes

    # will be found.

    aof-load-truncated yes

    ################################ LUASCRIPTING ###############################

    # Max execution time of a Lua script inmilliseconds.

    #

    # If the maximum execution time is reachedRedis will log that a script is

    # still in execution after the maximumallowed time and will start to

    # reply to queries with an error.

    #

    # When a long running script exceeds themaximum execution time only the

    # SCRIPT KILL and SHUTDOWN NOSAVE commandsare available. The first can be

    # used to stop a script that did not yetcalled write commands. The second

    # is the only way to shut down the serverin the case a write command was

    # already issued by the script but the userdoesn't want to wait for the natural

    # termination of the script.

    #

    # Set it to 0 or a negative value forunlimited execution without warnings.

    lua-time-limit 5000

    ################################ REDISCLUSTER  ###############################

    #

    ################################ REDIS 集群  ###############################

    #++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    # WARNING EXPERIMENTAL: Redis Cluster isconsidered to be stable code, however

    # in order to mark it as "mature"we need to wait for a non trivial percentage

    # of users to deploy it in production.

    #++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    #

    # Normal Redis instances can't be part of aRedis Cluster; only nodes that are

    # started as cluster nodes can. In order tostart a Redis instance as a

    # cluster node enable the cluster supportuncommenting the following:

    #

    # 启用或停用集群

    # cluster-enabled yes

    # Every cluster node has a clusterconfiguration file. This file is not

    # intended to be edited by hand. It iscreated and updated by Redis nodes.

    # Every Redis Cluster node requires adifferent cluster configuration file.

    # Make sure that instances running in thesame system do not have

    # overlapping cluster configuration filenames.

    #

    # cluster-config-file nodes-6379.conf

    # Cluster node timeout is the amount ofmilliseconds a node must be unreachable

    # for it to be considered in failure state.

    # Most other internal time limits aremultiple of the node timeout.

    #

    # cluster-node-timeout 15000

    # A slave of a failing master will avoid tostart a failover if its data

    # looks too old.

    #

    # There is no simple way for a slave toactually have a exact measure of

    # its "data age", so thefollowing two checks are performed:

    #

    # 1) If there are multiple slaves able tofailover, they exchange messages

    #   in order to try to give an advantage to the slave with the best

    #   replication offset (more data from the master processed).

    #   Slaves will try to get their rank by offset, and apply to the start

    #   of the failover a delay proportional to their rank.

    #

    # 2) Every single slave computes the timeof the last interaction with

    #   its master. This can be the last ping or command received (if the master

    #   is still in the "connected" state), or the time that elapsedsince the

    #   disconnection with the master (if the replication link is currentlydown).

    #   If the last interaction is too old, the slave will not try to failover

    #   at all.

    #

    # The point "2" can be tuned byuser. Specifically a slave will not perform

    # the failover if, since the lastinteraction with the master, the time

    # elapsed is greater than:

    #

    #  (node-timeout * slave-validity-factor) + repl-ping-slave-period

    #

    # So for example if node-timeout is 30seconds, and the slave-validity-factor

    # is 10, and assuming a defaultrepl-ping-slave-period of 10 seconds, the

    # slave will not try to failover if it wasnot able to talk with the master

    # for longer than 310 seconds.

    #

    # A large slave-validity-factor may allowslaves with too old data to failover

    # a master, while a too small value mayprevent the cluster from being able to

    # elect a slave at all.

    #

    # For maximum availability, it is possibleto set the slave-validity-factor

    # to a value of 0, which means, that slaveswill always try to failover the

    # master regardless of the last time theyinteracted with the master.

    # (However they'll always try to apply adelay proportional to their

    # offset rank).

    #

    # Zero is the only value able to guaranteethat when all the partitions heal

    # the cluster will always be able tocontinue.

    #

    # cluster-slave-validity-factor 10

    # Cluster slaves are able to migrate toorphaned masters, that are masters

    # that are left without working slaves.This improves the cluster ability

    # to resist to failures as otherwise anorphaned master can't be failed over

    # in case of failure if it has no workingslaves.

    #

    # Slaves migrate to orphaned masters onlyif there are still at least a

    # given number of other working slaves fortheir old master. This number

    # is the "migration barrier". Amigration barrier of 1 means that a slave

    # will migrate only if there is at least 1other working slave for its master

    # and so forth. It usually reflects thenumber of slaves you want for every

    # master in your cluster.

    #

    # Default is 1 (slaves migrate only iftheir masters remain with at least

    # one slave). To disable migration just setit to a very large value.

    # A value of 0 can be set but is usefulonly for debugging and dangerous

    # in production.

    #

    # cluster-migration-barrier 1

    # By default Redis Cluster nodes stopaccepting queries if they detect there

    # is at least an hash slot uncovered (noavailable node is serving it).

    # This way if the cluster is partially down(for example a range of hash slots

    # are no longer covered) all the clusterbecomes, eventually, unavailable.

    # It automatically returns available assoon as all the slots are covered again.

    #

    # However sometimes you want the subset ofthe cluster which is working,

    # to continue to accept queries for thepart of the key space that is still

    # covered. In order to do so, just set thecluster-require-full-coverage

    # option to no.

    #

    # cluster-require-full-coverage yes

    # In order to setup your cluster make sureto read the documentation

    # available at http://redis.io web site.

    ################################## SLOW LOG###################################

    # The Redis Slow Log is a system to logqueries that exceeded a specified

    # execution time. The execution time doesnot include the I/O operations

    # like talking with the client, sending thereply and so forth,

    # but just the time needed to actuallyexecute the command (this is the only

    # stage of command execution where thethread is blocked and can not serve

    # other requests in the meantime).

    #

    # You can configure the slow log with twoparameters: one tells Redis

    # what is the execution time, inmicroseconds, to exceed in order for the

    # command to get logged, and the otherparameter is the length of the

    # slow log. When a new command is loggedthe oldest one is removed from the

    # queue of logged commands.

    # The following time is expressed inmicroseconds, so 1000000 is equivalent

    # to one second. Note that a negativenumber disables the slow log, while

    # a value of zero forces the logging ofevery command.

    slowlog-log-slower-than 10000

    # There is no limit to this length. Just beaware that it will consume memory.

    # You can reclaim memory used by the slowlog with SLOWLOG RESET.

    slowlog-max-len 128

    ################################ LATENCYMONITOR ##############################

    ################################ 延迟监控 ##############################

    # The Redis latency monitoring subsystemsamples different operations

    # at runtime in order to collect datarelated to possible sources of

    # latency of a Redis instance.

    #

    # redis延迟监控子系统例子与操作系统收集的redis实例相关的数据不同

    # Via the LATENCY command this informationis available to the user that can

    # print graphs and obtain reports.

    #

    # 通过LATENCY命令,可以为用户打印出相关信息的图形和报告

    # The system only logs operations that wereperformed in a time equal or

    # greater than the amount of millisecondsspecified via the

    # latency-monitor-threshold configurationdirective. When its value is set

    # to zero, the latency monitor is turnedoff.

    #

    #这个系统只会记录运行时间超出指定时间值的命令,如果设置为0,这个监控将会被关闭

    # By default latency monitoring is disabledsince it is mostly not needed

    # if you don't have latency issues, andcollecting data has a performance

    # impact, that while very small, can bemeasured under big load. Latency

    # monitoring can easily be enabled atruntime using the command

    # "CONFIG SETlatency-monitor-threshold <milliseconds>" if needed.

    # 默认的情况下,延迟监控是关闭,因为如果你没有延迟的问题大部分情况下不需要

    #并且收集数据的行为会对性能造成影响,虽然这个影响很小可以在大负荷下工作

    #延迟监控可以使用如下命令来打开

    latency-monitor-threshold 0

    ############################# EVENTNOTIFICATION ##############################

    # Redis can notify Pub/Sub clients aboutevents happening in the key space.

    # This feature is documented athttp://redis.io/topics/notifications

    #

    #redis 可以在key空间中采用发布订阅模式来通知事件的发生

    # 这个分支功能参考文档:http://redis.io/topics/notifications

    # For instance if keyspace eventsnotification is enabled, and a client

    # performs a DEL operation on key"foo" stored in the Database 0, two

    # messages will be published via Pub/Sub:

    #

    # PUBLISH __keyspace@0__:foo del

    # PUBLISH __keyevent@0__:del foo

    #

    # It is possible to select the events thatRedis will notify among a set

    # of classes. Every class is identified bya single character:

    #

    # K     Keyspace events, publishedwith __keyspace@<db>__ prefix.

    # E     Keyevent events, publishedwith __keyevent@<db>__ prefix.

    # g     Generic commands (non-typespecific) like DEL, EXPIRE, RENAME, ...

    # $     String commands

    # l     List commands

    # s     Set commands

    # h     Hash commands

    # z     Sorted set commands

    # x     Expired events (events generated every time akey expires)

    # e     Evicted events (eventsgenerated when a key is evicted for maxmemory)

    # A     Alias for g$lshzxe, so thatthe "AKE" string means all the events.

    #

    # The "notify-keyspace-events" takes as argument a string thatis composed

    #  ofzero or multiple characters. The empty string means that notifications

    # are disabled.

    #

    # Example: to enable list and generic events, from the point of view ofthe

    #          event name, use:

    #

    # notify-keyspace-events Elg

    #

    # Example 2: to get the stream of the expired keys subscribing to channel

    #             name __keyevent@0__:expired use:

    #

    # notify-keyspace-events Ex

    #

    #  Bydefault all notifications are disabled because most users don't need

    #默认不启用所有的通知,因为大部分的用户不需要这些功能,

    # this feature and the feature has some overhead. Note that if you don't

    #这些功能会带来一些开销

    # specify at least one of K or E, no events will be delivered.

    #如果你没有指定 K或者 E,没有事件会被传递

    notify-keyspace-events ""

    ############################### ADVANCEDCONFIG ###############################

    # Hashes are encoded using a memoryefficient data structure when they have a

    # small number of entries, and the biggestentry does not exceed a given

    # threshold. These thresholds can beconfigured using the following directives.

    hash-max-ziplist-entries 512

    hash-max-ziplist-value 64

    # Lists are also encoded in a special wayto save a lot of space.

    # The number of entries allowed perinternal list node can be specified

    # as a fixed maximum size or a maximumnumber of elements.

    # For a fixed maximum size, use -5 through-1, meaning:

    # -5: max size: 64 Kb  <-- not recommended for normal workloads

    # -4: max size: 32 Kb  <-- not recommended

    # -3: max size: 16 Kb  <-- probably not recommended

    # -2: max size: 8 Kb   <-- good

    # -1: max size: 4 Kb   <-- good

    # Positive numbers mean store up to_exactly_ that number of elements

    # per list node.

    # The highest performing option is usually-2 (8 Kb size) or -1 (4 Kb size),

    # but if your use case is unique, adjustthe settings as necessary.

    list-max-ziplist-size -2

    # Lists may also be compressed.

    # Compress depth is the number of quicklistziplist nodes from *each* side of

    # the list to *exclude* fromcompression.  The head and tail of thelist

    # are always uncompressed for fast push/popoperations.  Settings are:

    # 0: disable all list compression

    # 1: depth 1 means "don't startcompressing until after 1 node into the list,

    #   going from either the head or tail"

    #   So: [head]->node->node->...->node->[tail]

    #   [head], [tail] will always be uncompressed; inner nodes will compress.

    # 2:[head]->[next]->node->node->...->node->[prev]->[tail]

    #   2 here means: don't compress head or head->next or tail->prev ortail,

    #   but compress all nodes between them.

    # 3:[head]->[next]->[next]->node->node->...->node->[prev]->[prev]->[tail]

    # etc.

    list-compress-depth 0

    # Sets have a special encoding in just onecase: when a set is composed

    # of just strings that happen to beintegers in radix 10 in the range

    # of 64 bit signed integers.

    # The following configuration setting setsthe limit in the size of the

    # set in order to use this special memorysaving encoding.

    #以下配置设置了set的限制大小,当小于这个值的时候将会使用一个更紧凑的数据结构来保存以期减少内存占用

    set-max-intset-entries 512

    # Similarly to hashes and lists, sortedsets are also specially encoded in

    # order to save a lot of space. Thisencoding is only used when the length and

    # elements of a sorted set are below thefollowing limits:

    zset-max-ziplist-entries 128

    zset-max-ziplist-value 64

    # HyperLogLog sparse representation byteslimit. The limit includes the

    # 16 bytes header. When an HyperLogLogusing the sparse representation crosses

    # this limit, it is converted into thedense representation.

    #

    # A value greater than 16000 is totallyuseless, since at that point the

    # dense representation is more memoryefficient.

    #

    # The suggested value is ~ 3000 in order tohave the benefits of

    # the space efficient encoding withoutslowing down too much PFADD,

    # which is O(N) with the sparse encoding.The value can be raised to

    # ~ 10000 when CPU is not a concern, butspace is, and the data set is

    # composed of many HyperLogLogs withcardinality in the 0 - 15000 range.

    hll-sparse-max-bytes 3000

    # Active rehashing uses 1 millisecond every100 milliseconds of CPU time in

    # order to help rehashing the main Redishash table (the one mapping top-level

    # keys to values). The hash tableimplementation Redis uses (see dict.c)

    # performs a lazy rehashing: the moreoperation you run into a hash table

    # that is rehashing, the more rehashing"steps" are performed, so if the

    # server is idle the rehashing is nevercomplete and some more memory is used

    # by the hash table.

    #

    # The default is to use this millisecond 10times every second in order to

    # actively rehash the main dictionaries,freeing memory when possible.

    #

    # If unsure:

    # use "activerehashing no" if youhave hard latency requirements and it is

    # not a good thing in your environment thatRedis can reply from time to time

    # to queries with 2 milliseconds delay.

    #

    # use "activerehashing yes" ifyou don't have such hard requirements but

    # want to free memory asap when possible.

    #是否重置Hash表

    #设置成yes后redis将每100毫秒使用1毫秒CPU时间来对redis的hash表重新hash,可降低内存的使用

    #当使用场景有较为严格的实时性需求,不能接受Redis时不时的对请求有2毫秒的延迟的话,把这项配置为no。

    #如果没有这么严格的实时性要求,可以设置为 yes,以便能够尽可能快的释放内存

    activerehashing yes

    # The client output buffer limits can beused to force disconnection of clients

    # that are not reading data from the serverfast enough for some reason (a

    # common reason is that a Pub/Sub clientcan't consume messages as fast as the

    # publisher can produce them).

    #

    # The limit can be set differently for thethree different classes of clients:

    #

    # normal -> normal clients includingMONITOR clients

    # slave -> slave clients

    # pubsub -> clients subscribed to atleast one pubsub channel or pattern

    #

    # The syntax of everyclient-output-buffer-limit directive is the following:

    #

    # client-output-buffer-limit <class><hard limit> <soft limit> <soft seconds>

    #

    # A client is immediately disconnected oncethe hard limit is reached, or if

    # the soft limit is reached and remainsreached for the specified number of

    # seconds (continuously).

    # So for instance if the hard limit is 32megabytes and the soft limit is

    # 16 megabytes / 10 seconds, the client willget disconnected immediately

    # if the size of the output buffers reach32 megabytes, but will also get

    # disconnected if the client reaches 16megabytes and continuously overcomes

    # the limit for 10 seconds.

    #

    # By default normal clients are not limitedbecause they don't receive data

    # without asking (in a push way), but justafter a request, so only

    # asynchronous clients may create ascenario where data is requested faster

    # than it can read.

    #

    # Instead there is a default limit forpubsub and slave clients, since

    # subscribers and slaves receive data in apush fashion.

    #

    # Both the hard or the soft limit can bedisabled by setting them to zero.

    client-output-buffer-limit normal 0 0 0

    client-output-buffer-limit slave 256mb 64mb60

    client-output-buffer-limit pubsub 32mb 8mb60

    # Redis calls an internal function toperform many background tasks, like

    # closing connections of clients intimeout, purging expired keys that are

    # never requested, and so forth.

    #

    # Not all tasks are performed with the samefrequency, but Redis checks for

    # tasks to perform according to thespecified "hz" value.

    #

    # By default "hz" is set to 10.Raising the value will use more CPU when

    # Redis is idle, but at the same time willmake Redis more responsive when

    # there are many keys expiring at the sametime, and timeouts may be

    # handled with more precision.

    #

    # The range is between 1 and 500, however avalue over 100 is usually not

    # a good idea. Most users should use thedefault of 10 and raise this up to

    # 100 only in environments where very lowlatency is required.

    hz 10

    # When a child rewrites the AOF file, ifthe following option is enabled

    # the file will be fsync-ed every 32 MB ofdata generated. This is useful

    # in order to commit the file to the diskmore incrementally and avoid

    # big latency spikes.

    # 当子进程重写AOF文件的时候,以下选项将会允许等到存在32MB数据的时候才调用强制同步这样可以降低IO上的延迟。

    aof-rewrite-incremental-fsync yes

    这里我们为了简单起见,我们将redis运行模式改为守护进程模式。

     图2:

     

    改为

    daemonize yes

    保存。

    启动redis服务

    /usr/local/redis/bin/redis-server/usr/local/redis/etc/redis.conf

    注:Redis服务端的默认连接端口是6379

     Redis默认不是后台运行,上面我们已经将其改为守护进程模式,即是后台运行模式。

    客户端连接

    /usr/local/redis/bin/redis-cli

    停止Redis

    /usr/local/redis/bin/redis-clishutdown

    或者

    pkill redis-server

    或者

    Kill -9 redis-server启动端口号

    注:redis-server启动端口号查询方式 ps –ef|grep redis-server

    Redis的配置

    主要的配置修改,具体的请参考上面的redis.conf配置文件信息:

    daemonize 如果需要在后台运行,把该项改为yes

                  pidfile 配置多个pid的地址,默认在/var/run/redis.pid

                  bind 绑定ip,设置后只接受自该ip的请求

                  port 监听端口,默认为6379

                  timeout 设置客户端连接时的超时时间,单位为秒

                  loglevel 分为4级,debug、verbose、notice、warning

                  logfile 配置log文件地址

                  databases 设置数据库的个数,默认使用的数据库为0

                  save 设置redis进行数据库镜像的频率,保存快照的频率,第一个*表示多长时间,       第三个*表示执行多少次写操作。在一定时间内执行一定数量的写操作时,自动保存快照。可设置多个条件。

                  rdbcompression 在进行镜像备份时,是否进行压缩

                  dbfilename 镜像备份文件的文件名

                  dir 数据库镜像备份的文件放置路径

                  Slaveof 设置数据库为其他数据库的从数据库

                  Masterauth 主数据库连接需要的密码验证

                  Requirepass 设置登录时需要使用的密码

                  Maxclients 限制同时连接的客户数量

                  Maxmemory 设置redis能够使用的最大内存

                  Appendonly 开启append only模式

                  appendfsync 设置对appendonly.aof文件同步的频率

                  activerehashing 重新hash

    redis数据存储

    redis的存储分为内存存储、磁盘存储(RDB)和log(AOF)文件三部分,配置文件中有三个参数对其进行配置。Redis默认配置是打开了RDB存储方式。

    save secondsupdates,save配置,指出在多长时间内,有多少次更新操作,就将数据同步到数据文件。可多个条件配合,默认配置了三个条件。

    图3:

     

    appendonlyyes/no ,appendonly配置,指出是否在每次更新操作后进行日志记录,如果不开启,可能会在断电时导致一段时间内的数据丢失。因为redis本身同步数据文件是按上面的save条件来同步的,所以有的数据会在一段时间内只存在于内存中。

    appendfsyncno/always/everysec ,appendfsync配置,no表示等操作系统进行数据缓存同步到磁盘,always表示每次更新操作后手动调用fsync()将数据写到磁盘,everysec表示每秒同步一次。

    图4:

  • 相关阅读:
    sql学习2----函数
    网络相关命令
    网络相关概念
    linux学习(2)--指令
    linux学习(1)--基本知识
    Linux学习技巧
    VMware安装Linux
    接口测试
    app测试--DDMS的使用
    app测试--性能测试DDMS
  • 原文地址:https://www.cnblogs.com/xiaohouzai/p/7282816.html
Copyright © 2011-2022 走看看