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

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Boosting Application Performance With MicroStream and Redis Integration
  • Linked List Popular Problems Vol. 1
  • Java: Why a Set Can Contain Duplicate Elements
  • What Is Ant, Really?

Trending

  • How To Introduce a New API Quickly Using Quarkus and ChatGPT
  • Introducing Graph Concepts in Java With Eclipse JNoSQL
  • The Evolution of Scalable and Resilient Container Infrastructure
  • Supervised Fine-Tuning (SFT) on VLMs: From Pre-trained Checkpoints To Tuned Models
  1. DZone
  2. Coding
  3. Java
  4. Distributed Java Queues on Top of Redis

Distributed Java Queues on Top of Redis

By 
Nikita Koksharov user avatar
Nikita Koksharov
·
Updated Mar. 11, 20 · Tutorial
Likes (8)
Comment
Save
Tweet
Share
33.2K Views

Join the DZone community and get the full member experience.

Join For Free

Using Queues in Redis

Redis is a powerful tool that supports many different types of data structures from Strings and lists to maps and streams. Developers use Redis as a database, a cache, and a message broker.

Like any message broker, Redis needs to send messages in the correct order. Messages may be sent according to their age or according to some other predefined priority ranking.

In order to store these pending messages, Redis developers need a queue data structure. Redisson is a framework for distributed programming with Redis and Java that provides implementations of many distributed data structures, including queues.

Redisson makes Redis development easier by providing a Java API. Instead of requiring developers to learn Redis commands, Redisson includes all the well-known Java interfaces, such as Queue and BlockingQueue. Redisson also handles the tedious behind-the-scenes work in Redis, such as connection management, failover handling, and data serialization.

You may also like: Building Microservices With Redis.

Redis-Based Distributed Java Queues

Redisson provides multiple Redis based implementations of the basic queue data structure in Java, each with a different functionality. This allows you to select the type of queue that is best suited for your purposes.

Below, we'll discuss six different types of Redis based distributed queues using the Redisson Java framework.

Queue

The RQueue object in Redisson implements the java.util.Queue interface. Queues are used for situations in which elements should be processed beginning with the oldest ones first (also known as "first in, first out" or FIFO).

As with plain Java, the first element of the RQueue can be examined with the peek() method, or examined and removed with the poll() method:

Java
xxxxxxxxxx
1
 
1
RQueue<SomeObject> queue = redisson.getQueue("anyQueue");
2
queue.add(new SomeObject());
3
SomeObject obj = queue.peek();
4
SomeObject someObj = queue.poll();


BlockingQueue

The RBlockingQueue object in Redisson implements the java.util.BlockingQueue interface.

BlockingQueues are queues that block a thread attempting to poll from an empty queue, or attempting to insert an element in a queue that is full. The thread is blocked until another thread inserts an element into the empty queue, or polls the first element from the full queue.

The example code below demonstrates the proper instantiation and use of an RBlockingQueue. In particular, you can call the poll() method with arguments that specify how long the thread will wait for an element to become available:

Java
xxxxxxxxxx
1
 
1
RBlockingQueue<SomeObject> queue = redisson.getBlockingQueue("anyQueue");
2
queue.offer(new SomeObject());
3
SomeObject obj = queue.peek();
4
SomeObject someObj = queue.poll();
5
SomeObject ob = queue.poll(10, TimeUnit.MINUTES);


During times of failover or reconnection to the Redis server, the poll(), pollFromAny(), pollLastAndOfferFirstTo(), and take() Java methods are resubscribed automatically.

BoundedBlockingQueue

The RBoundedBlockingQueue object in Redisson implements a bounded blocking queue structure. Bounded blocking queues are blocking queues whose capacity has been bounded, i.e. limited.

The code below demonstrates how to instantiate and use an RBoundedBlockingQueue in Redisson. The trySetCapacity() method is used to attempt to set the capacity of the blocking queue. trySetCapacity() returns the Boolean value "true" or "false", depending on whether the capacity was successfully set or whether it was already set:

Java
xxxxxxxxxx
1
 
1
RBoundedBlockingQueue<SomeObject> queue = redisson.getBoundedBlockingQueue("anyQueue");
2
queue.trySetCapacity(2);
3
queue.offer(new SomeObject(1));
4
queue.offer(new SomeObject(2));
5
// will be blocked until free space available in queue
6
queue.put(new SomeObject());
7
SomeObject obj = queue.peek();
8
SomeObject someObj = queue.poll();
9
SomeObject ob = queue.poll(10, TimeUnit.MINUTES);


DelayedQueue

The RDelayedQueue object in Redisson allows you to implement a delayed queue in Redis. This could be useful when delivering messages to consumers using a strategy such as exponential backoff. After each failed attempt to deliver a message, the time between retries will increase exponentially.

Each element in the delayed queue will be transferred to a destination queue after a delay that is specified together with the element. This destination queue may be any queue that implements the RQueue interface, such as an RBlockingQueue or RBoundedBlockingQueue.

Java
xxxxxxxxxx
1
 
1
RQueue<String> destinationQueue = redisson.getQueue("anyQueue");
2
RDelayedQueue<String> delayedQueue = getDelayedQueue(destinationQueue);
3
// move object to destinationQueue in 10 seconds
4
delayedQueue.offer("msg1", 10, TimeUnit.SECONDS);
5
// move object to destinationQueue in 1 minute
6
delayedQueue.offer("msg2", 1, TimeUnit.MINUTES);


It's a good idea to destroy the delayed queue by using the destroy() method after the queue is no longer needed. However, this is not necessary if you are shutting down Redisson.

PriorityQueue

The RPriorityQueue object in Redisson implements the java.util.Queue interface. Priority queues are queues that are sorted not by the age of the element, but by the priority that is associated with each element.

As shown in the example code below, RPriorityQueue uses a Comparator to sort the elements in the queue:

Java
xxxxxxxxxx
1
 
1
RPriorityQueue<Integer> queue = redisson.getPriorityQueue("anyQueue");
2
queue.trySetComparator(new MyComparator()); // set object comparator
3
queue.add(3);
4
queue.add(1);
5
queue.add(2);
6
queue.removeAsync(0);
7
queue.addAsync(5);
8
queue.poll();


PriorityBlockingQueue

The RPriorityBlockingQueue object in Redisson combines the functionalities of RPriorityQueue and RBlockingQueue. Like RPriorityQueue, RPriorityBlockingQueue uses a Comparator to sort the elements in the queue.

Java
xxxxxxxxxx
1
 
1
RPriorityBlockingQueue<Integer> queue = redisson.getPriorityBlockingQueue("anyQueue");
2
queue.trySetComparator(new MyComparator()); // set object comparator
3
queue.add(3);
4
queue.add(1);
5
queue.add(2);
6
queue.removeAsync(0);
7
queue.addAsync(5);
8
queue.take();


During times of failover or reconnection to the Redis server, the poll(), pollLastAndOfferFirstTo(), and take() Java methods are resubscribed automatically.


Further Reading

  • Java-Distributed Caching in Redis.
  • Introduction to Spring Data Redis.
  • Redis in a Microservices Architecture.
Redis (company) Java (programming language) Element

Opinions expressed by DZone contributors are their own.

Related

  • Boosting Application Performance With MicroStream and Redis Integration
  • Linked List Popular Problems Vol. 1
  • Java: Why a Set Can Contain Duplicate Elements
  • What Is Ant, Really?

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!