SlideShare ist ein Scribd-Unternehmen logo
1 von 35
Downloaden Sie, um offline zu lesen
Tutorial Talk

           By:
      Ankur Gupta
http://uptosomething.in
What is Redis?
                                Overview
• Few of the fundamental and commonly used data types in
  software would be string, list, hash, set.


• Redis is an in-memory key-value store. It allows you to
  add/update/delete the above data types as values to a key.
    i.e. Key:Value aka “String”:<Data Type>.
    Thus named as a data structure server.


• Redis is free, fast, easy to install ,scales well as more data is
  inserted/operation performed.


• Following languages have libraries that communicate with redis
 “ActionScript, C, C++, C#, Clojure, Common Lisp, Erlang, Go, Haskell, haXe, Io, Java, server-side
 JavaScript (Node.js), Lua, Objective-C, Perl, PHP, Pure Data, Python, Ruby, Scala, Smalltalk and Tcl “
 Wikipedia
Why Should Redis Matter?
                  Features/Use Case
•   Caching server, ( e.g. memcache equivalent)
•   Queue, (store user request that would take time to compute e.g. image resize on flickr/picasa)
•   User Clicks (Counting), (upvote/downvote on reddit)
•   Real Time Analytics for Stats, (No of users logged into chat )
•   Publish – Subscribe, ( e.g. Quora/Facebook Notification system)
Modern web application require web developer to build software that responds in
milliseconds and scale as no of users/data/operations increases e.g. increase in pageviews.

Yes, You can use a database like MySql to achieve all the above but wouldn’t it be faster to hit
RAM then HDD ?.

Using Redis developers can satisfy architectural paradigm found in modern web application
development.
Who made Redis?
          Motivation, Support, Future
Salvatore Sanfilippo is founder developer of Redis since April
2009,
• Read Redis Manifesto to understand motivation behind
  redis,
• Vmware is the sponsor of redis project with few employees
  working full time on redis,
• Redis related questions on stackoverflow and answers
  thereof gives you a sense of community support and
  usage.


• Why ?

 Beneficial to invest time mastering tools that are
 supported and will be there tomorrow.
Who is using Redis ?
Installing Redis
Linux System – Installation from Source

  ●
      Go to http://redis.io/download official download page
  ●
      Download source code of Current Stable Release - 2.4.14

      http://redis.googlecode.com/files/redis-2.4.14.tar.gz
  ●
      Extract the source code

      $ tar -xvf redis-2.4.14.tar.gz
  ●
      Redis is coded in C with dependencies being gcc and libc. If your computer
      doesn't have the same please use package manager and install the same.
  ●
      Execute the below commands in the directory where redis

      code is extracted

      $ make

      $ make test

      $ sudo make install
  ●
      You have Redis on your machine …
Running Redis
After compilation you have following binaries generated
a) redis-cli – Command line to talk to redis server
b) redis-server - Redis Server
c) redis-benchmark - is used to check Redis performances
d) redis-check-aof - Fix corrupted append only data files.
e) redis-check-dump - Useful in the event of corrupted data files.


Server


$ redis-server
     OR
$ redis-server /path/to/redisconfig.conf


Check redis.conf for default redis configuration used when no separate config file is
given. ( We will take a tour of the configuration file ahead )
Playing with redis-cli
Start Server
$ redis-server
Help
$ redis-cli --help
Can the command line client listen to server
$ redis-cli ping
Start redis-cli interactive mode
$ redis-cli


Let us try using creating the following data structures using redis-cli


