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

 


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


   

Nagappan is a freelance developer and also does corporate training.

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

How to install Redis

  • redis install setup

Redis is an open source (BSD licensed), in-memory data structure store, used also as a database cache and message broker. <br />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


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


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


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


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


AbanteCart - Easy to use open source e-commerce platform, helps selling online

  • e-commerce ecommerce cart

AbanteCart is a free, open source shopping cart that was built by developers with a passion for free and accessible software. Founded in 2010 (launched in 2011), the platform is coded in PHP and supports MySQL. AbanteCart’s easy to use admin and basic layout management tool make this open source solution both easy to use and customizable, depending on the skills of the user. AbanteCart is very user-friendly, it is entirely possible for a user with little to no coding experience to set up and use this cart. If the user would be limited to the themes and features available in base AbanteCart, there is a marketplace where third-party extensions or plugins come to the rescue.

Read More


Lucene Vs Solr

  • searchengine lucene solr

Lucene is a search library built in Java. Solr is a web application built on top of Lucene. Certainly Solr = Lucene + Added features. Often there would a question, when to choose Solr and when to choose Lucene.

Read More


How to solve CommunicationsException in Java while using Hibernate and MySQL

  • java hibernate mysql communicationsexception timeout

You might have faced CommunicationsException, basically timeout issue in Java while connecting to MySQL using Hibernate. The session would be timed out after certain period of time. You might be thinking that the your site or application is running without any issue but it would have stopped or crashed due to exception.

Read More


Why require Searchengine? Why not use database for full text search in Enterprise application.

  • searchengine database

Most of the database has support of full text search, basically indexing and saarching. MySQL, Oracle and many more databases has in-built full text search. Then what is the need to go for external search engine like Lucene, Sphinx, Solr etc. Check out the advantage of using Searchengine.

Read More


PySpark: Installation, RDDs, MLib, Broadcast and Accumulator

  • pyspark spark python rdd big-data

We knew that Apace Spark- the most famous parallel computing model or processing the massive data set is written in Scala programming language. The Apace foundation offered a tool to support the Python in Spark which was named PySpark. The PySpark allows us to use RDDs in Python programming language through a library called Py4j. This article provides basic introduction about PySpark, RDD, MLib, Broadcase and Accumulator.

Read More


How to create SEO friendly url

  • seo url searchengine

SEO friendly URL is recommended for any website which wants to be indexed and wants its presence in search results. Searchengine mostly index the static URL. It will avoid the URL which has lot of query strings. Almost all websites generate content dynamically then how could the URL be static. That is the job of the programmer.

Read More


An introduction to LucidWorks Enterprise Search

  • lucene solr search engine enterprise

Lucidworks Enterprise search solution is built on top of Apache Solr. It scales seamlessly w/sub-second response times under extreme query loads for multi-billion document collections. It has user friendly UI, which does all the job of configuration and search.

Read More