Intro to Redis


Published on

Presented at BJUG, 5/8/2012 by Shane Davies

Redis is an open source, advanced key-value store. Shane will present some examples using an open source java library Jedis to create various data structures that can be stored in Redis. He will start with a brief intro to the command line interface, some history, and finish it off with some code examples.

1 Like
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Intro to Redis

  1. 1. What is Redis?• Redis is an open source, advanced key-value store. It is often referred to as a data structure server since keys can contain strings, hashes, lists, sets and sorted sets.
  2. 2. What is Jedis? • Redis recommended client is Jedis. • Available at Maven dependency <dependency>Setting up the Pool <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> private void setupPool(){ <version>2.0.0</version> try{ <type>jar</type> pool = new JedisPool(new JedisPoolConfig(), HOST, PORT, <scope>compile</scope>poolTimeout) ; </dependency> jedis = pool.getResource(); System.out.println("Redis Client is connection to: " + HOST + ":" +PORT) ; jedis.auth("foobared"); jedis.configSet("timeout", "500"); jedis.connect(); jedis.flushAll(); }catch(Exception ex){ ex.printStackTrace(); } } git clone git://
  3. 3. InstallationDownload, extract and compile Redis with:$ wget$ tar xzf redis-2.4.13.tar.gz$ cd redis-2.4.13$ make
  4. 4. Basic Usage- Strings$ src/redis-cliredis> set foo barOKredis> get foo"bar"
  5. 5. Basic Usage- StringsAPPEND – Make a string longerGET – Fetch a string at keyGETRANGE – Fetch a substring of keys valueGETSET – Get and Set in one operationMGET – Multiple GetsMSET – Multiple SetsMSETNX – SET Multiple if Not eXistsSET – SET a value if not existsSETEX – SET a value that EXpiresSETNX – Set if Not eXistsSETRANGE – Rewrite a substringSTRLEN – Integer length of string
  6. 6. Basic Usage- More with StringsINCR, INCRBY, DECR, DECRBY,Atomic Counters!Atomic operation - prevents anyother processor or I/O device fromwriting or reading memory untilthe operation is complete.
  7. 7. More with StringsIn fact, all of the built-incommands of Redis are atomic.And they can be chained together(pipelined) to create complexatomic transactions.
  8. 8. Command Line Interface Basic Usage – Keys redis> keys b* 1) "baz" 2) "bar" (Use sparingly, though; keys is expensive.)
  9. 9. Basic Usage - Listsredis> LPUSH mylist "world" public void lPushListTest(String queueName,(integer) 1 String value){redis> LPUSH mylist "hello" try{(integer) 2 jedis.lpush(queueName, value) ;// [ world, hello ] }catch(Exception ex){redis> LRANGE mylist 0 -1 ex.printStackTrace();1) "hello" }2) "world" } public void lPopList(String queueName){ while(jedis.llen(queueName) != 0 ){ String item = jedis.lpop(queueName); } }
  10. 10. Basic Usage - ListsLINDEX – Return the list item at a certain positionLINSERT – Insert item into list BEFORE|AFTER itemLLEN – Number of list items (length)LRANGE – Return some of the itemsLREM – Remove one or more itemsLSET – Sets the list element at index to valueLTRIM – Lop off some itemsLPOP, LPUSH, LPUSHX – Left pop/pushRPOP, RPUSH, RPUSHX, RPOPLPUSH – Right pop/pushBLPOP, BRPOP, BRPOPLPUSH – Blocking pop/push
  11. 11. Basic Usage - Setsredis> SADD myset "Hello"(integer) 1redis> SADD myset "World"(integer) 1redis> SADD myset "World" public void sAdd(String key, String member)(integer) 0redis> SMEMBERS myset throws Exception {1) "World" 2) "Hello“ Jedis jedis = null;redis> try{ jedis = (Jedis) getJedisInstance() ; jedis.sadd(key, member); }catch(Exception ex){ ex.printStackTrace(); }finally{ returnJedisInstance(jedis); getLog( getClass() ).logInfo("returnJedisInstance"); } }
  12. 12. Basic Usage - SetsSADD – Add a member to a setSCARD – Set CARDinality – Number of set membersSDIFF – Calculate difference between 2 setsSDIFFSTORE – Store the Difference of 2 sets in a setSINTER – Calculate the intersection between 2 setsSINTERSTORE – Store the intersection of 2 sets in a setSISMEMBER – Bool test whether X is a member of set SSMEMBERS – list out all the membersSMOVE – Move a member from a set to another setSPOP – Pop a member off from a setSRANDMEMBER – Fetch a random set memberSREM – Remove a member from the setSUNION – Merge two sets togetherSUNIONSTORE – Store the merger of two sets in a set
  13. 13. Basic Usage - Hashesredis> HMSET myhash field1 "Hello" field2 "World"OKredis> HGET myhash field1"Hello“redis> HGET myhash field2 "World"redis> public void hSetTest(String queueName, String key, String value){ try{ jedis.hsetnx(queueName, key, value) ; }catch(Exception ex){ ex.printStackTrace(); } }
  14. 14. Basic Usage - HashesHDEL – Delete a field & value from a hashHEXISTS – Bool test whether field is in hashHGET – fetch value stored under hash → fieldHGETALL – fetch the whole hashHINCRBY – Increment a value stored under a hash fieldHKEYS – keys as a set → array_keys( )HLEN – Integer – Number of fields stored in hashHMGET – Array – Fetch multiple fields from hashHMSET – Set multiple fields in a hashHSET – Set one field in a hashHSETNX – Set a hash field if it doesnt existHVALS – vals as a list → array_values( )
  15. 15. Basic Usage - Sorted Setsredis> ZADD myzset 1 "one“ (integer) 1redis> ZADD myzset 1 "uno"(integer) 1redis> ZADD myzset 2 "two" public void zAdd(String key, Sting score, String(integer) 1redis> ZADD myzset 3 "two" member) throws Exception {(integer) 0 Jedis jedis = null;redis> ZRANGE myzset 0 -1 try{WITHSCORES jedis = (Jedis) getJedisInstance() ;1) "one“2) "1" jedis.zadd(key, score, member);3) "uno"4) "1" }catch(Exception ex){5) "two"6) "3" ex.printStackTrace();redis> }finally{ returnJedisInstance(jedis); getLog( getClass() ).logInfo("returnJedisInstance"); } }
  16. 16. Basic Usage - Sorted SetsZADD – Add a member to a set with a scoreZCARD – Count how many members are in the sorted setZCOUNT – Count how many elemenents between 2 scoresZINCRBY – Increase/Decrease a members scoreZINTERSTORE – Intersect on scores and store itZRANGE – Return some members between 2 indexesZRANGEBYSCORE – Return some members between 2 scoresZRANK – Returns a member index from Lo to HiZREM – Remove a sorted sets memberZREMRANGEBYRANK – Remove some members by rankZREMRANGEBYSCORE – Remove some members by scoreZREVRANGE – Fetch members by index in desc orderZREVRANGEBYSCORE – Fetch members by score in desc orderZREVRANK – Returns the index from Hi to LoZSCORE – Fetch the score of a memberZUNIONSTORE – Merge 2 sorted sets into a 3rd sorted set
  17. 17. Basic Usage- Pub/Sub redis>redis> subscribe fooReading messages... (press Ctrl-C to quit)1) "subscribe"2) “foo"3) (integer) 1
  18. 18. Basic Usage- Pub/Sub redis>publish foo test (integer) 1redis> subscribe fooReading messages... (press Ctrl-C to quit)1) "subscribe"2) “foo"3) (integer) 11) "message"2) “foo"3) “test"
  19. 19. Basic Usage- Pub/Sub public void publishMessage(String channel, String message){ try{ jedis.publish(channel, message); }catch(Exception ex){ ex.printStackTrace(); } }public void subscribeChannels(String channel1, String channel2){ try{ jedis.subscribe(this, channel1, channel2);System.out.println("sub.getSubscribedChannels();" +this.getSubscribedChannels()); }catch(Exception ex){ ex.printStackTrace(); } }
  20. 20. Utilitiespublic void flushAllQueue(){ try{ jedis.flushAll(); jedis.flushDB(); }catch(Exception ex){ ex.printStackTrace(); }}public void saveQueueToDisk(){;}