首页 文章资讯内容详情

redis.conf配置详细解析

2026-06-01 2 花语

本文内容纲要:

-

#redis配置文件示例 #当你需要为某个配置项指定内存大小的时候,必须要带上单位, #通常的格式就是1k5gb4m等酱紫: # #1k=>1000bytes #1kb=>1024bytes #1m=>1000000bytes #1mb=>1024*1024bytes #1g=>1000000000bytes #1gb=>1024*1024*1024bytes # #单位是不区分大小写的,你写1K5GB4M也行 ##################################INCLUDES################################### #假如说你有一个可用于所有的redisserver的标准配置模板, #但针对某些server又需要一些个性化的设置, #你可以使用include来包含一些其他的配置文件,这对你来说是非常有用的。 # #但是要注意哦,include是不能被configrewrite命令改写的 #由于redis总是以最后的加工线作为一个配置指令值,所以你最好是把include放在这个文件的最前面, #以避免在运行时覆盖配置的改变,相反,你就把它放在后面(外国人真啰嗦)。 # #include/path/to/local.conf #include/path/to/other.conf ################################常用##################################### #默认情况下redis不是作为守护进程运行的,如果你想让它在后台运行,你就把它改成yes。 #当redis作为守护进程运行的时候,它会写一个pid到/var/run/redis.pid文件里面。 daemonizeno #当redis作为守护进程运行的时候,它会把pid默认写到/var/run/redis.pid文件里面, #但是你可以在这里自己制定它的文件位置。 pidfile/var/run/redis.pid #监听端口号,默认为6379,如果你设为0,redis将不在socket上监听任何客户端连接。 port6379 #TCP监听的最大容纳数量 # #在高并发的环境下,你需要把这个值调高以避免客户端连接缓慢的问题。 #Linux内核会一声不响的把这个值缩小成/proc/sys/net/core/somaxconn对应的值, #所以你要修改这两个值才能达到你的预期。 tcp-backlog511 #默认情况下,redis在server上所有有效的网络接口上监听客户端连接。 #你如果只想让它在一个网络接口上监听,那你就绑定一个IP或者多个IP。 # #示例,多个IP用空格隔开: # #bind192.168.1.10010.0.0.1 #bind127.0.0.1 #指定unixsocket的路径。 # #unixsocket/tmp/redis.sock #unixsocketperm755 #指定在一个client空闲多少秒之后关闭连接(0就是不管它) timeout0 #tcp心跳包。 # #如果设置为非零,则在与客户端缺乏通讯的时候使用SO_KEEPALIVE发送tcpacks给客户端。 #这个之所有有用,主要由两个原因: # #1)防止死的peers #2)Taketheconnectionalivefromthepointofviewofnetwork #equipmentinthemiddle. # #OnLinux,thespecifiedvalue(inseconds)istheperiodusedtosendACKs. #Notethattoclosetheconnectionthedoubleofthetimeisneeded. #Onotherkernelstheperioddependsonthekernelconfiguration. # #Areasonablevalueforthisoptionis60seconds. #推荐一个合理的值就是60秒 tcp-keepalive0 #定义日志级别。 #可以是下面的这些值: #debug(适用于开发或测试阶段) #verbose(manyrarelyusefulinfo,butnotamesslikethedebuglevel) #notice(适用于生产环境) #warning(仅仅一些重要的消息被记录) loglevelnotice #指定日志文件的位置 logfile"" #要想把日志记录到系统日志,就把它改成yes, #也可以可选择性的更新其他的syslog参数以达到你的要求 #syslog-enabledno #设置syslog的identity。 #syslog-identredis #设置syslog的facility,必须是USER或者是LOCAL0-LOCAL7之间的值。 #syslog-facilitylocal0 #设置数据库的数目。 #默认数据库是DB0,你可以在每个连接上使用select<dbid>命令选择一个不同的数据库, #但是dbid必须是一个介于0到databasees-1之间的值 databases16 ################################快照################################ # #存DB到磁盘: # #格式:save<间隔时间(秒)><写入次数> # #根据给定的时间间隔和写入次数将数据保存到磁盘 # #下面的例子的意思是: #900秒内如果至少有1个key的值变化,则保存 #300秒内如果至少有10个key的值变化,则保存 #60秒内如果至少有10000个key的值变化,则保存 # #注意:你可以注释掉所有的save行来停用保存功能。 #也可以直接一个空字符串来实现停用: #save"" save9001 save30010 save6010000 #默认情况下,如果redis最后一次的后台保存失败,redis将停止接受写操作, #这样以一种强硬的方式让用户知道数据不能正确的持久化到磁盘, #否则就会没人注意到灾难的发生。 # #如果后台保存进程重新启动工作了,redis也将自动的允许写操作。 # #然而你要是安装了靠谱的监控,你可能不希望redis这样做,那你就改成no好了。 stop-writes-on-bgsave-erroryes #是否在dump.rdb数据库的时候使用LZF压缩字符串 #默认都设为yes #如果你希望保存子进程节省点cpu,你就设置它为no, #不过这个数据集可能就会比较大 rdbcompressionyes #是否校验rdb文件 rdbchecksumyes #设置dump的文件位置 dbfilenamedump.rdb #工作目录 #例如上面的dbfilename只指定了文件名, #但是它会写入到这个目录下。这个配置项一定是个目录,而不能是文件名。 dir./ #################################主从复制################################# #主从复制。使用slaveof来让一个redis实例成为另一个reids实例的副本。 #注意这个只需要在slave上配置。 # #slaveof<masterip><masterport> #如果master需要密码认证,就在这里设置 #masterauth<master-password> #当一个slave与master失去联系,或者复制正在进行的时候, #slave可能会有两种表现: # #1)如果为yes,slave仍然会应答客户端请求,但返回的数据可能是过时, #或者数据可能是空的在第一次同步的时候 # #2)如果为no,在你执行除了infohesalveof之外的其他命令时, #slave都将返回一个"SYNCwithmasterinprogress"的错误, # slave-serve-stale-datayes #你可以配置一个slave实体是否接受写入操作。 #通过写入操作来存储一些短暂的数据对于一个slave实例来说可能是有用的, #因为相对从master重新同步数而言,据数据写入到slave会更容易被删除。 #但是如果客户端因为一个错误的配置写入,也可能会导致一些问题。 # #从redis2.6版起,默认slaves都是只读的。 # #Note:readonlyslavesarenotdesignedtobeexposedtountrustedclients #ontheinternet.Itsjustaprotectionlayeragainstmisuseoftheinstance. #Stillareadonlyslaveexportsbydefaultalltheadministrativecommands #suchasCONFIG,DEBUG,andsoforth.Toalimitedextentyoucanimprove #securityofreadonlyslavesusingrename-commandtoshadowallthe #administrative/dangerouscommands. #注意:只读的slaves没有被设计成在internet上暴露给不受信任的客户端。 #它仅仅是一个针对误用实例的一个保护层。 slave-read-onlyyes #Slaves在一个预定义的时间间隔内发送ping命令到server。 #你可以改变这个时间间隔。默认为10秒。 # #repl-ping-slave-period10 #Thefollowingoptionsetsthereplicationtimeoutfor: #设置主从复制过期时间 # #1)BulktransferI/OduringSYNC,fromthepointofviewofslave. #2)Mastertimeoutfromthepointofviewofslaves(data,pings). #3)Slavetimeoutfromthepointofviewofmasters(REPLCONFACKpings). # #Itisimportanttomakesurethatthisvalueisgreaterthanthevalue #specifiedforrepl-ping-slave-periodotherwiseatimeoutwillbedetected #everytimethereislowtrafficbetweenthemasterandtheslave. #这个值一定要比repl-ping-slave-period大 # #repl-timeout60 #DisableTCP_NODELAYontheslavesocketafterSYNC? # #Ifyouselect"yes"RediswilluseasmallernumberofTCPpacketsand #lessbandwidthtosenddatatoslaves.Butthiscanaddadelayfor #thedatatoappearontheslaveside,upto40millisecondswith #Linuxkernelsusingadefaultconfiguration. # #Ifyouselect"no"thedelayfordatatoappearontheslavesidewill #bereducedbutmorebandwidthwillbeusedforreplication. # #Bydefaultweoptimizeforlowlatency,butinveryhightrafficconditions #orwhenthemasterandslavesaremanyhopsaway,turningthisto"yes"may #beagoodidea. repl-disable-tcp-nodelayno #设置主从复制容量大小。这个backlog是一个用来在slaves被断开连接时 #存放slave数据的buffer,所以当一个slave想要重新连接,通常不希望全部重新同步, #只是部分同步就够了,仅仅传递slave在断开连接时丢失的这部分数据。 # #Thebiggestthereplicationbacklog,thelongerthetimetheslavecanbe #disconnectedandlaterbeabletoperformapartialresynchronization. #这个值越大,salve可以断开连接的时间就越长。 # #Thebacklogisonlyallocatedoncethereisatleastaslaveconnected. # #repl-backlog-size1mb #Afteramasterhasnolongerconnectedslavesforsometime,thebacklog #willbefreed.Thefollowingoptionconfigurestheamountofsecondsthat #needtoelapse,startingfromthetimethelastslavedisconnected,for #thebacklogbuffertobefreed. #在某些时候,master不再连接slaves,backlog将被释放。 # #Avalueof0meanstoneverreleasethebacklog. #如果设置为0,意味着绝不释放backlog。 # #repl-backlog-ttl3600 #当master不能正常工作的时候,RedisSentinel会从slaves中选出一个新的master, #这个值越小,就越会被优先选中,但是如果是0,那是意味着这个slave不可能被选中。 # #默认优先级为100。 slave-priority100 #Itispossibleforamastertostopacceptingwritesiftherearelessthan #Nslavesconnected,havingalaglessorequalthanMseconds. # #TheNslavesneedtobein"online"state. # #Thelaginseconds,thatmustbe<=thespecifiedvalue,iscalculatedfrom #thelastpingreceivedfromtheslave,thatisusuallysenteverysecond. # #ThisoptiondoesnotGUARANTEESthatNreplicaswillacceptthewrite,but #willlimitthewindowofexposureforlostwritesincasenotenoughslaves #areavailable,tothespecifiednumberofseconds. # #Forexampletorequireatleast3slaveswithalag<=10secondsuse: # #min-slaves-to-write3 #min-slaves-max-lag10 # #Settingoneortheotherto0disablesthefeature. # #Bydefaultmin-slaves-to-writeissetto0(featuredisabled)and #min-slaves-max-lagissetto10. ##################################安全################################### #RequireclientstoissueAUTH<PASSWORD>beforeprocessinganyother #commands.Thismightbeusefulinenvironmentsinwhichyoudonottrust #otherswithaccesstothehostrunningredis-server. # #Thisshouldstaycommentedoutforbackwardcompatibilityandbecausemost #peopledonotneedauth(e.g.theyruntheirownservers). # #Warning:sinceRedisisprettyfastanoutsideusercantryupto #150kpasswordspersecondagainstagoodbox.Thismeansthatyoushould #useaverystrongpasswordotherwiseitwillbeveryeasytobreak. # #设置认证密码 #requirepassfoobared #Commandrenaming. # #Itispossibletochangethenameofdangerouscommandsinashared #environment.ForinstancetheCONFIGcommandmayberenamedintosomething #hardtoguesssothatitwillstillbeavailableforinternal-usetools #butnotavailableforgeneralclients. # #Example: # #rename-commandCONFIGb840fc02d524045429941cc15f59e41cb7be6c52 # #Itisalsopossibletocompletelykillacommandbyrenamingitinto #anemptystring: # #rename-commandCONFIG"" # #Pleasenotethatchangingthenameofcommandsthatareloggedintothe #AOFfileortransmittedtoslavesmaycauseproblems. ###################################限制#################################### #Setthemaxnumberofconnectedclientsatthesametime.Bydefault #thislimitissetto10000clients,howeveriftheRedisserverisnot #abletoconfiguretheprocessfilelimittoallowforthespecifiedlimit #themaxnumberofallowedclientsissettothecurrentfilelimit #minus32(asRedisreservesafewfiledescriptorsforinternaluses). # #一旦达到最大限制,redis将关闭所有的新连接 #并发送一个‘maxnumberofclientsreached’的错误。 # #maxclients10000 #如果你设置了这个值,当缓存的数据容量达到这个值,redis将根据你选择的 #eviction策略来移除一些keys。 # #如果redis不能根据策略移除keys,或者是策略被设置为‘noeviction’, #redis将开始响应错误给命令,如set,lpush等等, #并继续响应只读的命令,如get # #ThisoptionisusuallyusefulwhenusingRedisasanLRUcache,ortoset #ahardmemorylimitforaninstance(usingthenoevictionpolicy). # #WARNING:Ifyouhaveslavesattachedtoaninstancewithmaxmemoryon, #thesizeoftheoutputbuffersneededtofeedtheslavesaresubtracted #fromtheusedmemorycount,sothatnetworkproblems/resyncswill #nottriggeraloopwherekeysareevicted,andinturntheoutput #bufferofslavesisfullwithDELsofkeysevictedtriggeringthedeletion #ofmorekeys,andsoforthuntilthedatabaseiscompletelyemptied. # #Inshort...ifyouhaveslavesattacheditissuggestedthatyousetalower #limitformaxmemorysothatthereissomefreeRAMonthesystemforslave #outputbuffers(butthisisnotneededifthepolicyisnoeviction). # #最大使用内存 #maxmemory<bytes> #最大内存策略,你有5个选择。 # #volatile-lru->removethekeywithanexpiresetusinganLRUalgorithm #volatile-lru->使用LRU算法移除包含过期设置的key。 #allkeys-lru->removeanykeyaccordinglytotheLRUalgorithm #allkeys-lru->根据LRU算法移除所有的key。 #volatile-random->removearandomkeywithanexpireset #allkeys-random->removearandomkey,anykey #volatile-ttl->removethekeywiththenearestexpiretime(minorTTL) #noeviction->dontexpireatall,justreturnanerroronwriteoperations #noeviction->不让任何key过期,只是给写入操作返回一个错误 # #Note:withanyoftheabovepolicies,Rediswillreturnanerroronwrite #operations,whentherearenotsuitablekeysforeviction. # #Atthedateofwritingthiscommandsare:setsetnxsetexappend #incrdecrrpushlpushrpushxlpushxlinsertlsetrpoplpushsadd #sintersinterstoresunionsunionstoresdiffsdiffstorezaddzincrby #zunionstorezinterstorehsethsetnxhmsethincrbyincrbydecrby #getsetmsetmsetnxexecsort # #Thedefaultis: # #maxmemory-policynoeviction #LRUandminimalTTLalgorithmsarenotprecisealgorithmsbutapproximated #algorithms(inordertosavememory),soyoucantuneitforspeedor #accuracy.FordefaultRediswillcheckfivekeysandpicktheonethatwas #usedlessrecently,youcanchangethesamplesizeusingthefollowing #configurationdirective. # #Thedefaultof5producesgoodenoughresults.10Approximatesveryclosely #trueLRUbutcostsabitmoreCPU.3isveryfastbutnotveryaccurate. # #maxmemory-samples5 ##############################APPENDONLYMODE############################### #BydefaultRedisasynchronouslydumpsthedatasetondisk.Thismodeis #goodenoughinmanyapplications,butanissuewiththeRedisprocessor #apoweroutagemayresultintoafewminutesofwriteslost(dependingon #theconfiguredsavepoints). # #TheAppendOnlyFileisanalternativepersistencemodethatprovides #muchbetterdurability.Forinstanceusingthedefaultdatafsyncpolicy #(seelaterintheconfigfile)Rediscanlosejustonesecondofwritesina #dramaticeventlikeaserverpoweroutage,orasinglewriteifsomething #wrongwiththeRedisprocessitselfhappens,buttheoperatingsystemis #stillrunningcorrectly. # #AOFandRDBpersistencecanbeenabledatthesametimewithoutproblems. #IftheAOFisenabledonstartupRediswillloadtheAOF,thatisthefile #withthebetterdurabilityguarantees. # #Pleasecheckhttp://redis.io/topics/persistenceformoreinformation. appendonlyno #Thenameoftheappendonlyfile(default:"appendonly.aof") appendfilename"appendonly.aof" #Thefsync()calltellstheOperatingSystemtoactuallywritedataondisk #insteadtowaitformoredataintheoutputbuffer.SomeOSwillreallyflush #dataondisk,someotherOSwilljusttrytodoitASAP. # #Redissupportsthreedifferentmodes: # #no:dontfsync,justlettheOSflushthedatawhenitwants.Faster. #always:fsyncaftereverywritetotheappendonlylog.Slow,Safest. #everysec:fsynconlyonetimeeverysecond.Compromise. # #Thedefaultis"everysec",asthatsusuallytherightcompromisebetween #speedanddatasafety.Itsuptoyoutounderstandifyoucanrelaxthisto #"no"thatwilllettheoperatingsystemflushtheoutputbufferwhen #itwants,forbetterperformances(butifyoucanlivewiththeideaof #somedatalossconsiderthedefaultpersistencemodethatssnapshotting), #oronthecontrary,use"always"thatsveryslowbutabitsaferthan #everysec. # #Moredetailspleasecheckthefollowingarticle: #http://antirez.com/post/redis-persistence-demystified.html # #Ifunsure,use"everysec". #appendfsyncalways appendfsynceverysec #appendfsyncno #WhentheAOFfsyncpolicyissettoalwaysoreverysec,andabackground #savingprocess(abackgroundsaveorAOFlogbackgroundrewriting)is #performingalotofI/Oagainstthedisk,insomeLinuxconfigurations #Redismayblocktoolongonthefsync()call.Notethatthereisnofixfor #thiscurrently,asevenperformingfsyncinadifferentthreadwillblock #oursynchronouswrite(2)call. # #Inordertomitigatethisproblemitspossibletousethefollowingoption #thatwillpreventfsync()frombeingcalledinthemainprocesswhilea #BGSAVEorBGREWRITEAOFisinprogress. # #Thismeansthatwhileanotherchildissaving,thedurabilityofRedisis #thesameas"appendfsyncnone".Inpracticalterms,thismeansthatitis #possibletoloseupto30secondsoflogintheworstscenario(withthe #defaultLinuxsettings). # #Ifyouhavelatencyproblemsturnthisto"yes".Otherwiseleaveitas #"no"thatisthesafestpickfromthepointofviewofdurability. no-appendfsync-on-rewriteno #Automaticrewriteoftheappendonlyfile. #Redisisabletoautomaticallyrewritethelogfileimplicitlycalling #BGREWRITEAOFwhentheAOFlogsizegrowsbythespecifiedpercentage. # #Thisishowitworks:RedisremembersthesizeoftheAOFfileafterthe #latestrewrite(ifnorewritehashappenedsincetherestart,thesizeof #theAOFatstartupisused). # #Thisbasesizeiscomparedtothecurrentsize.Ifthecurrentsizeis #biggerthanthespecifiedpercentage,therewriteistriggered.Also #youneedtospecifyaminimalsizefortheAOFfiletoberewritten,this #isusefultoavoidrewritingtheAOFfileevenifthepercentageincrease #isreachedbutitisstillprettysmall. # #SpecifyapercentageofzeroinordertodisabletheautomaticAOF #rewritefeature. auto-aof-rewrite-percentage100 auto-aof-rewrite-min-size64mb ################################LUASCRIPTING############################### #MaxexecutiontimeofaLuascriptinmilliseconds. # #IfthemaximumexecutiontimeisreachedRediswilllogthatascriptis #stillinexecutionafterthemaximumallowedtimeandwillstartto #replytoquerieswithanerror. # #Whenalongrunningscriptexceedthemaximumexecutiontimeonlythe #SCRIPTKILLandSHUTDOWNNOSAVEcommandsareavailable.Thefirstcanbe #usedtostopascriptthatdidnotyetcalledwritecommands.Thesecond #istheonlywaytoshutdowntheserverinthecaseawritecommandswas #alreadyissuebythescriptbuttheuserdontwanttowaitforthenatural #terminationofthescript. # #Setitto0oranegativevalueforunlimitedexecutionwithoutwarnings. lua-time-limit5000 ################################REDIS集群############################### # #启用或停用集群 #cluster-enabledyes #Everyclusternodehasaclusterconfigurationfile.Thisfileisnot #intendedtobeeditedbyhand.ItiscreatedandupdatedbyRedisnodes. #EveryRedisClusternoderequiresadifferentclusterconfigurationfile. #Makesurethatinstancesrunninginthesamesystemdoesnothave #overlappingclusterconfigurationfilenames. # #cluster-config-filenodes-6379.conf #Clusternodetimeoutistheamountofmillisecondsanodemustbeunreachable #forittobeconsideredinfailurestate. #Mostotherinternaltimelimitsaremultipleofthenodetimeout. # #cluster-node-timeout15000 #Aslaveofafailingmasterwillavoidtostartafailoverifitsdata #lookstooold. # #Thereisnosimplewayforaslavetoactuallyhaveaexactmeasureof #its"dataage",sothefollowingtwochecksareperformed: # #1)Iftherearemultipleslavesabletofailover,theyexchangemessages #inordertotrytogiveanadvantagetotheslavewiththebest #replicationoffset(moredatafromthemasterprocessed). #Slaveswilltrytogettheirrankbyoffset,andapplytothestart #ofthefailoveradelayproportionaltotheirrank. # #2)Everysingleslavecomputesthetimeofthelastinteractionwith #itsmaster.Thiscanbethelastpingorcommandreceived(ifthemaster #isstillinthe"connected"state),orthetimethatelapsedsincethe #disconnectionwiththemaster(ifthereplicationlinkiscurrentlydown). #Ifthelastinteractionistooold,theslavewillnottrytofailover #atall. # #Thepoint"2"canbetunedbyuser.Specificallyaslavewillnotperform #thefailoverif,sincethelastinteractionwiththemaster,thetime #elapsedisgreaterthan: # #(node-timeout*slave-validity-factor)+repl-ping-slave-period # #Soforexampleifnode-timeoutis30seconds,andtheslave-validity-factor #is10,andassumingadefaultrepl-ping-slave-periodof10seconds,the #slavewillnottrytofailoverifitwasnotabletotalkwiththemaster #forlongerthan310seconds. # #Alargeslave-validity-factormayallowslaveswithtooolddatatofailover #amaster,whileatoosmallvaluemaypreventtheclusterfrombeingableto #electaslaveatall. # #Formaximumavailability,itispossibletosettheslave-validity-factor #toavalueof0,whichmeans,thatslaveswillalwaystrytofailoverthe #masterregardlessofthelasttimetheyinteractedwiththemaster. #(Howevertheyllalwaystrytoapplyadelayproportionaltotheir #offsetrank). # #Zeroistheonlyvalueabletoguaranteethatwhenallthepartitionsheal #theclusterwillalwaysbeabletocontinue. # #cluster-slave-validity-factor10 #Clusterslavesareabletomigratetoorphanedmasters,thataremasters #thatareleftwithoutworkingslaves.Thisimprovestheclusterability #toresisttofailuresasotherwiseanorphanedmastercantbefailedover #incaseoffailureifithasnoworkingslaves. # #Slavesmigratetoorphanedmastersonlyiftherearestillatleasta #givennumberofotherworkingslavesfortheiroldmaster.Thisnumber #isthe"migrationbarrier".Amigrationbarrierof1meansthataslave #willmigrateonlyifthereisatleast1otherworkingslaveforitsmaster #andsoforth.Itusuallyreflectsthenumberofslavesyouwantforevery #masterinyourcluster. # #Defaultis1(slavesmigrateonlyiftheirmastersremainwithatleast #oneslave).Todisablemigrationjustsetittoaverylargevalue. #Avalueof0canbesetbutisusefulonlyfordebugginganddangerous #inproduction. # #cluster-migration-barrier1 #Inordertosetupyourclustermakesuretoreadthedocumentation #availableathttp://redis.iowebsite. ##################################SLOWLOG################################### #TheRedisSlowLogisasystemtologqueriesthatexceededaspecified #executiontime.TheexecutiontimedoesnotincludetheI/Ooperations #liketalkingwiththeclient,sendingthereplyandsoforth, #butjustthetimeneededtoactuallyexecutethecommand(thisistheonly #stageofcommandexecutionwherethethreadisblockedandcannotserve #otherrequestsinthemeantime). # #Youcanconfiguretheslowlogwithtwoparameters:onetellsRedis #whatistheexecutiontime,inmicroseconds,toexceedinorderforthe #commandtogetlogged,andtheotherparameteristhelengthofthe #slowlog.Whenanewcommandisloggedtheoldestoneisremovedfromthe #queueofloggedcommands. #Thefollowingtimeisexpressedinmicroseconds,so1000000isequivalent #toonesecond.Notethatanegativenumberdisablestheslowlog,while #avalueofzeroforcestheloggingofeverycommand. slowlog-log-slower-than10000 #Thereisnolimittothislength.Justbeawarethatitwillconsumememory. #YoucanreclaimmemoryusedbytheslowlogwithSLOWLOGRESET. slowlog-max-len128 #############################Eventnotification############################## #RediscannotifyPub/Subclientsabouteventshappeninginthekeyspace. #Thisfeatureisdocumentedathttp://redis.io/topics/keyspace-events # #Forinstanceifkeyspaceeventsnotificationisenabled,andaclient #performsaDELoperationonkey"foo"storedintheDatabase0,two #messageswillbepublishedviaPub/Sub: # #PUBLISH__keyspace@0__:foodel #PUBLISH__keyevent@0__:delfoo # #ItispossibletoselecttheeventsthatRediswillnotifyamongaset #ofclasses.Everyclassisidentifiedbyasinglecharacter: # #KKeyspaceevents,publishedwith__keyspace@<db>__prefix. #EKeyeventevents,publishedwith__keyevent@<db>__prefix. #gGenericcommands(non-typespecific)likeDEL,EXPIRE,RENAME,... #$Stringcommands #lListcommands #sSetcommands #hHashcommands #zSortedsetcommands #xExpiredevents(eventsgeneratedeverytimeakeyexpires) #eEvictedevents(eventsgeneratedwhenakeyisevictedformaxmemory) #AAliasforg$lshzxe,sothatthe"AKE"stringmeansalltheevents. # #The"notify-keyspace-events"takesasargumentastringthatiscomposed #byzeroormultiplecharacters.Theemptystringmeansthatnotifications #aredisabledatall. # #Example:toenablelistandgenericevents,fromthepointofviewofthe #eventname,use: # #notify-keyspace-eventsElg # #Example2:togetthestreamoftheexpiredkeyssubscribingtochannel #name__keyevent@0__:expireduse: # #notify-keyspace-eventsEx # #Bydefaultallnotificationsaredisabledbecausemostusersdontneed #thisfeatureandthefeaturehassomeoverhead.Notethatifyoudont #specifyatleastoneofKorE,noeventswillbedelivered. notify-keyspace-events"" ###############################ADVANCEDCONFIG############################### #Hashesareencodedusingamemoryefficientdatastructurewhentheyhavea #smallnumberofentries,andthebiggestentrydoesnotexceedagiven #threshold.Thesethresholdscanbeconfiguredusingthefollowingdirectives. hash-max-ziplist-entries512 hash-max-ziplist-value64 #Similarlytohashes,smalllistsarealsoencodedinaspecialwayinorder #tosavealotofspace.Thespecialrepresentationisonlyusedwhen #youareunderthefollowinglimits: list-max-ziplist-entries512 list-max-ziplist-value64 #Setshaveaspecialencodinginjustonecase:whenasetiscomposed #ofjuststringsthathappenstobeintegersinradix10intherange #of64bitsignedintegers. #Thefollowingconfigurationsettingsetsthelimitinthesizeofthe #setinordertousethisspecialmemorysavingencoding. set-max-intset-entries512 #Similarlytohashesandlists,sortedsetsarealsospeciallyencodedin #ordertosavealotofspace.Thisencodingisonlyusedwhenthelengthand #elementsofasortedsetarebelowthefollowinglimits: zset-max-ziplist-entries128 zset-max-ziplist-value64 #HyperLogLogsparserepresentationbyteslimit.Thelimitincludesthe #16bytesheader.WhenanHyperLogLogusingthesparserepresentationcrosses #thislimit,itisconvertedintothedenserepresentation. # #Avaluegreaterthan16000istotallyuseless,sinceatthatpointthe #denserepresentationismorememoryefficient. # #Thesuggestedvalueis~3000inordertohavethebenefitsof #thespaceefficientencodingwithoutslowingdowntoomuchPFADD, #whichisO(N)withthesparseencoding.Thevaluecanberaisedto #~10000whenCPUisnotaconcern,butspaceis,andthedatasetis #composedofmanyHyperLogLogswithcardinalityinthe0-15000range. hll-sparse-max-bytes3000 #Activerehashinguses1millisecondevery100millisecondsofCPUtimein #ordertohelprehashingthemainRedishashtable(theonemappingtop-level #keystovalues).ThehashtableimplementationRedisuses(seedict.c) #performsalazyrehashing:themoreoperationyourunintoahashtable #thatisrehashing,themorerehashing"steps"areperformed,soifthe #serverisidletherehashingisnevercompleteandsomemorememoryisused #bythehashtable. # #Thedefaultistousethismillisecond10timeseverysecondinorderto #activerehashingthemaindictionaries,freeingmemorywhenpossible. # #Ifunsure: #use"activerehashingno"ifyouhavehardlatencyrequirementsanditis #notagoodthinginyourenvironmentthatRediscanreplyformtimetotime #toquerieswith2millisecondsdelay. # #use"activerehashingyes"ifyoudonthavesuchhardrequirementsbut #wanttofreememoryasapwhenpossible. activerehashingyes #Theclientoutputbufferlimitscanbeusedtoforcedisconnectionofclients #thatarenotreadingdatafromtheserverfastenoughforsomereason(a #commonreasonisthataPub/Subclientcantconsumemessagesasfastasthe #publishercanproducethem). # #Thelimitcanbesetdifferentlyforthethreedifferentclassesofclients: # #normal->normalclients #slave->slaveclientsandMONITORclients #pubsub->clientssubscribedtoatleastonepubsubchannelorpattern # #Thesyntaxofeveryclient-output-buffer-limitdirectiveisthefollowing: # #client-output-buffer-limit<class><hardlimit><softlimit><softseconds> # #Aclientisimmediatelydisconnectedoncethehardlimitisreached,orif #thesoftlimitisreachedandremainsreachedforthespecifiednumberof #seconds(continuously). #Soforinstanceifthehardlimitis32megabytesandthesoftlimitis #16megabytes/10seconds,theclientwillgetdisconnectedimmediately #ifthesizeoftheoutputbuffersreach32megabytes,butwillalsoget #disconnectediftheclientreaches16megabytesandcontinuouslyovercomes #thelimitfor10seconds. # #Bydefaultnormalclientsarenotlimitedbecausetheydontreceivedata #withoutasking(inapushway),butjustafterarequest,soonly #asynchronousclientsmaycreateascenariowheredataisrequestedfaster #thanitcanread. # #Insteadthereisadefaultlimitforpubsubandslaveclients,since #subscribersandslavesreceivedatainapushfashion. # #Boththehardorthesoftlimitcanbedisabledbysettingthemtozero. client-output-buffer-limitnormal000 client-output-buffer-limitslave256mb64mb60 client-output-buffer-limitpubsub32mb8mb60 #Rediscallsaninternalfunctiontoperformmanybackgroundtasks,like #closingconnectionsofclientsintimeout,purgingexpiredkeysthatare #neverrequested,andsoforth. # #Notalltasksareperformedwiththesamefrequency,butRedischecksfor #taskstoperformaccordinglytothespecified"hz"value. # #Bydefault"hz"issetto10.RaisingthevaluewillusemoreCPUwhen #Redisisidle,butatthesametimewillmakeRedismoreresponsivewhen #therearemanykeysexpiringatthesametime,andtimeoutsmaybe #handledwithmoreprecision. # #Therangeisbetween1and500,howeveravalueover100isusuallynot #agoodidea.Mostusersshouldusethedefaultof10andraisethisupto #100onlyinenvironmentswhereverylowlatencyisrequired. hz10 #WhenachildrewritestheAOFfile,ifthefollowingoptionisenabled #thefilewillbefsync-edevery32MBofdatagenerated.Thisisuseful #inordertocommitthefiletothediskmoreincrementallyandavoid #biglatencyspikes. aof-rewrite-incremental-fsyncyes

