Tuesday 1 November 2016

Storing files in redis

In Redis, data can be stored in various types like String, Hash(HashMap), Set, SortedSet, List etc.
Today we will see the java code to store a file in redis.
File is normally stored in the form of byte array in Redis.
First we start the redis server by executing the below in redis home directory.
src/redis-server


This will start the server.
We can see that there is no data in it by executing the "dbsize" command.


The below java code for uploading the file uses Jedis client, although Lettuce client can also be used.
The code saves redis-3.2.4.tar.gz in the redis, but any other file can also be stored in it.
It will save the byte array in redis. further it will get the data from redis and store it as a file with a different name on the disk.

<pre class="brush: java">
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

import redis.clients.jedis.Jedis;

public class RedisUploadFile {

public static void main(String[] args) throws IOException {
String host = "localhost";
int port = 6379;
String filePath = "/Users/test/redis/";
String fileName = "redis-3.2.4.tar.gz";
String newFileName = "new_"+ fileName;
Jedis jedis = new Jedis(host, port);
byte[] bytes = Files.readAllBytes(new File(filePath+fileName).toPath());
byte[] key =
(filePath+fileName).getBytes();
System.out.println("Setting bytes of length:" + bytes.length + " got from file " + filePath + fileName + "in redis.");
jedis.set(key, bytes);

byte[] retrievedBytes = jedis.get(key);
System.out.println("Saving data in file " + filePath + newFileName);
Files.write(Paths.get(filePath+newFileName), retrievedBytes);
System.out.println("Done.");
jedis.close();

}


}
</pre>

After the above code is run, it will save the tar file in the redis, and will download it from redis and save it in a separate name.

After that, we can see that the data is also stored in redis by executing "dbsize" command, which returns 1, "keys *" command which returns the key.
Getting the key returns the stored binary representation of the file.


Also, we can see that the file is also created on the file system.




1 comment:

  1. hi, i have a doubt whether its possible to send binary data in redis?

    ReplyDelete