Redis

Using Redis with Ruby

Redis is an in-memory, key-value pair database that is highly flexible in a wide range of scenarios. In addition, it provides a collection of primitive types that make it versatile as a caching mechanism or message broker.

Let us learn how we can connect Redis with Ruby application.

Requirements

Basic knowledge in working with Redis and Ruby.

Install Ruby interpreter and Redis server on your system.

Installing Redis Ruby Client

To connect Ruby with Redis, we need to install a Redis Ruby client. For this article, we will use redis-rb gem.

https://github.com/redis/redis-rb

Open the terminal and enter the command below to install:

$ gem install redis

Once installed, we can proceed to connect redis with our app.

Connecting Ruby to Redis

Create a working directory and add the file to hold your code.

$ mkdir redis_rb && cd redis_rb && touch main.rb

Open the file and add the code as shown below:

require redis
# connect with default
redis = Redis.new
# connect with password ro database 0
redis = Redis.new(url: "redis://:[email protected]:6379/0")

In the code above, we start to import the required modules.

Next, we connect to Redis using the new method. If your Redis server is secured with a password, opt for connection method 2.

Testing Redis Connection

To test the connection, you can run redis.ping method as shown:

redis.ping

This should return PONG upon successful connection.

Setting Ruby Key-Value pair

Create a new key-value pair to the database by using the set command as:

redis.set("key", "value")

This should return like this:

# => "OK"

Getting Ruby Value

To get a value associated with a key in Redis, use the get method as shown:

redis.get("key")

This should return the value associated with the key:

# => "value"

Setting Ruby Expiring Key

To create a key-value pair with expiry duration, use the setex method as:

redis.setex("expiry_key", 60,”expiry_value)

The above should create a key with an expiry duration of 60 seconds.

Conclusion

In this article, you learn how to connect your Redis database to a Ruby application through a comprehensible walk-through of the whole process. Check the docs to learn more.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list