Redis for Java Developers: Tutorial and Code Examples

Redis for Java Developers: Tutorial and Code Examples

<strong>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.</strong>

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.

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&lt;String&gt; 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&lt;String, Integer&gt; 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.

Originally published by Nikita Koksharov at https://dzone.com

Learn More

☞ Complete Java Masterclass

☞ Complete Step By Step Java For Testers

☞ Java Web Service Complete Guide - SOAP + REST + Buide App

☞ Selenium WebDriver with Java - Basics to Advanced& Interview

☞ Java Persistence: Hibernate and JPA Fundamentals

☞ Java Swing (GUI) Programming: From Beginner to Expert

☞ Java Basics: Learn to Code the Right Way

Database Caching With Redis and Java

Database Caching With Redis and Java

Explore database caching with Redis and Java and see some of the different caching strategies.

Explore database caching with Redis and Java and see some of the different caching strategies.

Why Is Database Caching so Important?

The more information you have in a database, the slower it will become over time. Even database management systems that are well-designed to support many concurrent requests will eventually hit their limit.

Database caching is one of the most common strategies for dealing with these performance issues. Caching involves saving the results of database queries in a location that is faster and easier to access. When done correctly, caching will slash query response times, decrease the load on your databases, and cut costs.

However, caches also need to be handled with care because they essentially make another copy of your information in a separate location. Keeping both the database and the cache synchronized and up-to-date can be a trickier challenge than you anticipated. In the next section, we’ll discuss some of the most common database caching strategies.

What Are the Different Caching Strategies?

Manual caching (also known as a cache-aside strategy) involves direct management of both the database and the cache. Your application inspects the cache before launching a database query, and it updates the cache after any changes to the database.

While effective if implemented correctly, manual caching can be extremely tedious, especially if you need to query more than one database. For these reasons, developers have invented a number of alternative caching strategies.

Read-Through Caching Strategy

In read-through caching, the application first queries the cache to see if the information it needs is inside. If not, it retrieves the information from the database and uses it to update the cache. The cache provider or cache library is responsible for the detailed logic of querying and updating the cache.

The read-through strategy works best for read-heavy workloads when the application requests the same data repeatedly: for example, a news website that loads the same articles over and over.

One downside of the read-through strategy is that the first query to the cache will always result in a miss because the requested information is guaranteed not to be inside. To deal with this issue, developers often “warm” the cache ahead of time with information that users are likely to request.

Write-Through Caching Strategy

In write-through caching, updates are made to the cache first and to the database second. There is a direct line from the application to the cache and from the cache to the database. When combined with read-through caching, a write-through strategy guarantees that your data will be consistent, removing the need for manual cache invalidation.

Write-Behind Caching Strategy

In write-behind caching (also known as write-back caching), the application first writes data to the cache. After a set period of delay, the cache writes this information to the database as well. Write-behind caches are best for write-heavy workloads and can perform well even with some failures and downtime.

Java-Based Redis Caching With Redisson

Redis is one of the most popular options for NoSQL databases, using a key-value system to store data. Redisson, a client library for Redis in the Java programming language, makes it easy to access Redis features using all the familiar Java collections.

Redisson allows you to place data in Maps in external storage. You can use this functionality to implement caching for databases, web services, or any other data source.

Read-Through Caching in Redis

Below is a Java example of how to use read-through caching in Redis with Redisson.

If the requested entry doesn’t exist in the cache, it will be loaded by MapLoader object:

MapLoader<String, String> mapLoader = new MapLoader<String, String>() {

    @Override
    public Iterable<String> loadAllKeys() {
        List<String> list = new ArrayList<String>();
        Statement statement = conn.createStatement();
        try {
            ResultSet result = statement.executeQuery("SELECT id FROM student");
            while (result.next()) {
                list.add(result.getString(1));
            }
        } finally {
            statement.close();
        }

        return list;
    }

    @Override
    public String load(String key) {
        PreparedStatement preparedStatement = conn.prepareStatement("SELECT name FROM student where id = ?");
        try {
            preparedStatement.setString(1, key);
            ResultSet result = preparedStatement.executeQuery();
            if (result.next()) {
                return result.getString(1);
            }
            return null;
        } finally {
            preparedStatement.close();
        }
    }
};

Configuration example:

