How to connect to Redis in a Java project build with Maven using the Jedis client library

Last updated 20, Apr 2024

Goal

Understand how to connect to Redis using the Jedis client library for the Java programming language in a Maven project.

Solution

You can create a simple scaffold for a Java project with Maven.

mvn archetype:generate -DgroupId=com.redis.app -DartifactId=redis-test -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.4 -DinteractiveMode=false

This will generate a directory. Browse in and edit the pom.xml file where you will specify the desired Java version:

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>

Then include the following dependencies to the Jedis client library to connect to Redis.

    <dependency>
      <groupId>redis.clients</groupId>
      <artifactId>jedis</artifactId>
      <version>5.0.1</version>
    </dependency>

Now, you can edit the file src/main/java/com/redis/app/App.java and add the desired source code.

package com.redis.app;

import redis.clients.jedis.UnifiedJedis;

public class App 
{
    public static void main( String[] args )
    {
        System.out.println( "Redis test" );
        UnifiedJedis unifiedjedis = new UnifiedJedis(System.getenv().getOrDefault("REDIS_URL", "redis://localhost:6379"));
        System.out.println(unifiedjedis.ping());
    }
}

Compile the project with:

mvn package

And execute it using:

mvn exec:java -Dexec.mainClass=com.redis.app.App

References

Connect to Redis with Jedis