SlideShare a Scribd company logo
1 of 21
Download to read offline
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
What is Jedis?
 •      Redis recommended client is Jedis.

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

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




http://redis.io/clients                                                          git clone git://github.com/xetorthio/jedis.git
Installation
Download, 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
Basic Usage- Strings
$ src/redis-cli
redis> set foo bar
OK
redis> get foo
"bar"
Basic Usage- Strings
APPEND – Make a string longer
GET – Fetch a string at key
GETRANGE – Fetch a substring of key's value
GETSET – Get and Set in one operation
MGET – Multiple Gets
MSET – Multiple Sets
MSETNX – SET Multiple if Not eXists
SET – SET a value if not exists
SETEX – SET a value that EXpires
SETNX – Set if Not eXists
SETRANGE – Rewrite a substring
STRLEN – Integer length of string
Basic Usage- More with Strings

INCR, INCRBY, DECR, DECRBY,

Atomic Counters!


Atomic operation - prevents any
other processor or I/O device from
writing or reading memory until
the operation is complete.
More with Strings

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



And they can be chained together
(pipelined) to create complex
atomic transactions.
Command Line Interface

  Basic Usage – Keys

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

  (Use sparingly, though; keys is expensive.)
Basic Usage - Lists
redis> 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);

                                    }

                                }
Basic Usage - Lists

LINDEX – Return the list item at a certain position
LINSERT – Insert item into list BEFORE|AFTER item
LLEN – Number of list items (length)
LRANGE – Return some of the items
LREM – Remove one or more items
LSET – Sets the list element at index to value
LTRIM – Lop off some items
LPOP, LPUSH, LPUSHX – Left pop/push
RPOP, RPUSH, RPUSHX, RPOPLPUSH – Right pop/push
BLPOP, BRPOP, BRPOPLPUSH – Blocking pop/push
Basic Usage - Sets
redis>   SADD myset "Hello"
(integer) 1

redis> SADD myset "World"
(integer) 1

redis> SADD myset "World"      public void sAdd(String key, String member)
(integer) 0

redis> 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");
                                    }
                                  }
Basic Usage - Sets

SADD – Add a member to a set
SCARD – Set CARDinality – Number of set members
SDIFF – Calculate difference between 2 sets
SDIFFSTORE – Store the Difference of 2 sets in a set
SINTER – Calculate the intersection between 2 sets
SINTERSTORE – Store the intersection of 2 sets in a set
SISMEMBER – Bool test whether X is a member of set S
SMEMBERS – list out all the members
SMOVE – Move a member from a set to another set
SPOP – Pop a member off from a set
SRANDMEMBER – Fetch a random set member
SREM – Remove a member from the set
SUNION – Merge two sets together
SUNIONSTORE – Store the merger of two sets in a set
Basic Usage - Hashes
redis> 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();
                                           }
                                        }
Basic Usage - Hashes
HDEL – Delete a field & value from a hash
HEXISTS – Bool test whether field is in hash
HGET – fetch value stored under hash → field
HGETALL – fetch the whole hash
HINCRBY – Increment a value stored under a hash field
HKEYS – keys as a set → array_keys( )
HLEN – Integer – Number of fields stored in hash
HMGET – Array – Fetch multiple fields from hash
HMSET – Set multiple fields in a hash
HSET – Set one field in a hash
HSETNX – Set a hash field if it doesn't exist
HVALS – vals as a list → array_values( )
Basic Usage - Sorted Sets
redis> ZADD myzset 1 "one“
 (integer) 1

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

redis> ZADD myzset 2 "two"   public void zAdd(String key, Sting score, String
(integer) 1
redis> 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");
                                  }
                                }
Basic Usage - Sorted Sets
ZADD – Add a member to a set with a score
ZCARD – Count how many members are in the sorted set
ZCOUNT – Count how many elemenents between 2 scores
ZINCRBY – Increase/Decrease a member's score
ZINTERSTORE – Intersect on scores and store it
ZRANGE – Return some members between 2 indexes
ZRANGEBYSCORE – Return some members between 2 scores
ZRANK – Returns a member index from Lo to Hi
ZREM – Remove a sorted set's member
ZREMRANGEBYRANK – Remove some members by rank
ZREMRANGEBYSCORE – Remove some members by score
ZREVRANGE – Fetch members by index in desc order
ZREVRANGEBYSCORE – Fetch members by score in desc order
ZREVRANK – Returns the index from Hi to Lo
ZSCORE – Fetch the score of a member
ZUNIONSTORE – Merge 2 sorted sets into a 3rd sorted set
Basic Usage- Pub/Sub

                       redis>




