Quick Start Programming Guide for redis using java client Jedis
We aggregate and tag open source projects. We have collections of more than one million projects. Check out the projects section.
Redis is an open source (BSD licensed), in-memory data structure store, used also as a database cache and message broker. It supports data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperloglogs, geospatial indexes with radius queries and streams. This article explains about how to communicate with Redis using Java client Jedis.
Install Redis on Windows or Linux. Refer the post to know how to install and setup Redis in Windows and Linux.
Jedis is small and fast redis client. It is easy to use all the supported data types of redis with its exposed API methods. Usage has been described based on the best pratices of redis.
Connect to Redis Server
Jedis client can be created by passing hostname and port number. But it is always a best practise to use connection pool. In case of multi threaded environment, it is good to reuse the connections. To create the pool, the pool configuration and connection timeout (in ms) also need to be added as shown below.
JedisPool jedisPool = new JedisPool(new GenericObjectPoolConfig(), "localhost", 6379, 3000);
Jedis jedisClient = jedisPool.getResource();
Now we try to create Redis Data Structures using Jedis.
It is like key-value pair. Using a key set a value and later retrieve the value using the key. It internally uses redis commands - GET and SET.
lpush and rpush methods used to insert elements at the top and bottom of the lists respectively. It corresponds to LPUSH and RPUSH redis commands.
llen is to find the length of the list. Elements from the list can be popped out from the top or bottom using lpop and rpop methods.
Below code snippet, first clear all the items in the list, then add item at top and bottom of the lists results in taskone, tasktwo and taskthree,
then remove the last item in the list and print the remaining items.
long noOfItems = 0l;
noOfItems = jedisClient.lpush("jobqueue", "tasktwo");
noOfItems = jedisClient.rpush("jobqueue", "taskthree");
noOfItems = jedisClient.lpush("jobqueue", "taskone");
System.out.printf("Number of items: %X - %d\n", noOfItems, jedisClient.llen("jobqueue"));
/*returns the elements within given range. If -1 is mentioned then it is considered to be last element. */
List<String> subList = jedisClient.lrange("jobqueue",0, 1));
Exclude the repeated members and maintain unordered collection of strings using SET data type.
Below example, add tags to the laptop product in which "electronicdevice" will be added once as it is duplicate. then remove randomly one item and print it.
jedisClient.sadd("laptopproduct#tags","electronicdevice", "computer", "portable", "electronicdevice");
Set<String> productSet = jedisClient.smembers("laptopproduct#tags");
Create hashmap of field, value with hashmapkey. In below example hashmapkey is "productMap", field is "productid#1" and its associated value is "laptop".
jedisClient.hset("productMap", "productid#1", "laptop");
jedisClient.hset("productMap", "productid#2", "mobile");
jedisClient.hset("productMap", "productid#3", "desktop");
//Get all field values
Map<String,String> hashMap = jedisClient.hgetAll("productMap");
//Delete a field
//Get only keys
Set<String> keySet = jedisClient.hkeys("productMap");
SortedSets By Ranking
Values with scores to be added to key and then retrieve or remove the values based on scores.
Map<String, Double> studentMarks = new HashMap<>();
studentMarks.put( "student1", 60.00d);
studentMarks.put( "student2", 50.00d);
studentMarks.put( "student3", 80.00d);
/*Students scored greater than 80 */
Set<String> topScorers = jedisClient.zrangeByScore("studentsReport", 80d, 100d));
There are many redis commands available like counter, bit operation and so on. Please refer to redis commands
Transactions happens isolated without any race condition. It is also atomic whether all the operations within transactions happens together. For example, user session data stored as two data types, one with session id string and other with user profile data.
Transaction transaction = jedisClient.multi();
Map<String, String> userProfileMap = jedisClient.hgetAll("userprofile"));
String sessionId = jedisClient.get("user");