MapLoader<String, String> mapLoader = new MapLoader<String, String>() {

    @Override
    public Iterable<String> loadAllKeys() {
        List<String> list = new ArrayList<String>();
        Statement statement = conn.createStatement();
        try {
            ResultSet result = statement.executeQuery("SELECT id FROM student");
            while (result.next()) {
                list.add(result.getString(1));
            }
        } finally {
            statement.close();
        }

        return list;
    }

    @Override
    public String load(String key) {
        PreparedStatement preparedStatement = conn.prepareStatement("SELECT name FROM student where id = ?");
        try {
            preparedStatement.setString(1, key);
            ResultSet result = preparedStatement.executeQuery();
            if (result.next()) {
                return result.getString(1);
            }
            return null;
        } finally {
            preparedStatement.close();
        }
    }
};

Write-Through Caching in Redis

Below is a Java example of how to use write-through caching in Redis in Redis with Redisson.

Cache update method will not return until both the cache and the database have been updated by MapWriter object:

MapLoader<String, String> mapLoader = new MapLoader<String, String>() {

    @Override
    public Iterable<String> loadAllKeys() {
        List<String> list = new ArrayList<String>();
        Statement statement = conn.createStatement();
        try {
            ResultSet result = statement.executeQuery("SELECT id FROM student");
            while (result.next()) {
                list.add(result.getString(1));
            }
        } finally {
            statement.close();
        }

        return list;
    }

    @Override
    public String load(String key) {
        PreparedStatement preparedStatement = conn.prepareStatement("SELECT name FROM student where id = ?");
        try {
            preparedStatement.setString(1, key);
            ResultSet result = preparedStatement.executeQuery();
            if (result.next()) {
                return result.getString(1);
            }
            return null;
        } finally {
            preparedStatement.close();
        }
    }
};

Configuration example:

MapLoader<String, String> mapLoader = new MapLoader<String, String>() {

    @Override
    public Iterable<String> loadAllKeys() {
        List<String> list = new ArrayList<String>();
        Statement statement = conn.createStatement();
        try {
            ResultSet result = statement.executeQuery("SELECT id FROM student");
            while (result.next()) {
                list.add(result.getString(1));
            }
        } finally {
            statement.close();
        }

        return list;
    }

    @Override
    public String load(String key) {
        PreparedStatement preparedStatement = conn.prepareStatement("SELECT name FROM student where id = ?");
        try {
            preparedStatement.setString(1, key);
            ResultSet result = preparedStatement.executeQuery();
            if (result.next()) {
                return result.getString(1);
            }
            return null;
        } finally {
            preparedStatement.close();
        }
    }
};

Write-Behind Caching in Redis

The MapWriter interface is also used to asynchronously commit updates to the Map object (cache) and the external storage (database). Threads amounts used in the background write operation execution sets through the writeBehindThreads setting.

Below, we see a Java example of the configuration for a Redis-based write-behind caching implementation in Redisson:

MapLoader<String, String> mapLoader = new MapLoader<String, String>() {

    @Override
    public Iterable<String> loadAllKeys() {
        List<String> list = new ArrayList<String>();
        Statement statement = conn.createStatement();
        try {
            ResultSet result = statement.executeQuery("SELECT id FROM student");
            while (result.next()) {
                list.add(result.getString(1));
            }
        } finally {
            statement.close();
        }

        return list;
    }

    @Override
    public String load(String key) {
        PreparedStatement preparedStatement = conn.prepareStatement("SELECT name FROM student where id = ?");
        try {
            preparedStatement.setString(1, key);
            ResultSet result = preparedStatement.executeQuery();
            if (result.next()) {
                return result.getString(1);
            }
            return null;
        } finally {
            preparedStatement.close();
        }
    }
};

All discussed strategies are available for the RMap, RMapCache, RLocalCachedMap, and RLocalCachedMapCache objects in Redisson. Using these latter two objects can make read operations in Redis up to 45 times faster.

Java Fundamentals: Learn Java for absolute beginners |Simpliv

Java Fundamentals: Learn Java for absolute beginners |Simpliv

Java Fundamentals: Learn Java for absolute beginners

Description
This is the best course to learn to program in Java in Spanish from scratch and without any experience in this fabulous programming language. This is the first course where we will study the Fundamentals of Java, and we will take you step by step until you acquire the bases of the Java language and you can start to study more advanced Java topics.

The content is divided into perfectly structured levels, each level supported by the previous one, with the aim of adding Java knowledge incrementally and so you can focus on mastering the issues little by little and gradually. So ensure the success of your Java training.