redis> subscribe foo
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) “foo"
3) (integer) 1
Basic Usage- Pub/Sub

                       redis>publish foo test
                       (integer) 1




redis> subscribe foo
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) “foo"
3) (integer) 1
1) "message"
2) “foo"
3) “test"
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();
     }
  }
Utilities
public void flushAllQueue(){
  try{
     jedis.flushAll();
     jedis.flushDB();
  }catch(Exception ex){
     ex.printStackTrace();
  }
}




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

More Related Content

What's hot

BDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
BDD - Behavior Driven Development Webapps mit Groovy Spock und GebBDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
BDD - Behavior Driven Development Webapps mit Groovy Spock und GebChristian Baranowski
 
The Ring programming language version 1.10 book - Part 92 of 212
The Ring programming language version 1.10 book - Part 92 of 212The Ring programming language version 1.10 book - Part 92 of 212
The Ring programming language version 1.10 book - Part 92 of 212Mahmoud Samir Fayed
 
บทที่6 update&delete
บทที่6 update&deleteบทที่6 update&delete
บทที่6 update&deletePalm Unnop
 
Python client api
Python client apiPython client api
Python client apidreampuf
 
Replication MongoDB Days 2013
Replication MongoDB Days 2013Replication MongoDB Days 2013
Replication MongoDB Days 2013Randall Hunt
 
Replication and Replica Sets
Replication and Replica SetsReplication and Replica Sets
Replication and Replica SetsMongoDB
 
[제1회 루씬 한글분석기 기술세미나] solr로 나만의 검색엔진을 만들어보자
[제1회 루씬 한글분석기 기술세미나] solr로 나만의 검색엔진을 만들어보자[제1회 루씬 한글분석기 기술세미나] solr로 나만의 검색엔진을 만들어보자
[제1회 루씬 한글분석기 기술세미나] solr로 나만의 검색엔진을 만들어보자Donghyeok Kang
 
Testing Web Applications with GEB
Testing Web Applications with GEBTesting Web Applications with GEB
Testing Web Applications with GEBHoward Lewis Ship
 
SecureSocial - Authentication for Play Framework
SecureSocial - Authentication for Play FrameworkSecureSocial - Authentication for Play Framework
SecureSocial - Authentication for Play Frameworkjaliss
 
Real Time Web with Node
Real Time Web with NodeReal Time Web with Node
Real Time Web with NodeTim Caswell
 
Node Powered Mobile
Node Powered MobileNode Powered Mobile
Node Powered MobileTim Caswell
 
Terraform for fun and profit
Terraform for fun and profitTerraform for fun and profit
Terraform for fun and profitBram Vogelaar
 

What's hot (19)

Hadoop
HadoopHadoop
Hadoop
 
BDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
BDD - Behavior Driven Development Webapps mit Groovy Spock und GebBDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
BDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
 
The Ring programming language version 1.10 book - Part 92 of 212
The Ring programming language version 1.10 book - Part 92 of 212The Ring programming language version 1.10 book - Part 92 of 212
The Ring programming language version 1.10 book - Part 92 of 212
 
Spock and Geb in Action
Spock and Geb in ActionSpock and Geb in Action
Spock and Geb in Action
 
บทที่6 update&delete
บทที่6 update&deleteบทที่6 update&delete
บทที่6 update&delete
 
Java
JavaJava
Java
 
Python client api
Python client apiPython client api
Python client api
 
Replication MongoDB Days 2013
Replication MongoDB Days 2013Replication MongoDB Days 2013
Replication MongoDB Days 2013
 
Unit testing pig
Unit testing pigUnit testing pig
Unit testing pig
 
Replication and Replica Sets
Replication and Replica SetsReplication and Replica Sets
Replication and Replica Sets
 
[제1회 루씬 한글분석기 기술세미나] solr로 나만의 검색엔진을 만들어보자
[제1회 루씬 한글분석기 기술세미나] solr로 나만의 검색엔진을 만들어보자[제1회 루씬 한글분석기 기술세미나] solr로 나만의 검색엔진을 만들어보자
[제1회 루씬 한글분석기 기술세미나] solr로 나만의 검색엔진을 만들어보자
 