a) String
b) hashes,
c) lists,
d) sets,
e) sorted sets.
String
$ redis-cli
redis 127.0.0.1:6379> set aKey aValue
OK
redis 127.0.0.1:6379> get aKey
"aValue"
redis 127.0.0.1:6379> set PyConDate "8th - 9th June 2012"
OK
redis 127.0.0.1:6379> get pycondate
(nil)
redis 127.0.0.1:6379> get PyConDate
"8th - 9th June 2012"
redis 127.0.0.1:6379> append PyConDate ": Singapore"
(integer) 30
redis 127.0.0.1:6379> get PyConDate
"8th - 9th June 2012: Singapore"
redis 127.0.0.1:6379> exists PyConDate
(integer) 1
More String
redis 127.0.0.1:6379> setex boardingpasstosingapore 10 "Ankur Gupta"
OK
redis 127.0.0.1:6379> get boardingpasstosingapore
"Ankur Gupta"
redis 127.0.0.1:6379> get boardingpasstosingapore
(nil)
redis 127.0.0.1:6379> set attendance "0"
OK
redis 127.0.0.1:6379> incr attendance
(integer) 1
redis 127.0.0.1:6379> get attendance
"1"
redis 127.0.0.1:6379> incr attendance
(integer) 2
redis 127.0.0.1:6379> get attendance
"2"
redis 127.0.0.1:6379> set attendance "A"
OK
redis 127.0.0.1:6379> incr attendance
(error) ERR value is not an integer or out of range
Key 101 ?
●   Are Byte Array. Thus binary safe.
●   Obvious : Short key consume less memory vis a vi long keys.
    How verbose is good you decide.
    e.g. “authuser:14573:cacheenable” or “au:14573:ce”
●   Good practise to create your key naming convention in codebase and sticking to
    it.


    redis 127.0.0.1:6379> set " " "blank key ?"
    OK
    redis 127.0.0.1:6379> get " "
    "blank key ?"
    redis 127.0.0.1:6379> get "     "
    (nil)
    redis 127.0.0.1:6379> set does work "no"
    (error) ERR wrong number of arguments for 'set' command
    redis 127.0.0.1:6379> set "does work" "yes"
    OK
Redis List
• 4 slide
Redis Sets
• 4 slide
Exercise
a) Download the file
   http://uptosomething.in/sghistorytimeline.csv
b) Copy the first complete line from the file
   i.e. "3rd century","Early Chinese account of Singapore describes the island of Pu
Luo Chung"
   Take first column as key and second as value. Create a string using redis,
c) Use the 6th and 7th line and create a list with 1819 as key and respective historical
events as list elements,
d) Use the 6th and 7th line and create a sorted set. Show events in reverse
chronological order,
e) Use the line no 112 onwards till EOF and create a hash such that it takes Year as
hashname, month+day as key, and historical event as value,
f) Find what events happened in the month of june and create any datastructure
you please with them such that they expire when the event day is over. e.g. event
on june 12 will get over when june 13th arrives thus will expire.
Installing Redis Python Library
https://github.com/andymccurdy/redis-py

redis-py is versioned after Redis. For example, redis-py 2.0.0
should support all the commands available in Redis 2.0.0.

$ cd andymccurdy-redis-py-d2a7156/
$ python2.7 setup.py build
$ sudo python2.7 setup.py install

redis-py exposes two client classes that implement these
commands. The StrictRedis class adhere to the official
command syntax/names with few exceptions. The library also
offers another class that gives backward compatibility with
commands that are now deprecated.
Installing Redis Python Libraries
https://github.com/andymccurdy/redis-py

redis-py is versioned after Redis. For example, redis-py 2.0.0
should support all the commands available in Redis 2.0.0.

$ cd andymccurdy-redis-py-d2a7156/
$ python2.7 setup.py build
$ sudo python2.7 setup.py install

redis-py exposes two client classes that implement these
commands. The StrictRedis class adhere to the official
command syntax/names with few exceptions. The library also
offers another class that gives backward compatibility with
commands that are now deprecated.
Redis Python Library Code Snippets
 >>> import redis

 >>> r = redis.StrictRedis(host='localhost', port=6379)

 >>> r.set('sg', 'singapore')

 >>> r.get('sg')

 'singapore'

 >>> r.rpush('cities', 'Mumbai')

 >>> r.lpush('Singapore')

 >>> r.lrange('cities', 0 , 1)

 ['Mumbai', 'Singapore']

 >>> r.llen('cities')

 2