上述配置引用自:http://my.oschina.net/wfire/blog/301147

=========================================>=========================================>=========================================>

=========================================>=========================================>=========================================>

=========================================>=========================================>=========================================>

以前为redis5.0.5的运行参考配置

1.redis-default.conf作为基础配置,供其他配置文件引用

#redis-default.conf #作为基础配置,供其他配置文件引用 #把配置文件注释去掉,去除了RDB备份的Redis配置 bind127.0.0.1 protected-modeyes port6379 tcp-backlog511 timeout0 tcp-keepalive300 daemonizeno supervisedno pidfile/var/run/redis_6379.pid loglevelnotice logfile"" databases16 always-show-logoyes save"" stop-writes-on-bgsave-erroryes rdbcompressionyes rdbchecksumyes dbfilenamedump.rdb dir./ replica-serve-stale-datayes replica-read-onlyyes repl-diskless-syncno repl-diskless-sync-delay5 repl-disable-tcp-nodelayno replica-priority100 lazyfree-lazy-evictionno lazyfree-lazy-expireno lazyfree-lazy-server-delno replica-lazy-flushno appendonlyno appendfilename"appendonly.aof" appendfsynceverysec no-appendfsync-on-rewriteno auto-aof-rewrite-percentage100 auto-aof-rewrite-min-size64mb aof-load-truncatedyes aof-use-rdb-preambleyes lua-time-limit5000 slowlog-log-slower-than10000 slowlog-max-len128 latency-monitor-threshold0 notify-keyspace-events"" hash-max-ziplist-entries512 hash-max-ziplist-value64 list-max-ziplist-size-2 list-compress-depth0 set-max-intset-entries512 zset-max-ziplist-entries128 zset-max-ziplist-value64 hll-sparse-max-bytes3000 stream-node-max-bytes4096 stream-node-max-entries100 activerehashingyes client-output-buffer-limitnormal000 client-output-buffer-limitreplica256mb64mb60 client-output-buffer-limitpubsub32mb8mb60 dynamic-hzyes aof-rewrite-incremental-fsyncyes rdb-save-incremental-fsyncyes

