Redis for Windows

風色年代發表於2015-08-29

來自:http://zhaoshijie.iteye.com/blog/1989970,轉載保留出處。

 

關鍵字:redis for Windows

一、windows下安裝redis

1:首先下載redis:redis-2.0.2.zip (32 bit),解壓。
從下面地址下:http://code.google.com/p/servicestack/wiki/RedisWindowsDownload,看到下面有redis-2.0.2.zip (32 bit),就是他了,下載完成後,解壓到D:\redis-2.0.2.
2:建立redis.conf檔案:
這是一個配置檔案,指定了redis的監聽埠,timeout等。如下面有:port 6379。
把下面內容COPY到一新建檔案中,取名redis.conf,再儲存到redis-2.0.2目錄下:


# Redis configuration file example

# 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 run as a daemon, Redis write 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
port 6379

# If you want you can bind a single interface, if the bind option is not
# specified all the interfaces will listen for connections.
#
# bind 127.0.0.1

# Close the connection after a client is idle for N seconds (0 to disable)
timeout 300

# Set server verbosity to 'debug'
# it can be one of:
# debug (a lot of information, useful for development/testing)
# notice (moderately verbose, what you want in production probably)
# warning (only very important / critical messages are logged)
loglevel debug

# Specify the log file name. Also 'stdout' can be used to force
# the demon 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

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

# For default save/load DB in/from the working directory
# Note that you must specify a directory 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>

################################## 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).
#
# requirepass foobared

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

############################## 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.log. 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.
#
# The name of the append only file is "appendonly.log"
#
# IMPORTANT: Check the BGREWRITEAOF to check how to rewrite the append
# log file in background when it gets too big.

appendonly no

# 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 "always" that's the safer of the options. It's up to you to
# understand if you can relax this to "everysec" that will fsync every second
# or to "no" that will let the operating system flush the output buffer when
# it want, for better performances (but if you can live with the idea of
# some data loss consider the default persistence mode that's snapshotting).

appendfsync always
# appendfsync everysec
# appendfsync no

############################### ADVANCED CONFIG ###############################

# Glue small output buffers together in order to send small replies in a
# single TCP packet. Uses a bit more CPU but most of the times it is a win
# in terms of number of queries per second. Use 'yes' if unsure.
glueoutputbuf yes

# Use object sharing. Can save a lot of memory if you have many common
# string in your dataset, but performs lookups against the shared objects
# pool so it uses more CPU and can be a bit slower. Usually it's a good
# idea.
#
# When object sharing is enabled (shareobjects yes) you can use
# shareobjectspoolsize to control the size of the pool used in order to try
# object sharing. A bigger pool size will lead to better sharing capabilities.
# In general you want this value to be at least the double of the number of
# very common strings you have in your dataset.
#
# WARNING: object sharing is experimental, don't enable this feature
# in production before of Redis 1.0-stable. Still please try this feature in
# your development environment so that we can test it better.
# shareobjects no
# shareobjectspoolsize 1024

3:在cmd下面執行以下命令,指定它使用我們的redis.conf,同時也是啟動,把redis執行起來,這裡指定用redis.conf的配置執行伺服器
D:\redis-2.0.2>redis-server.exe redis.conf

4:開一新DOS視窗cmd.執行以下命令,這是Redis的客戶端程式:
redis-cli.exe -h 172.18.5.1 -p 6379
172.18.5.1是我本機IP地址,埠6379就是上面配置檔案中指定的監聽埠
執行完成後,應該能看到redis啟動了,這時在第一個cmd視窗可以看到連線資訊。
執行一條儲存key value操作
set mystock 300156
再查詢一下
get mystock

=================================

可以完全參考以下地址的資料:

http://hi.baidu.com/zchare/blog/item/bd6034f325d1c65f352acca1.html(very good,安全可以成功)

http://cardyn.iteye.com/blog/794194
http://zhaohaolin.iteye.com/blog/1017561


二、redis配置選項:

指定redis的配置檔案,如沒有指定,則使用預設設定
D:\redis-2.0.0-rc2>redis-server.exe redis.conf

redis.conf配置選項如下
daemonize 是否以後臺程式執行,預設為no
pidfile 如以後臺程式執行,則需指定一個pid,預設為/var/run/redis.pid
bind 繫結主機IP,預設值為127.0.0.1(註釋)
port 監聽埠,預設為6379
timeout 超時時間,預設為300(秒)
loglevel 日誌記錄等級,有4個可選值,debug,verbose(預設值),notice,warning
logfile 日誌記錄方式,預設值為stdout
databases 可用資料庫數,預設值為16,預設資料庫為0
save <seconds> <changes> 指出在多長時間內,有多少次更新操作,就將資料同步到資料檔案。這個可以多個條件配合,比如預設配置檔案中的設定,就設定了三個條件。
save 900 1  900秒(15分鐘)內至少有1個key被改變
save 300 10  300秒(5分鐘)內至少有300個key被改變
save 60 10000  60秒內至少有10000個key被改變
rdbcompression 儲存至本地資料庫時是否壓縮資料,預設為yes
dbfilename 本地資料庫檔名,預設值為dump.rdb
dir 本地資料庫存放路徑,預設值為 ./
slaveof <masterip> <masterport> 當本機為從服務時,設定主服務的IP及埠(註釋)
masterauth <master-password> 當本機為從服務時,設定主服務的連線密碼(註釋)
requirepass 連線密碼(註釋)
maxclients 最大客戶端連線數,預設不限制(註釋)
maxmemory <bytes> 設定最大記憶體,達到最大記憶體設定後,Redis會先嚐試清除已到期或即將到期的Key,當此方法處理後,任到達最大記憶體設定,將無法再進行寫入操作。(註釋)
appendonly 是否在每次更新操作後進行日誌記錄,如果不開啟,可能會在斷電時導致一段時間內的資料丟失。因為redis本身同步資料檔案是按上面save條件來同步的,所以有的資料會在一段時間內只存在於記憶體中。預設值為no
appendfilename 更新日誌檔名,預設值為appendonly.aof(註釋)
appendfsync 更新日誌條件,共有3個可選值。no表示等作業系統進行資料快取同步到磁碟,always表示每次更新操作後手動呼叫fsync()將資料寫到磁碟,everysec表示每秒同步一次(預設值)。
vm-enabled 是否使用虛擬記憶體,預設值為no
vm-swap-file 虛擬記憶體檔案路徑,預設值為/tmp/redis.swap,不可多個Redis例項共享
vm-max-memory 將所有大於vm-max-memory的資料存入虛擬記憶體,無論vm-max-memory設定多小,所有索引資料都是記憶體儲存的(Redis的索引資料就是keys),也就是說,當vm-max-memory設定為0的時候,其實是所有value都存在於磁碟。預設值為0。

Redis官方文件對VM的使用提出了一些建議:
當你的key很小而value很大時,使用VM的效果會比較好.因為這樣節約的記憶體比較大.
當你的key不小時,可以考慮使用一些非常方法將很大的key變成很大的value,比如你可以考慮將key,value組合成一個新的value.
最好使用linux ext3 等對稀疏檔案支援比較好的檔案系統儲存你的swap檔案.
vm-max-threads這個引數,可以設定訪問swap檔案的執行緒數,設定最好不要超過機器的核數.如果設定為0,那麼所有對swap檔案的操作都是序列的.可能會造成比較長時間的延遲,但是對資料完整性有很好的保證.redis-cli.exe:命令列客戶端,測試用
D:\redis-2.0.0-rc2>redis-cli.exe -h 127.0.0.1 -p 6379