Redis Python Library Code Snippets
 >>> r.sadd("interpretedlanguages", "Ruby")

 1

 >>> r.sadd("interpretedlanguages", "Perl")

 1

 >>> r.sadd("interpretedlanguages", "Basic")

 1

 >>> r.smembers("interpretedlanguages")

 set(['Python', 'Basic', 'Ruby', 'Perl'])

 >>>

 >>> r.sadd("interpretedlanguages", "Perl")

 0

 >>> >>> r.sismember("interpretedlanguages","Java")

 False

 >>> r.sismember("interpretedlanguages","Basic")

 True
Redis Python Library Code Snippets
    >>> r.zadd("social", 876, "blogpost:facebook:likes")

    1

    >>> r.zadd("social", 2345, "blogpost:diggs:count")

    1

    >>> r.zadd("social", 67, "blogpost:twitter:tweets")

    1

    >>>

    >>> data = r.zrange("socialinteraction", 0, -1, withscores=True)

    >>> type(data)

    <type 'list'>

    >>> data[::-1]

    [('blogpost:diggs:count', 2345.0), ('blogpost:facebook:likes', 876.0), ('blogpost:gplus:likes',
    345.0), ('blogpost:twitter:tweets', 67.0)]

    >>>
●
Redis Python Library Code Snippets
●   >>> r.hset("travelchecklist:singapore", "airlines", "Air-India")
●   1
●   >>> r.hset("travelchecklist:singapore", "currency", "1070")
●   1
●   >>> r.hkeys("travelchecklist:singapore")
●   ['airlines', 'currency']
●   >>> r.hvals("travelchecklist:singapore")
●   ['Air-India', '1070']
●   >>> r.hgetall("travelchecklist:singapore")
●   {'currency': '1070', 'airlines': 'Air-India'}
Exercise
a) Download the file
   http://uptosomething.in/sghistorytimeline.csv


Write a Python program that uses the redis module and try to do whatever cool
idea comes in your mind with the above data and redis.
Creating Live Counters
import redis
r = redis.StrictRedis(host='localhost', port=6379)


def vote(objectid, is_up_vote):
  """ is_up_vote == true means up vote else down vote """
  if not r.exists(objectid):
     r.set(objectid, 1)
     return 1
  if is_up_vote:
     return r.incr(objectid, 1)
  else:
     return r.decr(objectid, 1)


print vote("people who like the redis talk", True)
print vote("people who like the redis talk", False)
print vote("people who like the redis talk", True)
print vote("people who like the redis talk", True)
print vote("people who like the redis talk", False)
Real-time notification backend

●   Facebook
    User receives notification when
    his/her mention is made i.e. @user
●   So we have
      a) Message Text
      b) User who wrote the message
      c) Time-stamp when the message was written
      d) Other Users who were mentioned in that
        message.
Real-time notification backend

Lets denote
●   msgsourceuser = User who wrote the message
    msgtxt = Actual message
    timestamp = In seconds when the msh was written since epoch
●   Userlist = List of users for whom the message is meant

Ideas
●   Hashes
    –   Timestamp → user from UserList → msgtxt:msgsourceuser
●   Sorted Sets
    –   Msgsourceuser → msgtxt:userlist → timestamp (score)
●   Redis Pub / Sub
    –   ???
Real-time notification backend
    import redis
    rc = redis.Redis()
    psredis = rc.pubsub()
    rc.publish('statusupdate', 'In Singapore with @user,@user2,@user3')


●   ______________________________________________________________________


    import redis
    rc = redis.Redis()
    psredis = rc.pubsub()
    psredis.subscribe('statusupdate')
    for item in psredis.listen(): # problem listen is blocking call
     print item['channel']
     print item['data']
Naive Redis Based Queue
●   Let us audit an open source redis
    queue implementation and see what
    is happening inside …
Auto-complete using redis
Salvatore Sanfilippo Auto-complete
implementation's code review
https://gist.github.com/925979/b4689bfd8b0bc0408cd61efe674ea305f06524b9


( The above is python port of original ruby code )
Redis In Production Environment

●   Daemon mode + init script
●   Server options and
Redis In Production Environment

●   Daemon mode + init script
●   Server options and config file
Redis Sorted Sets
• 4 slide
Redispresentation apac2012

Weitere ähnliche Inhalte

Was ist angesagt?