Testing Web Applications with GEB
Testing Web Applications with GEBTesting Web Applications with GEB
Testing Web Applications with GEB
 
veracruz
veracruzveracruz
veracruz
 
Nantes Jug - Java 7
Nantes Jug - Java 7Nantes Jug - Java 7
Nantes Jug - Java 7
 
SecureSocial - Authentication for Play Framework
SecureSocial - Authentication for Play FrameworkSecureSocial - Authentication for Play Framework
SecureSocial - Authentication for Play Framework
 
Real Time Web with Node
Real Time Web with NodeReal Time Web with Node
Real Time Web with Node
 
Node Powered Mobile
Node Powered MobileNode Powered Mobile
Node Powered Mobile
 
Elastic search 검색
Elastic search 검색Elastic search 검색
Elastic search 검색
 
Terraform for fun and profit
Terraform for fun and profitTerraform for fun and profit
Terraform for fun and profit
 

Similar to Intro to Redis

REDIS intro and how to use redis
REDIS intro and how to use redisREDIS intro and how to use redis
REDIS intro and how to use redisKris Jeong
 
Introduction to redis
Introduction to redisIntroduction to redis
Introduction to redisTanu Siwag
 
From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)Night Sailer
 
Softshake 2013: 10 reasons why java developers are jealous of Scala developers
Softshake 2013: 10 reasons why java developers are jealous of Scala developersSoftshake 2013: 10 reasons why java developers are jealous of Scala developers
Softshake 2013: 10 reasons why java developers are jealous of Scala developersMatthew Farwell
 
Postgres & Redis Sitting in a Tree- Rimas Silkaitis, Heroku
Postgres & Redis Sitting in a Tree- Rimas Silkaitis, HerokuPostgres & Redis Sitting in a Tree- Rimas Silkaitis, Heroku
Postgres & Redis Sitting in a Tree- Rimas Silkaitis, HerokuRedis Labs
 
Try Redis - interactive Tutorial
Try Redis - interactive TutorialTry Redis - interactive Tutorial
Try Redis - interactive TutorialEdward Lee
 
quickguide-einnovator-9-redis
quickguide-einnovator-9-redisquickguide-einnovator-9-redis
quickguide-einnovator-9-redisjorgesimao71
 
Drools5 Community Training Module 3 Drools Expert DRL Syntax
Drools5 Community Training Module 3 Drools Expert DRL SyntaxDrools5 Community Training Module 3 Drools Expert DRL Syntax
Drools5 Community Training Module 3 Drools Expert DRL SyntaxMauricio (Salaboy) Salatino
 
Lisp как универсальная обертка
Lisp как универсальная оберткаLisp как универсальная обертка
Lisp как универсальная оберткаVsevolod Dyomkin
 
Lisp for Python Programmers
Lisp for Python ProgrammersLisp for Python Programmers
Lisp for Python ProgrammersVsevolod Dyomkin
 
Redis for the Everyday Developer
Redis for the Everyday DeveloperRedis for the Everyday Developer
Redis for the Everyday DeveloperRoss Tuck
 
学生向けScalaハンズオンテキスト
学生向けScalaハンズオンテキスト学生向けScalaハンズオンテキスト
学生向けScalaハンズオンテキストOpt Technologies
 
Building fast interpreters in Rust
Building fast interpreters in RustBuilding fast interpreters in Rust
Building fast interpreters in RustIngvar Stepanyan
 
Building node.js applications with Database Jones
Building node.js applications with Database JonesBuilding node.js applications with Database Jones
Building node.js applications with Database JonesJohn David Duncan
 
Programming Lisp Clojure - 2장 : 클로저 둘러보기
Programming Lisp Clojure - 2장 : 클로저 둘러보기Programming Lisp Clojure - 2장 : 클로저 둘러보기
Programming Lisp Clojure - 2장 : 클로저 둘러보기JangHyuk You
 

Similar to Intro to Redis (20)

REDIS intro and how to use redis
REDIS intro and how to use redisREDIS intro and how to use redis
REDIS intro and how to use redis
 
Introduction to redis
Introduction to redisIntroduction to redis
Introduction to redis
 
Redis introduction
Redis introductionRedis introduction
Redis introduction
 
From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)
 