2.单机版配置redis-single.conf

#导入基础配置 include../redis-default.conf #根目录,建议配置成绝对路径,这样下面的file都可以配置成相对路径 dir/home/redishome/redis_6379 #守护方式启动 daemonizeyes #守护方式PID存放路径 pidfilerun/redis_6379.pid #启动端口 port6379 #tcp队列长度(不能超过somaxconn和tcp_max_syn_backlog的值) tcp-backlog4096 #绑定的客户端地址 bind0.0.0.0 #客户端闲置关闭时间,0代表不关闭 timeout300 #检测时间,空闲则关闭 tcp-keepalive60 #日志级别debug/verbose:适用于开发和调试notice:适用于生产模式warning:只打印警告 loglevelnotice #日志文件stdout是标准输出(输出屏幕或者发送给dev/null) #logfile"log/redis_6379.log" logfilestdout #数据库访问密码 requirepassAmhEytQUZjqnRSvo7uWkJaM7Vp2jn3rR #最大连接数0代表不限制 maxclients0 #最大内存限制maxmemorybytes #maxmemory16777216 #开启RDB每60分钟备份一次 save36001 #开启AOF appendonlyyes #AOF文件位置 appendfilename"appendonly.aof" #每秒备份 appendfsynceverysec #开启混合备份模式 aof-use-rdb-preambleyes #混合模式RDB备份时机,默认是文件到达64M即进行重写 auto-aof-rewrite-percentage100 auto-aof-rewrite-min-size128mb #禁用危险命令 rename-commandFLUSHALL"nkGqnnmrnES22sA0KI9KVP18TToAhbwP" rename-commandFLUSHDB"3h0Y2uVnENarfbF8tHtVrP4Q1PUXZnU8" rename-commandKEYS"Rq1iyHHsPfUam9w9XkBQ5mhRERI01YIs" rename-commandCONFIG"9jgj3ETHylbxczuJT6Kp6GSHuNdJB1xd"

