Quick Start Programming Guide for redis using java client Jedis

  •        0

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.

Maven Dependency


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"));

  System.out.println(jedisClient.lindex("jobqueue", 1));


  /*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
  jedisClient.hdel("productMap", "productid#1");
  //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);
  jedisClient.zadd("studentsReport", studentMarks);

  /*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();
  transaction.set("user", "sessionid");

  Map<String, String> userProfileMap = jedisClient.hgetAll("userprofile"));
  String sessionId = jedisClient.get("user");




To find embedded technology information about MCU, IoT, AI etc Check out embedkari.com.


Nagappan is a techie-geek and a full-stack senior developer having 10+ years of experience in both front-end and back-end. He has experience on front-end web technologies like HTML, CSS, JAVASCRIPT, Angular and expert in Java and related frameworks like Spring, Struts, EJB and RESTEasy framework. He hold bachelors degree in computer science and he is very passionate in learning new technologies.

Subscribe to our newsletter.

We will send mail once in a week about latest updates on open source tools and technologies. subscribe our newsletter

Related Articles

Advanced Programming Guide in Redis using Jedis

  • redis jedis advanced-guide cluster pipline publish-subscribe

Redis is an in-memory data structure store, used 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 blog covers the advanced concepts like cluster, publish and subscribe, pipeling concepts of Redis using Jedis Java library.

Read More

How to install and setup Redis

  • redis install setup redis-cluster

Redis is an open source (BSD licensed), in-memory data structure store, used also as a database cache and message broker. It is written in ANSI C and works in all the operating systems. 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 install Redis.

Read More

Cache using Hazelcast InMemory Data Grid

  • hazelcast cache key-value

Hazelcast is an open source In-Memory Data Grid (IMDG). It provides elastically scalable distributed In-Memory computing, widely recognized as the fastest and most scalable approach to application performance.&nbsp;Hazelcast makes distributed computing simple by offering distributed implementations of many developer-friendly interfaces from Java such as Map, Queue, ExecutorService, Lock and JCache.

Read More

Connect to MongoDB and Perform CRUD using Java

  • java mongodb database programming

MongoDB is a popular and widely used open source NoSQL database. MongoDB is a distributed database at its core, so high availability, horizontal scaling, and geographic distribution is quite possible. It is licensed under Server Side Public License. Recently they moved to Server Side Public License, before that MongoDB was released under AGPL. This article will provide basic example to connect and work with MongoDB using Java.

Read More

Exonum Blockchain Framework by the Bitfury Group

  • blockchain bitcoin hyperledger blockchain-framework

Exonum is an extensible open source blockchain framework for building private blockchains which offers outstanding performance, data security, as well as fault tolerance. The framework does not include any business logic, instead, you can develop and add the services that meet your specific needs. Exonum can be used to build various solutions from a document registry to a DevOps facilitation system.

Read More

LogicalDOC - Open Source DMS

  • dms document-management-system

LogicalDOC is both a document management and a collaboration system. The software is loaded with many functions and allows organizing, indexing, retrieving, controlling and distributing important business documents securely and safely for any organization and individual.

Read More

An Introduction to the UnQLite Embedded NoSQL Database Engine

  • database nosql embedded key-value-store

UnQLite is an embedded NoSQL database engine. It's a standard Key/Value store similar to the more popular Berkeley DB and a document-store database similar to MongoDB with a built-in scripting language called Jx9 that looks like Javascript. Unlike most other NoSQL databases, UnQLite does not have a separate server process. UnQLite reads and writes directly to ordinary disk files. A complete database with multiple collections is contained in a single disk file. The database file format is cross-platform, you can freely copy a database between 32-bit and 64-bit systems or between big-endian and little-endian architectures.

Read More

Introduction to Apache Cassandra

  • cassandra database nosql

Apache Cassandra was designed by Facebook and was open-sourced in July 2008. It is regarded as perfect choice when the users demand scalability and high availability without any impact towards performance. Apache Cassandra is highly scalable, high-performance distributed database designed to handle large voluminous amounts of data across many commodity servers with no failure.

Read More

Is ZooKeeper mandatory for Cloud

  • zookeeper distributed cloud

Cloud is nothing but more than one system or application distributed across the network, across the globe. It may have couple of application servers, database server, shared data storage, backup server and lot more. The resources in the distributed environment must have information about each other so that they could co-ordinate and share without any issues. ZooKeeper helps to do that.

Read More

Angular Service Workers Usage Guide

  • angular service-worker offline-app

Web developers come across scenarios like web application completely breaks when workstation goes offline. Likewise to get into our application, every time we need to open a browser and then access it. Instead if it is in app, it will be easy to access for end-user. Push notifications similar to email client need to be done through web application. All these are addressed by a magic called service worker.

Read More

Advantages and Disadvantages of using Hibernate like ORM libraries

  • database orm

Traditionally Programmers used ODBC, JDBC, ADO etc to access database. Developers need to write SQL queries, process the result set and convert the data in the form of objects (Data model). I think most programmers would typically write a function to convert the object to query and result set to object. To overcome these difficulties, ORM provides a mechanism to directly use objects and interact with the database.

Read More

How to learn from open source projects

  • open-source learning methodology

Students ask this question frequently steps or methodology to learn from open source projects. There is no single answer or steps available. I listed the steps which i follow and i hope this will help for few.

Read More

Best open source Text Editors

  • text-editor editor tools dev-tools

Text editors are mainly used by programmers and developers for manipulating plain text source code, editing configuration files or preparing documentation and even viewing error logs. Text editors is a piece of software which enables to create, modify and delete files that a programmer is using while creating website or mobile app.In this article, we will discuss about top 7 all-round performing text editors which is highly supportive for programmers.

Read More

Light4j Cookbook - Rest API, CORS and RDBMS

  • light4j sql cors rest-api

Light 4j is a fast, lightweight and cloud-native microservices framework. In this article, we will see what and how hybrid framework works and integrate with RDMS databases like MySQL, also built in option of CORS handler for in-flight request.

Read More

Lucene / Solr as NoSQL database

  • lucene solr no-sql nosql document-store

Lucene and Solr are most popular and widely used search engine. It indexes the content and delivers the search result faster. It has all capabilities of NoSQL database. This article describes about its pros and cons.

Read More

JWT Authentication using Auth0 Library

  • java jwt authentication security

Json Web Token shortly called as JWT becomes defacto standard for authenticating REST API. In a traditional web application, once the user login credentials are validated, loggedin user object will be stored in session. Till user logs out, session will remain and user can work on the web application without any issues. Rest world is stateless, it is difficult to identify whether the user is already authenticated. One way is to use authenticate every API but that would be too expensive task as the client has to provide credentials in every API. Another approach is to use token.

Read More

Thymeleaf - Text display, Iteration and Conditionals

  • thymeleaf template-engine web-programming java

Thymeleaf is a server-side Java template engine for both web and standalone environments. It is a better alternative to JavaServer Pages (JSP). Spring MVC and Thymeleaf compliment each other if chosen for web application development. In this article, we will discuss how to use Thymeleaf.

Read More

8 Reasons Why Python Scores Over PHP for Web Development

  • python php web-development

PHP, the general-purpose scripting language has been used since decades for socket programming and web development. But in recent times, Python has become the most sought after programming language. This all-purpose programming language is attracting more developers in the industry owing to its highly dynamic and extensible nature. Let's see how Python is winning over age-old PHP.

Read More

An introduction to web cache proxy server - nuster

  • web-cache proxy-server load-balancer

Nuster is a simple yet powerful web caching proxy server based on HAProxy. It is 100% compatible with HAProxy, and takes full advantage of the ACL functionality of HAProxy to provide fine-grained caching policy based on the content of request, response or server status. This article gives an overview of nuster - web cache proxy server, its installation and few examples of how to use it.

Read More

Introduction to Light 4J Microservices Framework

  • light4j microservice java programming framework

Light 4j is fast, lightweight, secure and cloud native microservices platform written in Java 8. It is based on pure HTTP server without Java EE platform. It is hosted by server UnderTow. Light-4j and related frameworks are released under the Apache 2.0 license.

Read More