Softshake 2013: 10 reasons why java developers are jealous of Scala developers
Softshake 2013: 10 reasons why java developers are jealous of Scala developersSoftshake 2013: 10 reasons why java developers are jealous of Scala developers
Softshake 2013: 10 reasons why java developers are jealous of Scala developers
 
Postgres & Redis Sitting in a Tree- Rimas Silkaitis, Heroku
Postgres & Redis Sitting in a Tree- Rimas Silkaitis, HerokuPostgres & Redis Sitting in a Tree- Rimas Silkaitis, Heroku
Postgres & Redis Sitting in a Tree- Rimas Silkaitis, Heroku
 
Php&redis presentation
Php&redis presentationPhp&redis presentation
Php&redis presentation
 
Try Redis - interactive Tutorial
Try Redis - interactive TutorialTry Redis - interactive Tutorial
Try Redis - interactive Tutorial
 
quickguide-einnovator-9-redis
quickguide-einnovator-9-redisquickguide-einnovator-9-redis
quickguide-einnovator-9-redis
 
Spark workshop
Spark workshopSpark workshop
Spark workshop
 
Drools5 Community Training Module 3 Drools Expert DRL Syntax
Drools5 Community Training Module 3 Drools Expert DRL SyntaxDrools5 Community Training Module 3 Drools Expert DRL Syntax
Drools5 Community Training Module 3 Drools Expert DRL Syntax
 
Lisp как универсальная обертка
Lisp как универсальная оберткаLisp как универсальная обертка
Lisp как универсальная обертка
 
Update&delete
Update&deleteUpdate&delete
Update&delete
 
Lisp for Python Programmers
Lisp for Python ProgrammersLisp for Python Programmers
Lisp for Python Programmers
 
Jug java7
Jug java7Jug java7
Jug java7
 
Redis for the Everyday Developer
Redis for the Everyday DeveloperRedis for the Everyday Developer
Redis for the Everyday Developer
 
学生向けScalaハンズオンテキスト
学生向けScalaハンズオンテキスト学生向けScalaハンズオンテキスト
学生向けScalaハンズオンテキスト
 
Building fast interpreters in Rust
Building fast interpreters in RustBuilding fast interpreters in Rust
Building fast interpreters in Rust
 
Building node.js applications with Database Jones
Building node.js applications with Database JonesBuilding node.js applications with Database Jones
Building node.js applications with Database Jones
 
Programming Lisp Clojure - 2장 : 클로저 둘러보기
Programming Lisp Clojure - 2장 : 클로저 둘러보기Programming Lisp Clojure - 2장 : 클로저 둘러보기
Programming Lisp Clojure - 2장 : 클로저 둘러보기
 

More from Boulder Java User's Group (8)

Spring insight what just happened
Spring insight   what just happenedSpring insight   what just happened
Spring insight what just happened
 
Introduction To Pentaho Kettle
Introduction To Pentaho KettleIntroduction To Pentaho Kettle
Introduction To Pentaho Kettle
 
Big Data and OSS at IBM
Big Data and OSS at IBMBig Data and OSS at IBM
Big Data and OSS at IBM
 
Json at work overview and ecosystem-v2.0
Json at work   overview and ecosystem-v2.0Json at work   overview and ecosystem-v2.0
Json at work overview and ecosystem-v2.0
 
Restful design at work v2.0
Restful design at work v2.0Restful design at work v2.0
Restful design at work v2.0
 
Introduction To JavaFX 2.0
Introduction To JavaFX 2.0Introduction To JavaFX 2.0
Introduction To JavaFX 2.0
 
55 New Features in Java 7
55 New Features in Java 755 New Features in Java 7
55 New Features in Java 7
 
Watson and Open Source Tools
Watson and Open Source ToolsWatson and Open Source Tools
Watson and Open Source Tools
 

Recently uploaded

IT Service Management (ITSM) Best Practices for Advanced Computing
IT Service Management (ITSM) Best Practices for Advanced ComputingIT Service Management (ITSM) Best Practices for Advanced Computing
IT Service Management (ITSM) Best Practices for Advanced ComputingMAGNIntelligence
 
Outage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedIn
Outage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedInOutage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedIn
Outage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedInThousandEyes
 
From the origin to the future of Open Source model and business
From the origin to the future of  Open Source model and businessFrom the origin to the future of  Open Source model and business
From the origin to the future of Open Source model and businessFrancesco Corti
 
Top 10 Squarespace Development Companies
Top 10 Squarespace Development CompaniesTop 10 Squarespace Development Companies
Top 10 Squarespace Development CompaniesTopCSSGallery
 