3.集群配置在单机版的配置下,增加集群配置

#启用集群模式 cluster-enabledyes #集群启动后存放节点的文件 cluster-config-filenodes_6379.conf #节点连接超时时间 cluster-node-timeout5000 #集群访问密码,一般和数据库访问密码一致 masterauthAmhEytQUZjqnRSvo7uWkJaM7Vp2jn3rR

include../redis-default.conf#根目录,建议配置成绝对路径,这样下面的file都可以配置成相对路径dir/home/redishome/redis_6379#守护方式启动daemonizeyes#守护方式PID存放路径pidfilerun/redis_6379.pid#启动端口port6379#tcp队列长度(不能超过somaxconn和tcp_max_syn_backlog的值)tcp-backlog4096#绑定的客户端地址bind0.0.0.0#客户端闲置关闭时间,0代表不关闭timeout300#检测时间,空闲则关闭tcp-keepalive60#日志级别debug/verbose:适用于开发和调试notice:适用于生产模式warning:只打印警告loglevelnotice#日志文件stdout是标准输出(输出屏幕或者发送给dev/null)#logfile"log/redis_6379.log"logfilestdout#数据库访问密码requirepassAmhEytQUZjqnRSvo7uWkJaM7Vp2jn3rR#最大连接数0代表不限制maxclients0#最大内存限制maxmemorybytes#maxmemory16777216#开启RDB每60分钟备份一次save36001#开启AOFappendonlyyes#AOF文件位置appendfilename"appendonly.aof"#每秒备份appendfsynceverysec#开启混合备份模式aof-use-rdb-preambleyes#混合模式RDB备份时机,默认是文件到达64M即进行重写auto-aof-rewrite-percentage100auto-aof-rewrite-min-size128mb

#禁用危险命令rename-commandFLUSHALL"nkGqnnmrnES22sA0KI9KVP18TToAhbwP"rename-commandFLUSHDB"3h0Y2uVnENarfbF8tHtVrP4Q1PUXZnU8"rename-commandKEYS"Rq1iyHHsPfUam9w9XkBQ5mhRERI01YIs"rename-commandCONFIG"9jgj3ETHylbxczuJT6Kp6GSHuNdJB1xd"

本文内容总结:

原文链接:https://www.cnblogs.com/kreo/p/4423362.html