OpenStack LA meetup Feb 18, 2015
OpenStack LA meetup Feb 18, 2015OpenStack LA meetup Feb 18, 2015
OpenStack LA meetup Feb 18, 2015
Tesora
 
Get Your Insecure PostgreSQL Passwords to SCRAM
Get Your Insecure PostgreSQL Passwords to SCRAMGet Your Insecure PostgreSQL Passwords to SCRAM
Get Your Insecure PostgreSQL Passwords to SCRAM
Jonathan Katz
 
Work Stealing For Fun & Profit: Jim Nelson
Work Stealing For Fun & Profit: Jim NelsonWork Stealing For Fun & Profit: Jim Nelson
Work Stealing For Fun & Profit: Jim Nelson
Redis Labs
 
Elastic search integration with hadoop leveragebigdata
Elastic search integration with hadoop   leveragebigdataElastic search integration with hadoop   leveragebigdata
Elastic search integration with hadoop leveragebigdata
Pooja Gupta
 

Was ist angesagt? (20)

StackExchange.redis
StackExchange.redisStackExchange.redis
StackExchange.redis
 
Data Encryption at Rest
Data Encryption at RestData Encryption at Rest
Data Encryption at Rest
 
Hopsfs 10x HDFS performance
Hopsfs 10x HDFS performanceHopsfs 10x HDFS performance
Hopsfs 10x HDFS performance
 
Safely Protect PostgreSQL Passwords - Tell Others to SCRAM
Safely Protect PostgreSQL Passwords - Tell Others to SCRAMSafely Protect PostgreSQL Passwords - Tell Others to SCRAM
Safely Protect PostgreSQL Passwords - Tell Others to SCRAM
 
Redis - for duplicate detection on real time stream
Redis - for duplicate detection on real time streamRedis - for duplicate detection on real time stream
Redis - for duplicate detection on real time stream
 
SequoiaDB Distributed Relational Database
SequoiaDB Distributed Relational DatabaseSequoiaDB Distributed Relational Database
SequoiaDB Distributed Relational Database
 
OpenStack LA meetup Feb 18, 2015
OpenStack LA meetup Feb 18, 2015OpenStack LA meetup Feb 18, 2015
OpenStack LA meetup Feb 18, 2015
 
Juggling Chainsaws: Perl and MongoDB
Juggling Chainsaws: Perl and MongoDBJuggling Chainsaws: Perl and MongoDB
Juggling Chainsaws: Perl and MongoDB
 
Get Your Insecure PostgreSQL Passwords to SCRAM
Get Your Insecure PostgreSQL Passwords to SCRAMGet Your Insecure PostgreSQL Passwords to SCRAM
Get Your Insecure PostgreSQL Passwords to SCRAM
 
Work Stealing For Fun & Profit: Jim Nelson
Work Stealing For Fun & Profit: Jim NelsonWork Stealing For Fun & Profit: Jim Nelson
Work Stealing For Fun & Profit: Jim Nelson
 
ELK stack at weibo.com
ELK stack at weibo.comELK stack at weibo.com
ELK stack at weibo.com
 
Everything as Code with Terraform
Everything as Code with TerraformEverything as Code with Terraform
Everything as Code with Terraform
 
Mongo Sharding: Case Study
Mongo Sharding: Case StudyMongo Sharding: Case Study
Mongo Sharding: Case Study
 
Valtech - Big Data & NoSQL : au-delà du nouveau buzz
Valtech  - Big Data & NoSQL : au-delà du nouveau buzzValtech  - Big Data & NoSQL : au-delà du nouveau buzz
Valtech - Big Data & NoSQL : au-delà du nouveau buzz
 
Leveraging Hadoop in your PostgreSQL Environment
Leveraging Hadoop in your PostgreSQL EnvironmentLeveraging Hadoop in your PostgreSQL Environment
Leveraging Hadoop in your PostgreSQL Environment
 
Open Source Logging and Metric Tools
Open Source Logging and Metric ToolsOpen Source Logging and Metric Tools
Open Source Logging and Metric Tools
 
Using MongoDB and Python
Using MongoDB and PythonUsing MongoDB and Python
Using MongoDB and Python
 