UiPath Studio Web workshop Series - Day 3
UiPath Studio Web workshop Series - Day 3UiPath Studio Web workshop Series - Day 3
UiPath Studio Web workshop Series - Day 3DianaGray10
 
Q4 2023 Quarterly Investor Presentation - FINAL - v1.pdf
Q4 2023 Quarterly Investor Presentation - FINAL - v1.pdfQ4 2023 Quarterly Investor Presentation - FINAL - v1.pdf
Q4 2023 Quarterly Investor Presentation - FINAL - v1.pdfTejal81
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
 
Oracle Database 23c Security New Features.pptx
Oracle Database 23c Security New Features.pptxOracle Database 23c Security New Features.pptx
Oracle Database 23c Security New Features.pptxSatishbabu Gunukula
 
LF Energy Webinar - Unveiling OpenEEMeter 4.0
LF Energy Webinar - Unveiling OpenEEMeter 4.0LF Energy Webinar - Unveiling OpenEEMeter 4.0
LF Energy Webinar - Unveiling OpenEEMeter 4.0DanBrown980551
 
Planetek Italia Srl - Corporate Profile Brochure
Planetek Italia Srl - Corporate Profile BrochurePlanetek Italia Srl - Corporate Profile Brochure
Planetek Italia Srl - Corporate Profile BrochurePlanetek Italia Srl
 
TrustArc Webinar - How to Live in a Post Third-Party Cookie World
TrustArc Webinar - How to Live in a Post Third-Party Cookie WorldTrustArc Webinar - How to Live in a Post Third-Party Cookie World
TrustArc Webinar - How to Live in a Post Third-Party Cookie WorldTrustArc
 
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - Tech
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - TechWebinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - Tech
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - TechProduct School
 
Keep Your Finger on the Pulse of Your Building's Performance with IES Live
Keep Your Finger on the Pulse of Your Building's Performance with IES LiveKeep Your Finger on the Pulse of Your Building's Performance with IES Live
Keep Your Finger on the Pulse of Your Building's Performance with IES LiveIES VE
 
UiPath Studio Web workshop series - Day 1
UiPath Studio Web workshop series  - Day 1UiPath Studio Web workshop series  - Day 1
UiPath Studio Web workshop series - Day 1DianaGray10
 
Trailblazer Community - Flows Workshop (Session 2)
Trailblazer Community - Flows Workshop (Session 2)Trailblazer Community - Flows Workshop (Session 2)
Trailblazer Community - Flows Workshop (Session 2)Muhammad Tiham Siddiqui
 
The Importance of Indoor Air Quality (English)
The Importance of Indoor Air Quality (English)The Importance of Indoor Air Quality (English)
The Importance of Indoor Air Quality (English)IES VE
 
Flow Control | Block Size | ST Min | First Frame
Flow Control | Block Size | ST Min | First FrameFlow Control | Block Size | ST Min | First Frame
Flow Control | Block Size | ST Min | First FrameKapil Thakar
 
Where developers are challenged, what developers want and where DevEx is going
Where developers are challenged, what developers want and where DevEx is goingWhere developers are challenged, what developers want and where DevEx is going
Where developers are challenged, what developers want and where DevEx is goingFrancesco Corti
 
GraphSummit Copenhagen 2024 - Neo4j Vision and Roadmap.pptx
GraphSummit Copenhagen 2024 - Neo4j Vision and Roadmap.pptxGraphSummit Copenhagen 2024 - Neo4j Vision and Roadmap.pptx
GraphSummit Copenhagen 2024 - Neo4j Vision and Roadmap.pptxNeo4j
 

Recently uploaded (20)

IT Service Management (ITSM) Best Practices for Advanced Computing
IT Service Management (ITSM) Best Practices for Advanced ComputingIT Service Management (ITSM) Best Practices for Advanced Computing
IT Service Management (ITSM) Best Practices for Advanced Computing
 
Outage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedIn
Outage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedInOutage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedIn
Outage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedIn
 
From the origin to the future of Open Source model and business
From the origin to the future of  Open Source model and businessFrom the origin to the future of  Open Source model and business
From the origin to the future of Open Source model and business
 
Top 10 Squarespace Development Companies
Top 10 Squarespace Development CompaniesTop 10 Squarespace Development Companies
Top 10 Squarespace Development Companies
 
