- Learning Redis
- Vinoo Das
- 1883字
- 2025-02-21 03:07:48
Hello World in Redis
This section will excite programmers the most. Let's get our hands dirty and punch in some code. But, before that, we have to understand that Redis works on a client-server model and uses the Redis protocol to communicate with the server. For the client to connect to the server, the client has to know the location of the server. For this section, I am going to show samples using the redis-cli and Java clients.
Hello World using redis-cli
Start the Redis client Command Prompt (make sure that the server is running). Type in the following commands, as shown in the following screenshot, and see the outcome:

Trying simple Set and Get commands using the Redis client
There are three parts to the command we wrote. They are explained as follows:
Set
: This command is used to set a value in the Redis serverMSG
: This is the key for the message to be stored in the Redis serverHello World
: This is the value stored in the server for theMSG
key
So, this clears a pattern that we have to keep in mind when working with Redis. Remember, Redis is a key-value NoSQL datastore. The syntax for this is COMMAND <space> KEY <space> VALUE
.
Continuing with the Hello world
program, we will do something more. Let's type in set MSG Learning Redis
we get an error message, and when we type set MSG "Hello World", the value that the server is going to return is OK
:

Overwriting the key with a new value
The old value is overwritten with the new value for the given key. Let's add another dimension to this sample, that is, open another client to the already existing client Command Prompt we have opened. In the second Command Prompt, let's type the command and key as get MSG
. The value it's going to return is again "Hello World"
. This is shown in the following screenshot:

Writing in one client and reading it in another client
At this point, one will wonder what happens if we write a number as a value, maybe to store some timestamp, instead of a string.
Let's have the new command's key value as set new_msg 1234
, and when we write the command key to retrieve the value as get new_msg
, we get the result "1234"
. Notice the double quotes around the value; this tells us something more about Redis and the way it stores the data, that is, every value stored in Redis is of the type string:

