Top Banner
21

Intro to Redis

May 06, 2015

Download

Technology

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.
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Intro to Redis
Page 2: Intro to Redis

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.

http://redis.io

Page 3: Intro to Redis

What is Jedis?• Redis recommended client is Jedis.

• Available at https://github.com/xetorthio/jedis/wiki/Getting-started

http://redis.io/clients git clone git://github.com/xetorthio/jedis.git

Maven dependency

<dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.0.0</version> <type>jar</type> <scope>compile</scope></dependency>

Setting up the Pool

private void setupPool(){ try{ pool = new JedisPool(new JedisPoolConfig(), HOST, PORT, poolTimeout) ; 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(); } }

Page 4: Intro to Redis

InstallationDownload, extract and compile Redis with:$ wget http://redis.googlecode.com/files/redis-2.4.13.tar.gz$ tar xzf redis-2.4.13.tar.gz$ cd redis-2.4.13$ make

Page 5: Intro to Redis

Basic Usage- Strings $ src/redis-cliredis> set foo barOKredis> get foo"bar"

Page 6: Intro to Redis

Basic Usage- StringsAPPEND – Make a string longerGET – Fetch a string at keyGETRANGE – Fetch a substring of key's 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

Page 7: Intro to Redis

Basic Usage- More with Strings

INCR, INCRBY, DECR, DECRBY,

Atomic Counters!

Atomic operation - prevents anyother processor or I/O device fromwriting or reading memory untilthe operation is complete.

Page 8: Intro to Redis

More with Strings

In fact, all of the built-incommands of Redis are atomic.

And they can be chained together(pipelined) to create complexatomic transactions.

Page 9: Intro to Redis

Command Line Interface

Basic Usage – Keys

redis> keys b*1) "baz"2) "bar"

(Use sparingly, though; keys is expensive.)

Page 10: Intro to Redis

Basic Usage - Listsredis> LPUSH mylist "world"(integer) 1redis> LPUSH mylist "hello"(integer) 2// [ 'world', 'hello' ]redis> LRANGE mylist 0 -11) "hello"2) "world"

public void lPushListTest(String queueName, String value){ try{ jedis.lpush(queueName, value) ; }catch(Exception ex){ ex.printStackTrace(); } }

public void lPopList(String queueName){ while(jedis.llen(queueName) != 0 ){ String item = jedis.lpop(queueName); } }

Page 11: Intro to Redis

Basic Usage - Lists

LINDEX – 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

Page 12: Intro to Redis

Basic Usage - Setsredis>  SADD myset "Hello" (integer) 1

redis>  SADD myset "World" (integer) 1

redis>  SADD myset "World" (integer) 0

redis>  SMEMBERS myset 1) "World" 2) "Hello“

redis> 

public void sAdd(String key, String member) throws Exception { Jedis jedis = null; try{ jedis = (Jedis) getJedisInstance() ;jedis.sadd(key, member); }catch(Exception ex){ ex.printStackTrace(); }finally{ returnJedisInstance(jedis); getLog( getClass() ).logInfo("returnJedisInstance"); } }

Page 13: Intro to Redis

Basic Usage - Sets

SADD – 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

Page 14: Intro to Redis

Basic Usage - Hashesredis>  HMSET myhash field1 "Hello" field2 "World" OK

redis>  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(); } }

Page 15: Intro to Redis

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 doesn't existHVALS – vals as a list → array_values( )

Page 16: Intro to Redis

Basic Usage - Sorted Sets

public void zAdd(String key, Sting score, String member) throws Exception { Jedis jedis = null; try{ jedis = (Jedis) getJedisInstance() ;jedis.zadd(key, score, member); }catch(Exception ex){ ex.printStackTrace(); }finally{ returnJedisInstance(jedis); getLog( getClass() ).logInfo("returnJedisInstance"); } }

redis>  ZADD myzset 1 "one“ (integer) 1

redis>  ZADD myzset 1 "uno" (integer) 1

redis>  ZADD myzset 2 "two" (integer) 1

redis>  ZADD myzset 3 "two" (integer) 0

redis>  ZRANGE myzset 0 -1 WITHSCORES 1) "one“2) "1" 3) "uno" 4) "1" 5) "two" 6) "3"

redis> 

Page 17: Intro to Redis

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 member's 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 set's 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

Page 18: Intro to Redis

Basic Usage- Pub/Sub

redis> subscribe fooReading messages... (press Ctrl-C to quit)1) "subscribe"2) “foo"3) (integer) 1

redis>

Page 19: Intro to Redis

Basic Usage- Pub/Sub

redis> subscribe fooReading messages... (press Ctrl-C to quit)1) "subscribe"2) “foo"3) (integer) 1 1) "message"2) “foo"3) “test"

redis>publish foo test(integer) 1

Page 20: Intro to Redis

Basic Usage- Pub/Sub

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(); } }

public void publishMessage(String channel, String message){ try{ jedis.publish(channel, message); }catch(Exception ex){ ex.printStackTrace(); }}

Page 21: Intro to Redis

Utilities public void flushAllQueue(){ try{ jedis.flushAll(); jedis.flushDB(); }catch(Exception ex){ ex.printStackTrace(); } }

public void saveQueueToDisk(){ jedis.save(); }