SheDev 2024
SheDev 2024SheDev 2024
SheDev 2024
 
UiPath Studio Web workshop Series - Day 3
UiPath Studio Web workshop Series - Day 3UiPath Studio Web workshop Series - Day 3
UiPath Studio Web workshop Series - Day 3
 
Q4 2023 Quarterly Investor Presentation - FINAL - v1.pdf
Q4 2023 Quarterly Investor Presentation - FINAL - v1.pdfQ4 2023 Quarterly Investor Presentation - FINAL - v1.pdf
Q4 2023 Quarterly Investor Presentation - FINAL - v1.pdf
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
Oracle Database 23c Security New Features.pptx
Oracle Database 23c Security New Features.pptxOracle Database 23c Security New Features.pptx
Oracle Database 23c Security New Features.pptx
 
LF Energy Webinar - Unveiling OpenEEMeter 4.0
LF Energy Webinar - Unveiling OpenEEMeter 4.0LF Energy Webinar - Unveiling OpenEEMeter 4.0
LF Energy Webinar - Unveiling OpenEEMeter 4.0
 
Planetek Italia Srl - Corporate Profile Brochure
Planetek Italia Srl - Corporate Profile BrochurePlanetek Italia Srl - Corporate Profile Brochure
Planetek Italia Srl - Corporate Profile Brochure
 
TrustArc Webinar - How to Live in a Post Third-Party Cookie World
TrustArc Webinar - How to Live in a Post Third-Party Cookie WorldTrustArc Webinar - How to Live in a Post Third-Party Cookie World
TrustArc Webinar - How to Live in a Post Third-Party Cookie World
 
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - Tech
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - TechWebinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - Tech
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - Tech
 
Keep Your Finger on the Pulse of Your Building's Performance with IES Live
Keep Your Finger on the Pulse of Your Building's Performance with IES LiveKeep Your Finger on the Pulse of Your Building's Performance with IES Live
Keep Your Finger on the Pulse of Your Building's Performance with IES Live
 
UiPath Studio Web workshop series - Day 1
UiPath Studio Web workshop series  - Day 1UiPath Studio Web workshop series  - Day 1
UiPath Studio Web workshop series - Day 1
 
Trailblazer Community - Flows Workshop (Session 2)
Trailblazer Community - Flows Workshop (Session 2)Trailblazer Community - Flows Workshop (Session 2)
Trailblazer Community - Flows Workshop (Session 2)
 
The Importance of Indoor Air Quality (English)
The Importance of Indoor Air Quality (English)The Importance of Indoor Air Quality (English)
The Importance of Indoor Air Quality (English)
 
Flow Control | Block Size | ST Min | First Frame
Flow Control | Block Size | ST Min | First FrameFlow Control | Block Size | ST Min | First Frame
Flow Control | Block Size | ST Min | First Frame
 
Where developers are challenged, what developers want and where DevEx is going
Where developers are challenged, what developers want and where DevEx is goingWhere developers are challenged, what developers want and where DevEx is going
Where developers are challenged, what developers want and where DevEx is going
 
GraphSummit Copenhagen 2024 - Neo4j Vision and Roadmap.pptx
GraphSummit Copenhagen 2024 - Neo4j Vision and Roadmap.pptxGraphSummit Copenhagen 2024 - Neo4j Vision and Roadmap.pptx
GraphSummit Copenhagen 2024 - Neo4j Vision and Roadmap.pptx
 

