Getting Started With Redis

tudip-logo

Tudip

28 March 2019

Introduction to Redis

Redis is an open source (with minimal restrictions on the use and distribution of the software), memory resident database store which especially relies on the main memory unit for computer data storage. Redis can be used as a storing database, cache, message validation, transformation, and routing. Also in addition to the above benefits, the data model of Redis allows data to be stored as a key-value pair, which also supports a wide range of data structures, such as Lists, Strings, Hashes, Sets (unranked group of all the different values), sorted sets (ranked group of all the different values) etc. The in-memory feature of Redis makes it extremely fast to access the data as it uses a single-threaded event loop, and therefore in choosing the database, Redis is frequently used as cache storage and considered as a secondary database to support the primary database and to handle some time efficient operation.

Why use Redis?

  • The ability to work with different types of data and due to its blazingly fast speed as it uses the volatile memory.
  • It even stores the data after a reboot of the system, unlike Memcached which makes it a first choice.
  • It provides us the ability to save multiple requests to the cloud database servers and eventually making a cost-effective option too.
  • It is open source, supported by various languages and stable which makes it developer independent.
  • Redis is having capabilities of replication, transactions, a server-side scripting language (Lua), and different modes of disk persistence.
  • The zero-latency proxy utilizes many mechanisms for rising performance, including just-in-time pipelining, socket connections, connection pooling, and multiplexing.
  • Transactional support: In Redis, it can never happen that another transaction will overlap a pending request, as Redis transaction commands are executed as a single isolated operation. See Transactions – Redis.
  • Pub/Sub: you’ll be able to keep track of subscribers and what info they’re curious about. We can use the SUBSCRIBE, UNSUBSCRIBE, and PUBLISH commands of Redis which will not allow the user to issue any other commands and also can be configured the actions from the program.
  • Queues: We can use the normal queue type data structure, Redis has blocking queue commands as well which blocks the requested connection if there are it found no elements to pop.
  • Real-time analysis of events(stats, anti-spam etc) – With the use of Redis primitives implementation of a real-time tracking filtering system or a spam filtering system has been made really simple.
  • Order by user votes and time: A functionality similar to a logic of the leaderboard type, where the score get updated over time.

The underlying implementation of the data types in Redis:

  • Strings: Implemented using a C dynamic string library so that we don’t have to spend on the allocations in any append operations. This way we will be having O(N) appends, for instance, instead of having a quadratic behavior.
  • Lists: Linked lists are used to implement this.
  • Sets and Hashes: Hash tables were used to implement and compile sets.
  • Sorted sets: Balanced trees (skip lists) were used to implement sorted sets.

Install Redis on Ubuntu:

  • Step-1: Log in to your Ubuntu server as a non-root sudo user and follow the below steps.
  • Step-2: Install the dependencies in the system:
    • sudo apt update
    • sudo apt full-upgrade
    • sudo apt install build-essential tcl
  • Step-3: Installing redis in the system:
    • Download the latest version of Redis via this link or also can use the below command to get the tar file.
    • Create a temporary folder for it, ex: /home/redis-stable directory.
    • Move to the created folder cd /home/redis-stable
    • Extract the file tar xzvf <path>/redis-stable.tar.gz
    • Change into the newly created folder cd redis-stable and build it with
      • make
      • make test (It will test the build file).
      • sudo make install
    • cd redis-stable/utils and run ./install_server.sh
  • Step-4: Configuring redis:
    • Create a configuration directory for redic in the etc directory:
      • sudo mkdir /etc/redis
    • Move sample redis configuration file:
      • sudo cp /home/<username>/redis-stable/redis.conf /etc/redis
    • Edit the file using vim or we can use any other text editor (like nano, Gedit, Atom, KWrite etc.):
      • sudo vim /etc/redis/redis.conf
    • Update the below changes in the configuration file:
      • supervised no to supervised systemd
      • dir ./ to dir /var/lib/redis # for persistent information dump