Elastic search integration with hadoop leveragebigdata
Elastic search integration with hadoop   leveragebigdataElastic search integration with hadoop   leveragebigdata
Elastic search integration with hadoop leveragebigdata
 
NOVA Data Science Meetup 5/10/2017 - Presentation Building a gigaword corpus
NOVA Data Science Meetup 5/10/2017 - Presentation Building a gigaword corpusNOVA Data Science Meetup 5/10/2017 - Presentation Building a gigaword corpus
NOVA Data Science Meetup 5/10/2017 - Presentation Building a gigaword corpus
 
新浪微博开放平台中的 Redis 实践
新浪微博开放平台中的 Redis 实践新浪微博开放平台中的 Redis 实践
新浪微博开放平台中的 Redis 实践
 

Ähnlich wie Redispresentation apac2012

Redis+Spark Structured Streaming: Roshan Kumar
Redis+Spark Structured Streaming: Roshan KumarRedis+Spark Structured Streaming: Roshan Kumar
Redis+Spark Structured Streaming: Roshan Kumar
Redis Labs
 
대용량 데이타 쉽고 빠르게 분석하기 :: 김일호 솔루션즈 아키텍트 :: Gaming on AWS 2016
대용량 데이타 쉽고 빠르게 분석하기 :: 김일호 솔루션즈 아키텍트 :: Gaming on AWS 2016대용량 데이타 쉽고 빠르게 분석하기 :: 김일호 솔루션즈 아키텍트 :: Gaming on AWS 2016
대용량 데이타 쉽고 빠르게 분석하기 :: 김일호 솔루션즈 아키텍트 :: Gaming on AWS 2016
Amazon Web Services Korea
 

Ähnlich wie Redispresentation apac2012 (20)

Developing a Redis Module - Hackathon Kickoff
 Developing a Redis Module - Hackathon Kickoff Developing a Redis Module - Hackathon Kickoff
Developing a Redis Module - Hackathon Kickoff
 
Redis for Security Data : SecurityScorecard JVM Redis Usage
Redis for Security Data : SecurityScorecard JVM Redis UsageRedis for Security Data : SecurityScorecard JVM Redis Usage
Redis for Security Data : SecurityScorecard JVM Redis Usage
 
Mini-Training: Redis
Mini-Training: RedisMini-Training: Redis
Mini-Training: Redis
 
Redis
RedisRedis
Redis
 
Introduction to Redis
Introduction to RedisIntroduction to Redis
Introduction to Redis
 
Redis and it's data types
Redis and it's data typesRedis and it's data types
Redis and it's data types
 
Extend Redis with Modules
Extend Redis with ModulesExtend Redis with Modules
Extend Redis with Modules
 
Introduction to redis
Introduction to redisIntroduction to redis
Introduction to redis
 
Redis. Performance on custom searches. Production screw up
Redis. Performance on custom searches. Production screw upRedis. Performance on custom searches. Production screw up
Redis. Performance on custom searches. Production screw up
 
Redis
RedisRedis
Redis
 
R the unsung hero of Big Data
R the unsung hero of Big DataR the unsung hero of Big Data
R the unsung hero of Big Data
 
Redis Use Patterns (DevconTLV June 2014)
Redis Use Patterns (DevconTLV June 2014)Redis Use Patterns (DevconTLV June 2014)
Redis Use Patterns (DevconTLV June 2014)
 
Redis 101
Redis 101Redis 101
Redis 101
 
Supa fast Ruby + Rails
Supa fast Ruby + RailsSupa fast Ruby + Rails
Supa fast Ruby + Rails
 
Redis+Spark Structured Streaming: Roshan Kumar
Redis+Spark Structured Streaming: Roshan KumarRedis+Spark Structured Streaming: Roshan Kumar
Redis+Spark Structured Streaming: Roshan Kumar
 
대용량 데이타 쉽고 빠르게 분석하기 :: 김일호 솔루션즈 아키텍트 :: Gaming on AWS 2016
대용량 데이타 쉽고 빠르게 분석하기 :: 김일호 솔루션즈 아키텍트 :: Gaming on AWS 2016대용량 데이타 쉽고 빠르게 분석하기 :: 김일호 솔루션즈 아키텍트 :: Gaming on AWS 2016
대용량 데이타 쉽고 빠르게 분석하기 :: 김일호 솔루션즈 아키텍트 :: Gaming on AWS 2016
 
(DAT407) Amazon ElastiCache: Deep Dive
(DAT407) Amazon ElastiCache: Deep Dive(DAT407) Amazon ElastiCache: Deep Dive
(DAT407) Amazon ElastiCache: Deep Dive
 
How to automate all your SEO projects
How to automate all your SEO projectsHow to automate all your SEO projects
How to automate all your SEO projects
 
Boosting Machine Learning with Redis Modules and Spark
Boosting Machine Learning with Redis Modules and SparkBoosting Machine Learning with Redis Modules and Spark
Boosting Machine Learning with Redis Modules and Spark
 
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
 

Kürzlich hochgeladen

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 

Kürzlich hochgeladen (20)

Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 

Redispresentation apac2012

  • 1. Tutorial Talk By: Ankur Gupta http://uptosomething.in
  • 2. What is Redis? Overview • Few of the fundamental and commonly used data types in software would be string, list, hash, set. • Redis is an in-memory key-value store. It allows you to add/update/delete the above data types as values to a key. i.e. Key:Value aka “String”:<Data Type>. Thus named as a data structure server. • Redis is free, fast, easy to install ,scales well as more data is inserted/operation performed. • Following languages have libraries that communicate with redis “ActionScript, C, C++, C#, Clojure, Common Lisp, Erlang, Go, Haskell, haXe, Io, Java, server-side JavaScript (Node.js), Lua, Objective-C, Perl, PHP, Pure Data, Python, Ruby, Scala, Smalltalk and Tcl “ Wikipedia
  • 3. Why Should Redis Matter? Features/Use Case • Caching server, ( e.g. memcache equivalent) • Queue, (store user request that would take time to compute e.g. image resize on flickr/picasa) • User Clicks (Counting), (upvote/downvote on reddit) • Real Time Analytics for Stats, (No of users logged into chat ) • Publish – Subscribe, ( e.g. Quora/Facebook Notification system) Modern web application require web developer to build software that responds in milliseconds and scale as no of users/data/operations increases e.g. increase in pageviews. Yes, You can use a database like MySql to achieve all the above but wouldn’t it be faster to hit RAM then HDD ?. Using Redis developers can satisfy architectural paradigm found in modern web application development.
  • 4. Who made Redis? Motivation, Support, Future Salvatore Sanfilippo is founder developer of Redis since April 2009, • Read Redis Manifesto to understand motivation behind redis, • Vmware is the sponsor of redis project with few employees working full time on redis, • Redis related questions on stackoverflow and answers thereof gives you a sense of community support and usage. • Why ? Beneficial to invest time mastering tools that are supported and will be there tomorrow.
  • 5. Who is using Redis ?
  • 6. Installing Redis Linux System – Installation from Source ● Go to http://redis.io/download official download page ● Download source code of Current Stable Release - 2.4.14 http://redis.googlecode.com/files/redis-2.4.14.tar.gz ● Extract the source code $ tar -xvf redis-2.4.14.tar.gz ● Redis is coded in C with dependencies being gcc and libc. If your computer doesn't have the same please use package manager and install the same. ● Execute the below commands in the directory where redis code is extracted $ make $ make test $ sudo make install ● You have Redis on your machine …
  • 7. Running Redis After compilation you have following binaries generated a) redis-cli – Command line to talk to redis server b) redis-server - Redis Server c) redis-benchmark - is used to check Redis performances d) redis-check-aof - Fix corrupted append only data files. e) redis-check-dump - Useful in the event of corrupted data files. Server $ redis-server OR $ redis-server /path/to/redisconfig.conf Check redis.conf for default redis configuration used when no separate config file is given. ( We will take a tour of the configuration file ahead )
  • 8. Playing with redis-cli Start Server $ redis-server Help $ redis-cli --help Can the command line client listen to server $ redis-cli ping Start redis-cli interactive mode $ redis-cli Let us try using creating the following data structures using redis-cli a) String b) hashes, c) lists, d) sets, e) sorted sets.
  • 9. String $ redis-cli redis 127.0.0.1:6379> set aKey aValue OK redis 127.0.0.1:6379> get aKey "aValue" redis 127.0.0.1:6379> set PyConDate "8th - 9th June 2012" OK redis 127.0.0.1:6379> get pycondate (nil) redis 127.0.0.1:6379> get PyConDate "8th - 9th June 2012" redis 127.0.0.1:6379> append PyConDate ": Singapore" (integer) 30 redis 127.0.0.1:6379> get PyConDate "8th - 9th June 2012: Singapore" redis 127.0.0.1:6379> exists PyConDate (integer) 1
  • 10. More String redis 127.0.0.1:6379> setex boardingpasstosingapore 10 "Ankur Gupta" OK redis 127.0.0.1:6379> get boardingpasstosingapore "Ankur Gupta" redis 127.0.0.1:6379> get boardingpasstosingapore (nil) redis 127.0.0.1:6379> set attendance "0" OK redis 127.0.0.1:6379> incr attendance (integer) 1 redis 127.0.0.1:6379> get attendance "1" redis 127.0.0.1:6379> incr attendance (integer) 2 redis 127.0.0.1:6379> get attendance "2" redis 127.0.0.1:6379> set attendance "A" OK redis 127.0.0.1:6379> incr attendance (error) ERR value is not an integer or out of range
  • 11.
  • 12. Key 101 ? ● Are Byte Array. Thus binary safe. ● Obvious : Short key consume less memory vis a vi long keys. How verbose is good you decide. e.g. “authuser:14573:cacheenable” or “au:14573:ce” ● Good practise to create your key naming convention in codebase and sticking to it. redis 127.0.0.1:6379> set " " "blank key ?" OK redis 127.0.0.1:6379> get " " "blank key ?" redis 127.0.0.1:6379> get " " (nil) redis 127.0.0.1:6379> set does work "no" (error) ERR wrong number of arguments for 'set' command redis 127.0.0.1:6379> set "does work" "yes" OK
  • 13.
  • 14.
  • 17.
  • 18. Exercise a) Download the file http://uptosomething.in/sghistorytimeline.csv b) Copy the first complete line from the file i.e. "3rd century","Early Chinese account of Singapore describes the island of Pu Luo Chung" Take first column as key and second as value. Create a string using redis, c) Use the 6th and 7th line and create a list with 1819 as key and respective historical events as list elements, d) Use the 6th and 7th line and create a sorted set. Show events in reverse chronological order, e) Use the line no 112 onwards till EOF and create a hash such that it takes Year as hashname, month+day as key, and historical event as value, f) Find what events happened in the month of june and create any datastructure you please with them such that they expire when the event day is over. e.g. event on june 12 will get over when june 13th arrives thus will expire.
  • 19. Installing Redis Python Library https://github.com/andymccurdy/redis-py redis-py is versioned after Redis. For example, redis-py 2.0.0 should support all the commands available in Redis 2.0.0. $ cd andymccurdy-redis-py-d2a7156/ $ python2.7 setup.py build $ sudo python2.7 setup.py install redis-py exposes two client classes that implement these commands. The StrictRedis class adhere to the official command syntax/names with few exceptions. The library also offers another class that gives backward compatibility with commands that are now deprecated.
  • 20. Installing Redis Python Libraries https://github.com/andymccurdy/redis-py redis-py is versioned after Redis. For example, redis-py 2.0.0 should support all the commands available in Redis 2.0.0. $ cd andymccurdy-redis-py-d2a7156/ $ python2.7 setup.py build $ sudo python2.7 setup.py install redis-py exposes two client classes that implement these commands. The StrictRedis class adhere to the official command syntax/names with few exceptions. The library also offers another class that gives backward compatibility with commands that are now deprecated.
  • 21. Redis Python Library Code Snippets >>> import redis >>> r = redis.StrictRedis(host='localhost', port=6379) >>> r.set('sg', 'singapore') >>> r.get('sg') 'singapore' >>> r.rpush('cities', 'Mumbai') >>> r.lpush('Singapore') >>> r.lrange('cities', 0 , 1) ['Mumbai', 'Singapore'] >>> r.llen('cities') 2
  • 22. Redis Python Library Code Snippets >>> r.sadd("interpretedlanguages", "Ruby") 1 >>> r.sadd("interpretedlanguages", "Perl") 1 >>> r.sadd("interpretedlanguages", "Basic") 1 >>> r.smembers("interpretedlanguages") set(['Python', 'Basic', 'Ruby', 'Perl']) >>> >>> r.sadd("interpretedlanguages", "Perl") 0 >>> >>> r.sismember("interpretedlanguages","Java") False >>> r.sismember("interpretedlanguages","Basic") True
  • 23. Redis Python Library Code Snippets >>> r.zadd("social", 876, "blogpost:facebook:likes") 1 >>> r.zadd("social", 2345, "blogpost:diggs:count") 1 >>> r.zadd("social", 67, "blogpost:twitter:tweets") 1 >>> >>> data = r.zrange("socialinteraction", 0, -1, withscores=True) >>> type(data) <type 'list'> >>> data[::-1] [('blogpost:diggs:count', 2345.0), ('blogpost:facebook:likes', 876.0), ('blogpost:gplus:likes', 345.0), ('blogpost:twitter:tweets', 67.0)] >>> ●
  • 24. Redis Python Library Code Snippets ● >>> r.hset("travelchecklist:singapore", "airlines", "Air-India") ● 1 ● >>> r.hset("travelchecklist:singapore", "currency", "1070") ● 1 ● >>> r.hkeys("travelchecklist:singapore") ● ['airlines', 'currency'] ● >>> r.hvals("travelchecklist:singapore") ● ['Air-India', '1070'] ● >>> r.hgetall("travelchecklist:singapore") ● {'currency': '1070', 'airlines': 'Air-India'}
  • 25. Exercise a) Download the file http://uptosomething.in/sghistorytimeline.csv Write a Python program that uses the redis module and try to do whatever cool idea comes in your mind with the above data and redis.
  • 26. Creating Live Counters import redis r = redis.StrictRedis(host='localhost', port=6379) def vote(objectid, is_up_vote): """ is_up_vote == true means up vote else down vote """ if not r.exists(objectid): r.set(objectid, 1) return 1 if is_up_vote: return r.incr(objectid, 1) else: return r.decr(objectid, 1) print vote("people who like the redis talk", True) print vote("people who like the redis talk", False) print vote("people who like the redis talk", True) print vote("people who like the redis talk", True) print vote("people who like the redis talk", False)
  • 27. Real-time notification backend ● Facebook User receives notification when his/her mention is made i.e. @user ● So we have a) Message Text b) User who wrote the message c) Time-stamp when the message was written d) Other Users who were mentioned in that message.
  • 28. Real-time notification backend Lets denote ● msgsourceuser = User who wrote the message msgtxt = Actual message timestamp = In seconds when the msh was written since epoch ● Userlist = List of users for whom the message is meant Ideas ● Hashes – Timestamp → user from UserList → msgtxt:msgsourceuser ● Sorted Sets – Msgsourceuser → msgtxt:userlist → timestamp (score) ● Redis Pub / Sub – ???
  • 29. Real-time notification backend import redis rc = redis.Redis() psredis = rc.pubsub() rc.publish('statusupdate', 'In Singapore with @user,@user2,@user3') ● ______________________________________________________________________ import redis rc = redis.Redis() psredis = rc.pubsub() psredis.subscribe('statusupdate') for item in psredis.listen(): # problem listen is blocking call print item['channel'] print item['data']
  • 30. Naive Redis Based Queue ● Let us audit an open source redis queue implementation and see what is happening inside …
  • 31. Auto-complete using redis Salvatore Sanfilippo Auto-complete implementation's code review https://gist.github.com/925979/b4689bfd8b0bc0408cd61efe674ea305f06524b9 ( The above is python port of original ruby code )
  • 32. Redis In Production Environment ● Daemon mode + init script ● Server options and
  • 33. Redis In Production Environment ● Daemon mode + init script ● Server options and config file