Intro to Redis

  • 2. 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
  • 3. What is Jedis? • Redis recommended client is Jedis. • Available at https://github.com/xetorthio/jedis/wiki/Getting-started 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(); } } http://redis.io/clients git clone git://github.com/xetorthio/jedis.git
  • 4. Installation Download, 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
  • 5. Basic Usage- Strings $ src/redis-cli redis> set foo bar OK redis> get foo "bar"
  • 6. Basic Usage- Strings APPEND – Make a string longer GET – Fetch a string at key GETRANGE – Fetch a substring of key's value GETSET – Get and Set in one operation MGET – Multiple Gets MSET – Multiple Sets MSETNX – SET Multiple if Not eXists SET – SET a value if not exists SETEX – SET a value that EXpires SETNX – Set if Not eXists SETRANGE – Rewrite a substring STRLEN – Integer length of string
  • 7. Basic Usage- More with Strings INCR, INCRBY, DECR, DECRBY, Atomic Counters! Atomic operation - prevents any other processor or I/O device from writing or reading memory until the operation is complete.
  • 8. More with Strings In fact, all of the built-in commands of Redis are atomic. And they can be chained together (pipelined) to create complex atomic transactions.
  • 9. Command Line Interface Basic Usage – Keys redis> keys b* 1) "baz" 2) "bar" (Use sparingly, though; keys is expensive.)
  • 10. Basic Usage - Lists redis> 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); } }
  • 11. Basic Usage - Lists LINDEX – Return the list item at a certain position LINSERT – Insert item into list BEFORE|AFTER item LLEN – Number of list items (length) LRANGE – Return some of the items LREM – Remove one or more items LSET – Sets the list element at index to value LTRIM – Lop off some items LPOP, LPUSH, LPUSHX – Left pop/push RPOP, RPUSH, RPUSHX, RPOPLPUSH – Right pop/push BLPOP, BRPOP, BRPOPLPUSH – Blocking pop/push
  • 12. Basic Usage - Sets redis> SADD myset "Hello" (integer) 1 redis> SADD myset "World" (integer) 1 redis> SADD myset "World" public void sAdd(String key, String member) (integer) 0 redis> 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"); } }
  • 13. Basic Usage - Sets SADD – Add a member to a set SCARD – Set CARDinality – Number of set members SDIFF – Calculate difference between 2 sets SDIFFSTORE – Store the Difference of 2 sets in a set SINTER – Calculate the intersection between 2 sets SINTERSTORE – Store the intersection of 2 sets in a set SISMEMBER – Bool test whether X is a member of set S SMEMBERS – list out all the members SMOVE – Move a member from a set to another set SPOP – Pop a member off from a set SRANDMEMBER – Fetch a random set member SREM – Remove a member from the set SUNION – Merge two sets together SUNIONSTORE – Store the merger of two sets in a set
  • 14. Basic Usage - Hashes redis> 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(); } }
  • 15. Basic Usage - Hashes HDEL – Delete a field & value from a hash HEXISTS – Bool test whether field is in hash HGET – fetch value stored under hash → field HGETALL – fetch the whole hash HINCRBY – Increment a value stored under a hash field HKEYS – keys as a set → array_keys( ) HLEN – Integer – Number of fields stored in hash HMGET – Array – Fetch multiple fields from hash HMSET – Set multiple fields in a hash HSET – Set one field in a hash HSETNX – Set a hash field if it doesn't exist HVALS – vals as a list → array_values( )
  • 16. Basic Usage - Sorted Sets redis> ZADD myzset 1 "one“ (integer) 1 redis> ZADD myzset 1 "uno" (integer) 1 redis> ZADD myzset 2 "two" public void zAdd(String key, Sting score, String (integer) 1 redis> 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"); } }
  • 17. Basic Usage - Sorted Sets ZADD – Add a member to a set with a score ZCARD – Count how many members are in the sorted set ZCOUNT – Count how many elemenents between 2 scores ZINCRBY – Increase/Decrease a member's score ZINTERSTORE – Intersect on scores and store it ZRANGE – Return some members between 2 indexes ZRANGEBYSCORE – Return some members between 2 scores ZRANK – Returns a member index from Lo to Hi ZREM – Remove a sorted set's member ZREMRANGEBYRANK – Remove some members by rank ZREMRANGEBYSCORE – Remove some members by score ZREVRANGE – Fetch members by index in desc order ZREVRANGEBYSCORE – Fetch members by score in desc order ZREVRANK – Returns the index from Hi to Lo ZSCORE – Fetch the score of a member ZUNIONSTORE – Merge 2 sorted sets into a 3rd sorted set
  • 18. Basic Usage- Pub/Sub redis> redis> subscribe foo Reading messages... (press Ctrl-C to quit) 1) "subscribe" 2) “foo" 3) (integer) 1
  • 19. Basic Usage- Pub/Sub redis>publish foo test (integer) 1 redis> subscribe foo Reading messages... (press Ctrl-C to quit) 1) "subscribe" 2) “foo" 3) (integer) 1 1) "message" 2) “foo" 3) “test"
  • 20. 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(); } }
  • 21. Utilities public void flushAllQueue(){ try{ jedis.flushAll(); jedis.flushDB(); }catch(Exception ex){ ex.printStackTrace(); } } public void saveQueueToDisk(){ jedis.save(); }