DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Oracle NoSQL Database: A Comprehensive Guide for Developers
  • Microsoft Teams for Developers: Enhancing Communication With Call Initiating and Recording
  • Mastering Thread-Local Variables in Java: Explanation and Issues
  • Migrating From Lombok to Records in Java

Trending

  • DZone's Article Submission Guidelines
  • Top Book Picks for Site Reliability Engineers
  • A Complete Guide to Modern AI Developer Tools
  • Event-Driven Architectures: Designing Scalable and Resilient Cloud Solutions
  1. DZone
  2. Coding
  3. Java
  4. Redis for Java Developers: Tutorial and Code Examples

Redis for Java Developers: Tutorial and Code Examples

This article will go over a few common use cases of Redisson.

By 
Nikita Koksharov user avatar
Nikita Koksharov
·
Apr. 01, 19 · Tutorial
Likes (6)
Comment
Save
Tweet
Share
21.1K Views

Join the DZone community and get the full member experience.

Join For Free

Redis is one of the most popular NoSQL database solutions, and Java is one of the world's most popular programming languages. Although it seems natural for the two to work together, Redis doesn't come with native support for Java.

Instead, Java developers who want to integrate with Redis will need to use a Java client library. Redisson is a Redis-based in-memory data grid for Java that makes it easy for Java developers to work with Redis. Redisson provides implementations of many Java data structures to be distributed and scalable so that they can run on top of the Redis server.Image title

This article will go over a few common use cases of Redisson so that you can see how easy it is to get started writing Java code for Redis.

How to Install Redisson

The easiest way to install Redisson is by adding it as a Maven or Gradle dependency:

Maven

<dependency>
   <groupId>org.redisson</groupId>
   <artifactId>redisson</artifactId>
   <version>3.10.5</version>
</dependency>  

Gradle

compile 'org.redisson:redisson:3.10.5'  

You can find the latest version number of Redisson by searching the Maven central repository.

How to Compile and Run Redisson

Once Redisson has been installed, compiling and running Redisson code just requires using the Java compiler:

javac RedissonExample.java

java RedissonExample

Java Lists in Redis

The code below is a simple demonstration of how to use the RList object in Redisson. RList is a distributed and concurrent implementation of Java's List collection.

import org.redisson.Redisson;
import org.redisson.api.RList;
import org.redisson.api.RedissonClient;

public class ListExamples {

    public static void main(String[] args) {
        // connects to 127.0.0.1:6379 by default
        RedissonClient redisson = Redisson.create();

        // implements java.util.List
        RList<String> list = redisson.getList("myList");
        list.add("1");
        list.add("2");
        list.add("3");

        boolean contains = list.contains("1");

        System.out.println("List size: " + list.size());
        System.out.println("Is list contains value '1': " + contains);

        for (String element : list) {
            System.out.println("List element: " + element);
        }

        redisson.shutdown();
    }

}

When you run the code above, you should get the following output:

List size: 3

Does list contain value '1': true

List element: 1

List element: 2

List element: 3

Java Maps in Redis

Redisson also includes RMap, a distributed and concurrent implementation of the Java Map collection:

import java.io.IOException;

import org.redisson.Redisson;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;

public class MapExamples {

    public static void main(String[] args) throws IOException {
        // connects to 127.0.0.1:6379 by default
        RedissonClient redisson = Redisson.create();

        // implements java.util.concurrent.ConcurrentMap
        RMap<String, Integer> map =  redisson.getMap("myMap");
        map.put("a", 1);
        map.put("b", 2);
        map.put("c", 3);

        boolean contains = map.containsKey("a");
        System.out.println("Map size: " + map.size());
        System.out.println("Is map contains key 'a': " + contains);

        Integer value = map.get("c");
        System.out.println("Value mapped by key 'c': " + value);

        boolean added = map.putIfAbsent("c", 4) == null;
        System.out.println("Is value mapped by key 'c' added: " + added);

        redisson.shutdown();
    }

}

When you run the code above, you will see the following output:

Map size: 3
Map contains key 'a': true
Value mapped by key 'c': 3
Value mapped by key 'c' added: false

Java Locks in Redis

The code below demonstrates the usage of RLock, a distributed implementation of the reentrant lock in Java:

import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

public class LockExamples {

    public static void main(String[] args) throws InterruptedException {
        // connects to 127.0.0.1:6379 by default
        RedissonClient redisson = Redisson.create();

        // implements java.util.concurrent.locks.Lock
        RLock lock = redisson.getLock("lock");
        lock.lock();
        System.out.println("lock aquired");

        Thread t = new Thread() {
            public void run() {
                RLock lock1 = redisson.getLock("lock");
                lock1.lock();
                System.out.println("lock aquired by thread");
                lock1.unlock();
                System.out.println("lock released by thread");
            };
        };

        t.start();
        t.join(1000);

        lock.unlock();
        System.out.println("lock released");

        t.join();

        redisson.shutdown();
    }

}

This code will produce the following output:

lock aquired
lock released
lock aquired by thread
lock released by thread

Java AtomicLongs in Redis

Finally, this sample code demonstrates the usage of RAtomicLong, a distributed alternative to the AtomicLong class in Java for holding long values in a concurrent environment.

import org.redisson.Redisson;
import org.redisson.api.RAtomicLong;
import org.redisson.api.RedissonClient;

public class AtomicLongExamples {

    public static void main(String[] args) {
        // connects to 127.0.0.1:6379 by default
        RedissonClient redisson = Redisson.create();

        RAtomicLong atomicLong = redisson.getAtomicLong("myLong");
        System.out.println("Init value: " + atomicLong.get());

        atomicLong.incrementAndGet();

        System.out.println("Current value: " + atomicLong.get());

        atomicLong.addAndGet(10L);

        System.out.println("Final value: " + atomicLong.get());

        redisson.shutdown();
    }

}

The output of this code will be:

Init value: 0
Current value: 1
Final value: 11

What are your thoughts? Let me know in the comments.

Java (programming language) Redis (company) code style dev

Opinions expressed by DZone contributors are their own.

Related

  • Oracle NoSQL Database: A Comprehensive Guide for Developers
  • Microsoft Teams for Developers: Enhancing Communication With Call Initiating and Recording
  • Mastering Thread-Local Variables in Java: Explanation and Issues
  • Migrating From Lombok to Records in Java

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!