Java Jedis Tutorial: Redis Connection Pooling & 5 Data Type Operations

This tutorial demonstrates setting up Redis on Windows, configuring a Maven project with Jedis 4.1.1, building a connection pool utility, and providing JUnit test examples for operating Redis Strings, Lists, Hashes, Sets, and Sorted Sets with Jedis API.

Java Captain
Java Captain
Java Captain
Java Jedis Tutorial: Redis Connection Pooling & 5 Data Type Operations

Introduction

This article provides a step-by-step guide for Java developers to connect to and operate Redis using the Jedis client. It covers environment setup, Maven project configuration, connection pooling, and practical JUnit test examples for the five core Redis data types.

1. Quick Redis Environment Setup on Windows

Since a Linux VM was unavailable, the author uses Microsoft's Windows port of Redis (version 3.2.100) from

https://github.com/microsoftarchive/redis/releases/tag/win-3.2.100

. Download Redis-x64-3.2.100.zip, extract, and run redis-server.exe. By default, no password is set; configuration can be adjusted via redis.windows.conf.

To avoid manual startup, Redis can be installed as a Windows service:

redis-server.exe --service-install redis.windows-service.conf

Service management commands:

Uninstall: redis-server --service-uninstall Start: redis-server --service-start Stop: redis-server --service-stop Rename:

redis-server --service-name name

2. Maven Project Setup

Create a Maven project and add the following dependencies:

<!-- Jedis 4.1.1 -->
<dependency>
  <groupId>redis.clients</groupId>
  <artifactId>jedis</artifactId>
  <version>4.1.1</version>
</dependency>

<!-- JUnit 4.11 for testing -->
<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.11</version>
  <scope>test</scope>
</dependency>

Refresh the Maven window to download the JARs. The project structure includes: com.jobs.utils.jedisUtils — utility class for Jedis connection pooling resources/redis.properties — connection pool configuration test/com.jobs.JedisTest — JUnit test cases for Redis operations

3. Connection Pool Configuration ( redis.properties )

# Maximum total connections
maxTotal=50
# Maximum idle connections
maxIdel=10
# Redis server address
host=localhost
# Redis server port
port=6379

4. Jedis Connection Pool Utility ( jedisUtils )

The utility class initializes a JedisPool using ResourceBundle to load properties. It configures JedisPoolConfig with maxTotal and maxIdle, then creates the pool. Commented code shows alternative initialization with password and database index.

package com.jobs.utils;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import java.util.ResourceBundle;

public class jedisUtils {
    private static JedisPool jp;

    static {
        ResourceBundle bundle = ResourceBundle.getBundle("redis");
        int maxTotal = Integer.parseInt(bundle.getString("maxTotal"));
        int maxIdel = Integer.parseInt(bundle.getString("maxIdel"));
        String host = bundle.getString("host");
        int port = Integer.parseInt(bundle.getString("port"));

        JedisPoolConfig jpc = new JedisPoolConfig();
        jpc.setMaxTotal(maxTotal);
        jpc.setMaxIdle(maxIdel);
        jp = new JedisPool(jpc, host, port);

        // If Redis has a password:
        // jp = new JedisPool(jpc, host, port, 2000, "password");
        // With password and specific database:
        // jp = new JedisPool(jpc, host, port, 2000, "password", 0);
    }

    public static Jedis getJedis() {
        return jp.getResource();
    }
}

5. JUnit Tests for Five Redis Data Types

The JedisTest class demonstrates CRUD operations for each data type. Each test obtains a Jedis instance from the pool, performs operations, prints results, and closes the connection.

5.1 String ( testString )

@Test
public void testString() {
    Jedis jedis = jedisUtils.getJedis();
    jedis.set("name", "候胖胖");
    jedis.set("age", "40");
    String name = jedis.get("name");
    String age = jedis.get("age");
    System.out.println("name:" + name + ",age:" + age);
    jedis.close();
}

5.2 List ( testList )

Uses rpush to add elements to the right (queue behavior), llen for length, and lpop to retrieve from the left.

@Test
public void testList() {
    Jedis jedis = jedisUtils.getJedis();
    jedis.rpush("fat", "任肥肥", "侯胖胖", "李墩墩");
    long fatCount = jedis.llen("fat");
    System.out.println("列表数量:" + fatCount);
    for (int i = 0; i < fatCount; i++) {
        String fatMan = jedis.lpop("fat");
        System.out.println(fatMan);
    }
    jedis.close();
}

5.3 Hash ( testHash )

Stores user objects as Hash maps. Uses hmset for bulk insert, hset for field updates, and hgetAll to retrieve all fields.

@Test
public void testHash() {
    Jedis jedis = jedisUtils.getJedis();
    Map<String, String> user1 = new HashMap<>();
    user1.put("name", "侯胖胖");
    user1.put("age", "40");
    user1.put("kg", "80");
    Map<String, String> user2 = new HashMap<>();
    user2.put("name", "任肥肥");
    user2.put("age", "38");
    user2.put("kg", "90");
    jedis.hmset("user1", user1);
    jedis.hmset("user2", user2);
    jedis.hset("user1", "age", "45");
    jedis.hset("user2", "kg", "100");
    Map<String, String> user111 = jedis.hgetAll("user1");
    Map<String, String> user222 = jedis.hgetAll("user2");
    System.out.println(user111);
    System.out.println(user222);
    jedis.close();
}

5.4 Set ( testSet )

Demonstrates set operations: sadd (auto-deduplicates), sinter (intersection), sunion (union), sdiff (difference).

@Test
public void testSet() {
    Jedis jedis = jedisUtils.getJedis();
    jedis.sadd("aaa", "a", "b", "c", "x", "y", "z", "a", "x");
    jedis.sadd("bbb", "b", "c", "d", "e", "f", "y", "b", "e");
    Set<String> sinter = jedis.sinter("aaa", "bbb");
    System.out.println("交集:" + sinter);
    Set<String> sunion = jedis.sunion("aaa", "bbb");
    System.out.println("并集:" + sunion);
    Set<String> sdiff = jedis.sdiff("aaa", "bbb");
    System.out.println("aaa 相对于 bbb 的差集:" + sdiff);
    jedis.close();
}

5.5 Sorted Set / ZSet ( testZset )

Uses scores for ranking (e.g., leaderboard). zadd adds members with scores, zrange returns ascending order, zrevrange returns descending order (top N).

@Test
public void testZset() {
    Jedis jedis = jedisUtils.getJedis();
    Map<String, Double> fans = new HashMap<>();
    fans.put("侯胖胖", 10d);
    fans.put("李墩墩", 7d);
    fans.put("任肥肥", 6d);
    fans.put("乔豆豆", 12d);
    fans.put("杨重重", 8d);
    jedis.zadd("vote", fans);
    jedis.zadd("vote", 9d, "任肥肥"); // update score
    List<String> vote1 = jedis.zrange("vote", 0, -1);
    System.out.println("投票数量升序排列:" + vote1);
    List<String> vote2 = jedis.zrevrange("vote", 0, 2);
    System.out.println("投票数量倒序前 3 个人:" + vote2);
    jedis.close();
}

Conclusion

The article demonstrates that Jedis API methods map directly to Redis commands, making it straightforward for developers familiar with Redis CLI. The complete example covers connection pooling, configuration management, and practical usage of all five fundamental Redis data structures via JUnit tests. For further command details, refer to the official Redis documentation at https://redis.io.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaRedisConnection PoolJedisMavenData TypesTutorialJUnit
Java Captain
Written by

Java Captain

Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.