Redis2-1024x224  Redis1-1024x158

  • Step-5: Set up the systemd unit file:
    • sudo vim /etc/systemd/system/redis.service
    • Add the below text to it (Maintain the exact formatting)
      • [Unit] Description=Redis In-Memory Data Store After=network.target [Service] User=redis Group=redis ExecStart=/usr/local/bin/redis-server /etc/redis/redis.conf ExecStop=/usr/local/bin/redis-cli shutdown Restart=always [Install] WantedBy=multi-user.target

Redis5-1024x185

  • Step-6: Set up redis user, groups and directories:
    • create redis user and cluster with same ID however no home directory:
      • sudo adduser –system –group –no-create-home redis
      • sudo mkdir /var/lib/redis # create directory
      • sudo chown redis:redis /var/lib/redis # provide redis the ownership of /var/lib/redis
      • sudo chmod 770 /var/lib/redis # adjust permission
  • Step-7: Testing the redis setup:
    • Command to start redis service
      • sudo systemctl start redis
    • Command to check status of redis:
      • systemctl status redis
      • The output of a successful running would be as below:
        • ● redis.service – Redis In-Memory Data Store

Loaded: loaded (/etc/systemd/system/redis.service; disabled; vendor preset: enabled) Active: active (running) since <time> Main PID: 1878 (redis-server) Tasks: 4 (limit: 4915) CGroup: /system.slice/redis.service └─1878 /usr/local/bin/redis-server 127.0.0.1:6379

Redis4-1024x576

  • Step-8: Testing the instance:
    • Connect:
    • redis-cli
  • Step-9: Test the connectivity at prompt:
    • 127.0.0.1:6379> ping # return log PONG
  • Step-10: Check for setting keys ability in the redis environment:
    • 127.0.0.1:6379> set test “Redis initiated” # result ok
  • Step-11: Getting the value for the above set key:
    • 127.0.0.1:6379> get test # return log “Redis initiated”
  • Step-12: To exit the redis environment:
    • 127.0.0.1:6379> exit
  • Step-13: To check if redis is running as expected, restart redis and then check for the above set key values by running the steps i, iv, and v. Then check if the test values are cached, hence it’s working as expected:
    • sudo systemctl restart redis
  • Step-14: Use the below command to start redis at the system boot time:
    • sudo systemctl enable redis

Redis3-1024x576

Setting up redis-py:

Commands to follow:

  • Install redis-py
    • pip install redis
  • Start redis-cli on some shell, thus we were able to relate our python redis commands and default redis command.
    • sudo systemctl start redis
    • systemctl status redis
    • redis-cli
      • Set a variable in redis cli
        • set testkey testvalue
        • get testkey
  • Run python console and import redis
    • python
    • import redis
    • test = redis.StrictRedis() # We have created an instance of StrictRedis. which is needed for communication with redis-server.
    • Try getting “testkey”, which we set using redis-cli, from Python
      • test.get(“testkey”)
    • To set a value from python we can use the set command
      • test.set(“anothertestkey”, “anothertestvalue”)
  • We can increment a number value in the redis key and also we can set the margin to increse the value by using the INCR and INCRBY commands respectively
    • test.set(“testnum”, 17)
    • test.incr(“testnum”) will increment the number by 1 which will give an output of 18.
    • test.incrby(“testnum”, 12) will increase the number by 12 and will return 29.
  • DELETE
    • test.delete(“anothertestkey”) will delete the key value pair and return ‘null’ when trying to fetch.
  • EXPIRE
    • We can set the expiry time of a cached key-value pair in redis.
      • test.expire(“testnum”, <time in sec(ex: 10)>) – This command will delete the key-value pair after 10 seconds of setting.
  • lpush and rpush:
    • We can use lpush to push a value to the left of list.
      • test.lpush(“testlist”, 2, 3)
    • rlist is used to right push the item into the list.
  • hmset and hgetall:
    • test.hmset(“user”, {‘name’: ‘tudip’, ‘age’: 09})
    • test.hmset(“user_one”, {‘name’: ‘peter’, ‘age’: 17})
    • test.hgetall(“user_one”) will return all the details associated with the key.
    • test.hget(“user_one”, “name”) will return only the name associated with teh key.

Conclusion

Hope this article was helpful for you to learn about how to install redis on an Ubuntu server and working with redis for python. If you have found this article helpful and worthy then do share it with your other friends and circle too.

Happy Blogging!!

Request a quote