图文详解Windows下使用Redis缓存工具的方法
一、简介
redis是一个key-value存储系统。和memcached类似,它支持存储的value类型相对更多,包括string(字符串)、list(链表)、set(集合)和zset(有序集合)。
这些数据类型都支持push/pop、add/remove及取交集并集和差集及更丰富的操作,而且这些操作都是原子性的。在此基础上,redis支持各种不同方式的排序。与memcached一样,为了保证效率,数据都是缓存在内存中。区别的是redis会周期性的把更新的数据写入磁盘或者把修改操作写入追加的记录文件,并且在此基础上实现了master-slave(主从)同步。
redis 是一个高性能的key-value数据库。 redis的出现,很大程度补偿了memcached这类key/value存储的不足,在部 分场合可以对关系数据库起到很好的补充作用。
二、下载redis
redis 官网 :http://redis.io/
下载页面:http://redis.io/download
官方文档:http://redis.io/documentation
windows 版本下载:https://github.com/dmajkic/redis/downloads
三、环境搭建
1. 放到磁盘里面。
2.根据操作系统 进入相应的目录 ,启动redis服务端 redis-server.exe redis.conf
3.根据操作系统 进入相应的目录 ,启动redis客户端。
4. 测试redis缓存机制。
redis-cli.exe -h 127.0.0.1 -p 6379 set keytest valuestest get keytest
5. 效果如下:
6. 测试调换顺序调用的实例。
这个应用可以用在验证码的校验用以及缓存。
第一个号码 18276487300 发送了一个验证码”1234“,然后存到key-values 里面。
第二个号码 18276487301 发送了一个验证码”2345“,然后存到key-values 里面。
但是第二个验证码先进行验证,所以会先通过18276487301 来获取验证码。
这样就防止了一些验证码不知道对应哪个手机号码了。
后面会根据java配置到项目中应用。
四、redis.conf 配置文件
根据操作系统 进入相应的目录 ,会看到一个配置文件redis.conf。
配置文件的原文如下:
# redis configuration file example # note on units: when memory size is needed, it is possible to specifiy # it in the usual form of 1k 5gb 4m and so forth: # # 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 1gb are all the same. # 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 # when running daemonized, redis writes a pid file in /var/run/redis.pid by # default. you can specify a custom pid file location here. pidfile /var/run/redis.pid # accept connections on the specified port, default is 6379. # if port 0 is specified redis will not listen on a tcp socket. port 6379 # if you want you can bind a single interface, if the bind option is not # specified all the interfaces will listen for incoming connections. # # bind 127.0.0.1 # 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 755 # close the connection after a client is idle for n seconds (0 to disable) timeout 0 # set server verbosity to 'debug' # it 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 verbose # specify the log file name. also 'stdout' 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 stdout # 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 ################################ 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 at all commenting all the "save" lines. save 900 1 save 300 10 save 60 10000 # 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 # 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. # # also the append only file will be created inside this directory. # # note that you must specify a directory here, not a file name. dir ./ ################################# replication ################################# # master-slave replication. use slaveof to make a redis instance a copy of # another redis server. note that the configuration is local to the slave # so for example it is possible to configure the slave to save the db with a # different interval, or to listen to another port, and so on. # # slaveof <masterip> <masterport> # if the master is password protected (using the "requirepass" configuration # directive below) it is possible to tell the slave to authenticate before # starting the replication synchronization process, otherwise the master will # refuse the slave request. # # masterauth <master-password> # when a slave lost the connection with the master, or when the replication # is still in progress, the slave can act in 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 data 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 of commands # but to info and slaveof. # slave-serve-stale-data yes # slaves send pings to server in a predefined interval. it's possible to change # this interval with the repl_ping_slave_period option. the default value is 10 # seconds. # # repl-ping-slave-period 10 # the following option sets a timeout for both bulk transfer i/o timeout and # master data or ping response timeout. the default value is 60 seconds. # # it is important to make sure that this value is greater than the value # specified for repl-ping-slave-period otherwise a timeout will be detected # every time there is low traffic between the master and the slave. # # repl-timeout 60 ################################## security ################################### # require clients to issue auth <password> before processing any other # commands. this might be useful in environments in which you do not trust # others with access to the host running redis-server. # # this should stay commented out for backward compatibility and because most # people do not need auth (e.g. they run their own servers). # # warning: since redis is pretty fast an outside user can try up to # 150k passwords per second against a good box. this means that you should # use a very strong password otherwise it will be very easy to break. # # requirepass foobared # command renaming. # # it is possilbe to change the name of dangerous commands in a shared # environment. for instance the config command may be renamed into something # of hard to guess so that it will be still available for internal-use # tools but not available for general clients. # # example: # # rename-command config b840fc02d524045429941cc15f59e41cb7be6c52 # # it is also possilbe to completely kill a command renaming it into # an empty string: # # rename-command config "" ################################### limits #################################### # set the max number of connected clients at the same time. by default there # is no limit, and it's up to the number of file descriptors the redis process # is able to open. the special value '0' means no limits. # once the limit is reached redis will close all the new connections sending # an error 'max number of clients reached'. # # maxclients 128 # don't use more memory than the specified amount of bytes. # when the memory limit is reached redis will try to remove keys with an # expire set. it will try to start freeing keys that are going to expire # in little time and preserve keys with a longer time to live. # redis will also try to remove objects from free lists if possible. # # if all this fails, redis will start to reply with errors to commands # that will use more memory, like set, lpush, and so on, and will continue # to reply to most read-only commands like get. # # warning: maxmemory can be a good idea mainly if you want to use redis as a # 'state' server or cache, not as a real db. when redis is used as a real # database the memory usage will grow over the weeks, it will be obvious if # it is going to use too much memory in the long run, and you'll have the time # to upgrade. with maxmemory after the limit is reached you'll start to get # errors for write operations, and this may even lead to db inconsistency. # # maxmemory <bytes> # maxmemory policy: how redis will select what to remove when maxmemory # is reached? you can select among five behavior: # # volatile-lru -> remove the key with an expire set using an lru algorithm # allkeys-lru -> remove any key accordingly to the lru algorithm # volatile-random -> remove a random key with an expire set # allkeys->random -> remove a random key, any key # volatile-ttl -> remove the key with the nearest expire time (minor ttl) # noeviction -> don't expire at all, just return an error on write operations # # note: with all the kind of policies, redis will return an error on write # operations, when there are not suitable keys for eviction. # # at the date of writing this 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 volatile-lru # lru and minimal ttl algorithms are not precise algorithms but approximated # algorithms (in order to save memory), so you can select as well the sample # size to check. for instance for default redis will check three keys and # pick the one that was used less recently, you can change the sample size # using the following configuration directive. # # maxmemory-samples 3 ############################## append only mode ############################### # by default redis asynchronously dumps the dataset on disk. if you can live # with the idea that the latest records will be lost if something like a crash # happens this is the preferred way to run redis. if instead you care a lot # about your data and don't want to that a single record can get lost you should # enable the append only mode: when this mode is enabled redis will append # every write operation received in the file appendonly.aof. this file will # be read on startup in order to rebuild the full dataset in memory. # # note that you can have both the async dumps and the append only file if you # like (you have to comment the "save" statements above to disable the dumps). # still if append only mode is enabled redis will load the data from the # log file at startup ignoring the dump.rdb file. # # important: check the bgrewriteaof to check how to rewrite the append # log file in background when it gets too big. appendonly no # the name of the append only file (default: "appendonly.aof") # appendfilename appendonly.aof # the fsync() call tells the operating system to actually write data on disk # instead to wait for more data in the output buffer. some os will really flush # data on disk, some other os will just try to do it asap. # # redis supports three different modes: # # no: don't fsync, just let the os flush the data when it wants. faster. # always: fsync after every write to the append only log . slow, safest. # everysec: fsync only if one second passed since the last fsync. compromise. # # the default is "everysec" that's usually the right compromise between # speed and data safety. it's up to you to understand if you can relax this to # "no" that will will let the operating system flush the output buffer when # it wants, for better performances (but if you can live with the idea of # some data loss consider the default persistence mode that's snapshotting), # or on the contrary, use "always" that's very slow but a bit safer than # everysec. # # if unsure, use "everysec". # appendfsync always appendfsync everysec # appendfsync no # when the aof fsync policy is set to always or everysec, and a background # saving process (a background save or aof log 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 fsync in a different thread will block # our synchronous write(2) call. # # in order to mitigate this problem it's possible to use the following option # that will prevent fsync() from being called in the main process while a # bgsave or bgrewriteaof is in progress. # # this means that while another child is saving the durability of redis is # the same as "appendfsync none", that in pratical terms means that it is # possible to lost up to 30 seconds of log in 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 pick from the point of view of durability. no-appendfsync-on-rewrite no # automatic rewrite of the append only file. # redis is able to automatically rewrite the log file implicitly calling # bgrewriteaof when the aof log size will growth by the specified percentage. # # this is how it works: redis remembers the size of the aof file after the # latest rewrite (or if no rewrite happened since the restart, the size of # the aof at startup is used). # # this base size is compared to the current size. if the current size is # bigger than the specified percentage, the rewrite is triggered. also # you need to specify a minimal size for the aof file to be rewritten, this # is useful to avoid rewriting the aof file even if the percentage increase # is reached but it is still pretty small. # # specify a precentage of zero in order to disable the automatic aof # rewrite feature. auto-aof-rewrite-percentage 100 auto-aof-rewrite-min-size 64mb ################################## slow log ################################### # the redis slow log is a system to log queries that exceeded a specified # execution time. the execution time does not include the i/o operations # like talking with the client, sending the reply and so forth, # but just the time needed to actually execute the command (this is the only # stage of command execution where the thread is blocked and can not serve # other requests in the meantime). # # you can configure the slow log with two parameters: one tells redis # what is the execution time, in microseconds, to exceed in order for the # command to get logged, and the other parameter is the length of the # slow log. when a new command is logged the oldest one is removed from the # queue of logged commands. # the following time is expressed in microseconds, so 1000000 is equivalent # to one second. note that a negative number disables the slow log, while # a value of zero forces the logging of every command. slowlog-log-slower-than 10000 # there is no limit to this length. just be aware that it will consume memory. # you can reclaim memory used by the slow log with slowlog reset. slowlog-max-len 1024 ################################ virtual memory ############################### ### warning! virtual memory is deprecated in redis 2.4 ### the use of virtual memory is strongly discouraged. ### warning! virtual memory is deprecated in redis 2.4 ### the use of virtual memory is strongly discouraged. # virtual memory allows redis to work with datasets bigger than the actual # amount of ram needed to hold the whole dataset in memory. # in order to do so very used keys are taken in memory while the other keys # are swapped into a swap file, similarly to what operating systems do # with memory pages. # # to enable vm just set 'vm-enabled' to yes, and set the following three # vm parameters accordingly to your needs. vm-enabled no # vm-enabled yes # this is the path of the redis swap file. as you can guess, swap files # can't be shared by different redis instances, so make sure to use a swap # file for every redis process you are running. redis will complain if the # swap file is already in use. # # the best kind of storage for the redis swap file (that's accessed at random) # is a solid state disk (ssd). # # *** warning *** if you are using a shared hosting the default of putting # the swap file under /tmp is not secure. create a dir with access granted # only to redis user and configure redis to create the swap file there. vm-swap-file /tmp/redis.swap # vm-max-memory configures the vm to use at max the specified amount of # ram. everything that deos not fit will be swapped on disk *if* possible, that # is, if there is still enough contiguous space in the swap file. # # with vm-max-memory 0 the system will swap everything it can. not a good # default, just specify the max amount of ram you can in bytes, but it's # better to leave some margin. for instance specify an amount of ram # that's more or less between 60 and 80% of your free ram. vm-max-memory 0 # redis swap files is split into pages. an object can be saved using multiple # contiguous pages, but pages can't be shared between different objects. # so if your page is too big, small objects swapped out on disk will waste # a lot of space. if you page is too small, there is less space in the swap # file (assuming you configured the same number of total swap file pages). # # if you use a lot of small objects, use a page size of 64 or 32 bytes. # if you use a lot of big objects, use a bigger page size. # if unsure, use the default :) vm-page-size 32 # number of total memory pages in the swap file. # given that the page table (a bitmap of free/used pages) is taken in memory, # every 8 pages on disk will consume 1 byte of ram. # # the total swap size is vm-page-size * vm-pages # # with the default of 32-bytes memory pages and 134217728 pages redis will # use a 4 gb swap file, that will use 16 mb of ram for the page table. # # it's better to use the smallest acceptable value for your application, # but the default is large in order to work in most conditions. vm-pages 134217728 # max number of vm i/o threads running at the same time. # this threads are used to read/write data from/to swap file, since they # also encode and decode objects from disk to memory or the reverse, a bigger # number of threads can help with big objects even if they can't help with # i/o itself as the physical device may not be able to couple with many # reads/writes operations at the same time. # # the special value of 0 turn off threaded i/o and enables the blocking # virtual memory implementation. vm-max-threads 4 ############################### advanced config ############################### # hashes are encoded in a special way (much more memory efficient) when they # have at max a given numer of elements, and the biggest element does not # exceed a given threshold. you can configure this limits with the following # configuration directives. hash-max-zipmap-entries 512 hash-max-zipmap-value 64 # similarly to hashes, small lists are also encoded in a special way in order # to save a lot of space. the special representation is only used when # you are under the following limits: list-max-ziplist-entries 512 list-max-ziplist-value 64 # sets have a special encoding in just one case: when a set is composed # of just strings that happens to be integers in radix 10 in the range # of 64 bit signed integers. # the following configuration setting sets the limit in the size of the # set in order to use this special memory saving encoding. set-max-intset-entries 512 # similarly to hashes and lists, sorted sets are also specially encoded in # order to save a lot of space. this encoding is only used when the length and # elements of a sorted set are below the following limits: zset-max-ziplist-entries 128 zset-max-ziplist-value 64 # active rehashing uses 1 millisecond every 100 milliseconds of cpu time in # order to help rehashing the main redis hash table (the one mapping top-level # keys to values). the hash table implementation redis uses (see dict.c) # performs a lazy rehashing: the more operation you run into an hash table # that is rhashing, the more rehashing "steps" are performed, so if the # server is idle the rehashing is never complete and some more memory is used # by the hash table. # # the default is to use this millisecond 10 times every second in order to # active rehashing the main dictionaries, freeing memory when possible. # # if unsure: # use "activerehashing no" if you have hard latency requirements and it is # not a good thing in your environment that redis can reply form time to time # to queries with 2 milliseconds delay. # # use "activerehashing yes" if you don't have such hard requirements but # want to free memory asap when possible. activerehashing yes ################################## includes ################################### # include one or more other config files here. this is useful if you # have a standard template that goes to all redis server but also need # to customize a few per-server settings. include files can include # other files, so use this wisely. # # include /path/to/local.conf # include /path/to/other.conf
解析过的配置文件:
#是否以后台守护进程运行,默认为no, 取值yes, no daemonize no #pid文件存放路径 pidfile /var/run/redis.pid #配置redis端口,默认6379 port 6379 #绑定ip。默认绑定所有本机ip,一般用在服务器多ip下,可以只监听内网服务器ip,保证服务安全 bind 127.0.0.1 #sock文件 unixsocket /tmp/redis.sock #客户端超时时间,单位秒 timeout 300 #log级别,支持四个级别,debug,notice,verbose,warning loglevel verbose #log文件路径 logfile #log输出到标准设备,logs不写文件,输出到空设备,/deb/null logfile stdout #保存快照的频率,在多长时间内执行一定数量的写操作时,保存快照的频率,可以设置多个条件。如果都注释掉,则不做内存数据持久化。如果只是把redis只用作cache,不开启持久化功能 save <seconds> <changes> save 900 1 #是否使用压缩 rdbcompression #快照数据库名称 dbfilename #数据库存放路径 dir #redis主从 做法 在从上填上主的ip和端口号 主上不用做任何设置 slaveof <masterip> <masterport> #主库服务器口令,如果主服务器未打开requirepass,则不需要此项 masterauth <master-password> #在master服务器挂掉或者同步失败时,从服务器是否继续提供服务 slave-serve-stale-data yes #设置redis服务密码,如果开启,则客户端连接时需要 -a 指定密码,否则操作会提示无权限 requirepass foobared #命令改名,相当于linux alias,可以用改功能屏蔽一些危险命令 rename-command #最大连接数;0 表示不限制 maxclients 128 #最大使用内存(分配的内存),推荐生产环境下做相应调整,我们用的是只用来做高速缓存,限制2g。默认情况下,redis会占用可用的所有内存 maxmemory <bytes> #过期策略,提供六种策略 maxmemory-policy volatile-lru volatile-lru //删除过期和lru 的key(默认值) allkeys-lru //删除lru算法的key volatile-random //随机删除即将过期key allkeys->random //随机删除 volatile-ttl //删除即将过期的 noeviction //永不过期,返回错误 #是否开启appendonlylog,开启的话每次写操作会记一条log。相当于mysql的binlog;不同的是,每次redis启动都会读此文件构建完整数据。即使删除rdb文件,数据也是安全的 appendonly #日志文件的名称,默认appendonly.aof appendfilename appendonly.aof #异步写append file 的策略。类似mysql事物log写方式。三种 appendfsync appendfsync always //同步,每次写都要flush到磁盘,安全,速度慢。 appendfsync everysec //每秒写(默认值,推荐值)同mysql appendfsync no //交给操作系统去做flush的动作 #虚拟内存开关 vm-enabled no #swap文件,不同redis swap文件不能共享。而且生产环境下,不建议放在tmp目录 vm-swap-file /tmp/redis.swap #vm大小限制。0:不限制,建议60-80% 可用内存大小 vm-max-memory 0 #根据缓存内容大小调整,默认32字节 vm-page-size 32 #page数。每 8 page,会占用1字节内存。vm-page-size * vm-pages 等于 swap 文件大小 vm-pages 134217728 #vm 最大io线程数。注意: 0 标志禁止使用vm vm-max-threads 4
以上就是windows环境下使用redis缓存工具的图文详细方法,希望对大家的学习有所帮助。
上一篇: Redis数据库的使用场景介绍(避免误用Redis)
下一篇: Redis的使用模式之计数器模式实例
推荐阅读
-
windows8下IE10浏览器同步收藏夹的方法图文详解
-
在Windows下使用ffmpeg分割视频的图文方法
-
Windows 64位下安装Redis和可视化工具Redis Desktop Manager的图文教程
-
laravel使用Redis实现网站缓存读取的方法详解
-
windows8下IE10浏览器同步收藏夹的方法图文详解
-
Windows下安装Redis及使用Python操作Redis的方法
-
GitLab使用外部提供的Redis缓存数据库的方法详解
-
图文详解Windows下使用Redis缓存工具的方法
-
在Windows下使用ffmpeg分割视频的图文方法
-
Redis缓存服务器在Windows下的使用