Getting an integer value as a string
The redis-cli tool comes in handy for debugging the solution and executing commands to check the system and solution.
The next question that needs to be answered is how to access Redis programmatically.
Hello World using Java
In the previous section, you learned how to work with the redis-cli.exe
application in order to connect to the Redis server. In this section, we will introduce a Java client API to connect to the Redis server and fire some commands. In all reality, for Redis to be used in a solution, it needs an API to connect to the server. There are some other attributes that an API needs rather than just connecting to the server, passing on commands and command parameters, and returning the result, but we will cover this in later chapters.
The Java client API chosen to demonstrate the examples in this book is Jedis.
There are three steps to run the "Hello World"
example in Java. They are explained in the sections that follow.
Installing Jedis and creating an environment
Jedis is Apache License 2.0 Java client for Redis. This client will be used for the samples demonstrated in this book. So, the most important thing to get for this client is that you need to make sure that you have a development environment. For this book, we have chosen Eclipse as the development environment (http://www.eclipse.org/downloads/). If you don't have Eclipse, you can grab a copy and install it (it's free and licensed). The examples of this book will work equally well with other integrated development environments. Now, perform the following steps:
- Open Eclipse and create a project called
learning redis
, as shown in the following screenshot:Creating a project in Eclipse
- If you are using Maven, then add the following dependencies for Jedis:
Maven dependencies for Jedis
If you are using any other build tools, follow the instructions to add the dependency for Jedis accordingly.
Writing the program
The following program in Java is written with Redis as a datastore:
package org.learningredis.chapter.two; import redis.clients.jedis.*; public class HelloWorld { private JedisPool pool = new JedisPool(new JedisPoolConfig(), "localhost"); private void test() { try { Jedis jedis = pool.getResource(); jedis.set("MSG", "Hello World"); String result = jedis.get("MSG"); System.out.println(" MSG : " + result); pool.returnResource(jedis); } catch (Exception e) { System.err.println(e.toString()); }finally{ pool.destroy(); } } public static void main(String args[]) { HelloWorld helloWorld = new HelloWorld(); helloWorld.test(); } }
Make sure that your Redis server is up and running. In this sample, the port used here is the default port 6379.
Let's understand, step by step, what we are doing in the program:
- We are setting up a pool of connections to connect to the Redis server. The pool is configured to the default IP address to which the server will bind.
- We take a resource from the pool (the client stub that wraps the connection).
- We set the key-value into it. This will push the value to be inserted into the Redis datastore.
- We ask/get the value based on the key. In this case, the value inserted against the key in the previous step.
- We return the resource into the pool for reuse and close the pool.
Shutting down the server
As with any server, shutting down the server gracefully is very important. There are a couple of things that need to be kept in mind before you shut down any Redis server, which are explained here:
- Close all the client connections. For our Java program, we indicate the client to close all the connections by writing
"pool.destoy();"
. - The next thing that we need to do is to go to the client prompt and order a server shutdown.
- If you intend to use Redis as a cache server, then the data it holds need not be saved. In this case, just type
shutdown nosave
. This will flush out all the data in the memory and free it. - If you intend to save the data so that you can use it later, then you have to pass the
shutdown save
command. This will persist the data in theRDB
file even if no save points are configured, which we will cover in later chapters.
The following figure shows what happens in the example from the resource life cycle perspective:

Managing a resource for the Jedis client
We have three resources that we have to consider during the life cycle. They are explained as follows:
- Jedis connection pool: This is the pool that should get created when the system/application starts up. This allocates the resources for the pool. The application server life cycle should manage the life cycle of the pool.
- Connection: In Jedis, the client stub created wraps the connection and acts as a client for Redis. In the program listed earlier, the client stub is referenced as Jedis which is obtained in the
pool.getResource()
statement. - Request life cycle: This is where the command is getting executed. So, what is basically happening here is that using the Redis protocol, the command and the payload is being sent to the server. The payload consists of either the key, if it's a "getter," or the key and the value, if it's a "setter". The life cycle is managed with a positive acknowledgement from the server. It can be a success or an exception if it's a failure. In a way, we don't need explicit life cycle management for this statement.
How do we manage connections in Jedis, and what will happen if we don't manage them?
The answer to the question what will happen if we don't manage it is simple. The pool will run out of connections and the client application will suffer. We have seen connection-related problems in areas such as JDBC, where the application suffers when there are no connections for the client to connect to server. It's always the server that reserves the memory for a connection, and closing the connection is an indication for the server to release the memory.
The answer to the question how do we manage connections in Jedis is a bit more interesting and requires some code changes. We will take the previous code example and make changes to it, where we will handle connection resource management. For the following example, I am adding a wrapper, but in your applications, you can have more exotic recipes to address the concern mentioned. That is, you can use Spring to inject a connection or use cglib
to dynamically create a proxy, which will set the connection before the command and return the connection after the command.
The following code is for the new Hello World program, which is now called HelloWorld2
:
package org.learningredis.chapter.two; public class Helloworld2 { JedisWrapper jedisWrapper = null; public Helloworld2() { jedisWrapper = new JedisWrapper(); } private void test() { jedisWrapper.set("MSG", "Hello world 2 "); String result = jedisWrapper.get("MSG"); System.out.println("MSG : " + result); } public static void main(String[] args) { Helloworld2 helloworld2 = new Helloworld2(); helloworld2.test(); } }
The following is the wrapper code that handles the connection:
package org.learningredis.chapter.two; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; public class JedisWrapper { static JedisPool pool = new JedisPool(new JedisPoolConfig(), "localhost");");");");"); public void set(String key,String value){ Jedis jedis = pool.getResource(); jedis.set(key, value); pool.returnResource(jedis); } public String get(String key){ Jedis jedis = pool.getResource(); String result = jedis.get("MSG"); ");");");"); pool.returnResource(jedis); return result; } }
Two things becomes clear in this case, which are explained here:
- We don't have to manage the connection/resources, since this will be taken care of by the
wrapper
class - The number of lines of code gets reduced, since we don't have to repeat the code for resource management
Loading a test Hello World program in Redis
Well, you have seen an example of a Hello world
program in Java and the command line. But it's always good to add a load test dimension to your Hello World
program. Redis comes with a tool called redis-benchmark
, which can be found in the release folder.
The following command is going to make 100,000 calls to the Redis server:

Load testing of Hello World
The result is the total number of requests handled in a second for your machine. This tool comes in very handy for load testing your target environment. This is the snapshot of the result I got when I executed it in my Windows machine, and this will vary depending on the configuration of your machine and OS:

Tool performing the load test
What happened over here is that redis-benchmark
opened up 50 parallel connections to the Redis server and fired 10,000 requests. The requests contain Redis commands and a 3-byte payload. The approximate results get printed for analysis; in my case, the 10,000 Set
commands took an overall of 0.30 seconds, that is, 33,670 requests were catered to per second.