三、redis java操作(包括list/Map/刪除/新增/覆蓋/排序等都支援)

    import org.junit.After; 
    import org.junit.Before; 
    import org.junit.Test; 
    import redis.clients.jedis.Jedis; 
    import redis.clients.jedis.JedisPool; 
    import redis.clients.jedis.JedisPoolConfig; 
     
    import javax.sound.midi.Soundbank; 
    import java.util.*; 
     
    /**
     * @author: flychao88
     * Time: 2012.5.7 16:23:15
     */ 
    public class RedisTest { 
        JedisPool pool; 
        Jedis jedis; 
        @Before 
        public void setUp() { 
            pool = new JedisPool(new JedisPoolConfig(), "172.16.100.184"); 
     
            jedis = pool.getResource(); 
            jedis.auth("password"); 
        } 
     
        /**
         * Redis儲存初級的字串
         * CRUD
         */ 
        @Test 
        public void testBasicString(){ 
            //-----新增資料---------- 
            jedis.set("name","minxr");//向key-->name中放入了value-->minxr 
            System.out.println(jedis.get("name"));//執行結果:minxr 
     
            //-----修改資料----------- 
            //1、在原來基礎上修改 
            jedis.append("name","jarorwar");   //很直觀,類似map 將jarorwar append到已經有的value之後 
            System.out.println(jedis.get("name"));//執行結果:minxrjarorwar 
     
            //2、直接覆蓋原來的資料 
            jedis.set("name","閔曉榮"); 
            System.out.println(jedis.get("name"));//執行結果:閔曉榮 
     
            //刪除key對應的記錄 
            jedis.del("name"); 
            System.out.println(jedis.get("name"));//執行結果:null 
     
            /**
             * mset相當於
             * jedis.set("name","minxr");
             * jedis.set("jarorwar","閔曉榮");
             */ 
            jedis.mset("name","minxr","jarorwar","閔曉榮"); 
            System.out.println(jedis.mget("name","jarorwar")); 
     
        } 
     
        /**
         * jedis操作Map
         */ 
        @Test 
        public void testMap(){ 
            Map<String,String> user=new HashMap<String,String>(); 
            user.put("name","minxr"); 
            user.put("pwd","password"); 
            jedis.hmset("user",user); 
            //取出user中的name,執行結果:[minxr]-->注意結果是一個泛型的List 
            //第一個引數是存入redis中map物件的key,後面跟的是放入map中的物件的key,後面的key可以跟多個,是可變引數 
            List<String> rsmap = jedis.hmget("user", "name"); 
            System.out.println(rsmap); 
     
            //刪除map中的某個鍵值 
    //        jedis.hdel("user","pwd"); 
            System.out.println(jedis.hmget("user", "pwd")); //因為刪除了,所以返回的是null 
            System.out.println(jedis.hlen("user")); //返回key為user的鍵中存放的值的個數1 
            System.out.println(jedis.exists("user"));//是否存在key為user的記錄 返回true 
            System.out.println(jedis.hkeys("user"));//返回map物件中的所有key  [pwd, name] 
            System.out.println(jedis.hvals("user"));//返回map物件中的所有value  [minxr, password] 
     
            Iterator<String> iter=jedis.hkeys("user").iterator(); 
            while (iter.hasNext()){ 
                String key = iter.next(); 
                System.out.println(key+":"+jedis.hmget("user",key)); 
            } 
     
        } 
     
        /**
         * jedis操作List
         */ 
        @Test 
        public void testList(){ 
            //開始前,先移除所有的內容 
            jedis.del("java framework"); 
            System.out.println(jedis.lrange("java framework",0,-1)); 
           //先向key java framework中存放三條資料 
           jedis.lpush("java framework","spring"); 
           jedis.lpush("java framework","struts"); 
           jedis.lpush("java framework","hibernate"); 
           //再取出所有資料jedis.lrange是按範圍取出, 
           // 第一個是key,第二個是起始位置,第三個是結束位置,jedis.llen獲取長度 -1表示取得所有 
           System.out.println(jedis.lrange("java framework",0,-1)); 
        } 
     
        /**
         * jedis操作Set
         */ 
        @Test 
        public void testSet(){ 
            //新增 
            jedis.sadd("sname","minxr"); 
            jedis.sadd("sname","jarorwar"); 
            jedis.sadd("sname","閔曉榮"); 
            jedis.sadd("sanme","noname"); 
            //移除noname 
            jedis.srem("sname","noname"); 
            System.out.println(jedis.smembers("sname"));//獲取所有加入的value 
            System.out.println(jedis.sismember("sname", "minxr"));//判斷 minxr 是否是sname集合的元素 
            System.out.println(jedis.srandmember("sname")); 
            System.out.println(jedis.scard("sname"));//返回集合的元素個數 
        } 
     
        @Test 
        public void test() throws InterruptedException { 
            //keys中傳入的可以用萬用字元 
            System.out.println(jedis.keys("*")); //返回當前庫中所有的key  [sose, sanme, name, jarorwar, foo, sname, java framework, user, braand] 
            System.out.println(jedis.keys("*name"));//返回的sname   [sname, name] 
            System.out.println(jedis.del("sanmdde"));//刪除key為sanmdde的物件  刪除成功返回1 刪除失敗(或者不存在)返回 0 
            System.out.println(jedis.ttl("sname"));//返回給定key的有效時間,如果是-1則表示永遠有效 
            jedis.setex("timekey", 10, "min");//通過此方法,可以指定key的存活(有效時間) 時間為秒 
            Thread.sleep(5000);//睡眠5秒後,剩餘時間將為<=5 
            System.out.println(jedis.ttl("timekey"));   //輸出結果為5 
            jedis.setex("timekey", 1, "min");        //設為1後,下面再看剩餘時間就是1了 
            System.out.println(jedis.ttl("timekey"));  //輸出結果為1 
            System.out.println(jedis.exists("key"));//檢查key是否存在 
            System.out.println(jedis.rename("timekey","time")); 
            System.out.println(jedis.get("timekey"));//因為移除,返回為null 
            System.out.println(jedis.get("time")); //因為將timekey 重新命名為time 所以可以取得值 min 
     
            //jedis 排序 
            //注意,此處的rpush和lpush是List的操作。是一個雙向連結串列(但從表現來看的) 
            jedis.del("a");//先清除資料,再加入資料進行測試 
            jedis.rpush("a", "1"); 
            jedis.lpush("a","6"); 
            jedis.lpush("a","3"); 
            jedis.lpush("a","9"); 
            System.out.println(jedis.lrange("a",0,-1));// [9, 3, 6, 1] 
            System.out.println(jedis.sort("a")); //[1, 3, 6, 9]  //輸入排序後結果 
            System.out.println(jedis.lrange("a",0,-1)); 
     
        } 




六、redis和memcached比較

1、memcached多執行緒    redis單執行緒

2、memcached支援簡單的key/value  redis支援最為常用的資料型別主要由五種:String、Hash、List、Set和Sorted Set(最吸引人的就此,而且可以對list排序等)

3、memcached客戶端實現分散式   redis伺服器端實現分散式

4、

>>> 附件下載:


 

>>> 映象下載:

相關文章