We will also offer support for any doubts about the didactic material included in this Java Fundamentals course.

We manage a new teaching methodology that we have called Speed ​​Learning. This methodology consists of concise videos that go directly to the point to be studied, complemented by eBooks with explanations and step-by-step images (which you can print, or search for any text you need, or use for your offline study), since As we know we can not do text search within a video. In addition, our methodology includes perfectly structured and very didactic exercises that will allow you to accelerate your eLearning learning. No loss of time in videos where you have to watch the instructor codify an exercise, too much theory, little practice or anything like that. Our Speed ​​Learning methodology guarantees that in the shortest possible time you will acquire the necessary knowledge for the Java professional and working world.

The Java Fundamentals course includes the following topics for study:

Lesson 1 - Starting with Java Technology

The amazing world of Java programming

What is Java technology (from a practical approach)

Our first Java program from scratch

Lesson 2 - Variables and Operators in Java

Use of Variables in Java and what we use them for

Types of Data in Java and how they are classified

Management and Classification of operators in Java

Lesson 3 - Control statements in Java

Using the if-else structure and where to use it

Handling the switch structure and when applying it

Lesson 4 - Handling Loops in Java

Use of the for loop and its use

Using the while loop and how to apply it

Use of the do-while loop and when to use it

Lesson 5 - Object Oriented Programming

Introduction to Object Oriented Programming (OOP)

Handling Classes in Java

Use of Objects in Java

Lesson 6 - Functions in Java

Declaration of Methods or Functions in Java

Use and call of functions in Java

Lesson 7 - Data Management in Java

Using Arrays in Java

Management of Matrices in Java

Lesson 8 - Inheritance in Java

Inheritance Management in Java

Use of superclasses and subclasses in Java

Final Level Laboratory

Final Exercise where everything learned in this Level is integrated

At the end you get a certificate of having completed the Java Fundamentals course.

We wait for you on the other side.

Ing. Ubaldo Acosta

Founder of Global Mentoring

Passion for Java Technology

Who this course is for:

Anyone who wants to learn how to program in Java
Basic knowledge
Basic knowledge of PC use
Basic management of an operating system such as Windows, Mac or Linux
It is not necessary to know how to program, we will start from scratch !!!
The attitude and desire to start coding and learning Java once and for all from scratch!
What will you learn
Have the basics of the programming language with Java
You will know the basic syntax of the Java language
Manage the concept of Variables and Operators in Java
We will study Object Oriented Programming with Java
You will learn the Control Statements and Loops in Java
We will see the concept of Functions with Java
We will study the concept of Inheritance in Java
We will learn to use Arrays in java
We will handle the concept of Matrices in Java
We will learn to Design Classes in Java
We will make a final application with everything learned in the course
To know more:

Java Essentials : Learn Core Java From Basic to Advance

Java Essentials : Learn Core Java From Basic to Advance

Learn Java Programming Using Practical Assignments. Start Building Back-end Web Applications Robust Test Automation Frameworks By End Of The Course. Learn More!

Description
This is only Java related course and it's great because it covers just the right amount of Java which is needed to leaning programming, java.

This is a comprehensive yet simple course on java programming language and it concentrates on Java programming concepts.

*************************** No Prior Coding Experience Needed ***************************

This course assumes that you have no programming background. If you have some experience then, it's just a bonus point. You have never code, have some experience or have a lot of experience any other programming language, this course is one stop place for you.

Java is one of the most and useful programming languages to learn You can build back-end of web applications and build robust test automation framework. Specially for Selenium WebDriver GUI automation, Java is most popular choice and has the largest community.

Each lecture consist of a video screencast and code files

There are quizzes, homework to test your knowledge

High focus on practice and asking questions

You will also learn coding best practices

Market is never short of jobs in Java programming language, there are ample of jobs in both Java development and Automation Testing using Java.

What are you waiting for? Enroll today and learn the powerful Java language !!!

Basic knowledge
Nothing else! It’s just you, your computer and your hunger to get started today
Java concepts are covered in the course, no experience needed
Windows/MAC computer
What will you learn
You will be able to EXPLAIN, DESIGN and IMPLEMENT efficient java Programs
You will be confident to clear test automation interviews
Understand the concepts of Object Oriented Programming Language
Complete understanding of java
Expert-level knowledge of Java code (+ advanced tips and tricks used by the pros)
Suitable for beginner programmers and ideal for users who learn faster when shown
To learn more: