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

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>3.0.1</version>
</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.

Strings

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.

   jedisClient.set("ecommerce/customer/name","nagappans");
   System.out.println(jedisClient.get("ecommerce/customer/name"));

Lists

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;
  jedisClient.ltrim("jobqueue",-1,-1);
 
  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));

  System.out.println(jedisClient.rpop("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));

Sets

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");
  jedisClient.spop("laptopproduct#tags");
  Set<String> productSet = jedisClient.smembers("laptopproduct#tags");

Hashes

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

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");
  transaction.hset("userprofile","language","spanish");
  transaction.hset("userprofile","grade","3");
  transaction.exec();

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

 

Reference:
https://github.com/xetorthio/jedis
https://redis.io/commands
https://www.findbestopensource.com/tagged/redis-client

 


   

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


WebSocket implementation with Spring Boot

  • websocket web-sockets spring-boot java

Spring Boot is a microservice-based Java framework used to create web application. WebSocket API is an advanced technology that provides full-duplex communication channels over a single TCP connection. This article explains about how to implement WebSocket using Spring Boot.

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


Data Fetching and Form Building using NextJS

  • nextjs data-fetching form-handling

Next.js is one of the easy-to-learn frameworks for server-side pre-render pages for client-side web applications. In this blog, we will see how we can fetch data from API and make it pre-render pages. Also, let's see how forms work in Next.js and collect the data without maintaining the database.

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


Understanding Web Real-Time Communication (WebRTC)

  • webrtc communication web

Web Real-Time Communication (WebRTC) is an open source project currently being developed with an aim to provide real time, peer-to-peer communication between web applications. WebRTC provides simple JavaScript APIs that help developers to easily build web applications with real time audio, video and data transfer capabilities. This blog has been written assuming that the reader has zero knowledge of how WebRTC works and hence have explained the entire working in detail using simple terms and analogies wherever possible. Let’s get started!

Read More


Rowy - Airtable-like simplicity for managing your Firestore data

  • airtable-alternative spreedsheet admin-dashboard low-code cloud-function

Rowy an open-source platform to manage your data in an intuitive spreadsheet-like UI. Say goodbye to emailing that "vFinalFinal" Excel sheet. It helps to write Cloud Functions effortlessly in the browser, and connect to your favorite third party platforms such as SendGrid, Twilio, Algolia, Slack and more.

Read More







We have large collection of open source products. Follow the tags from Tag Cloud >>


Open source products are scattered around the web. Please provide information about the open source projects you own / you use. Add Projects.