Skip to content

Redis Usage

virtualWinter edited this page Aug 30, 2025 · 2 revisions

Redis Usage

This guide explains how to use the Redis features of the Storage library, particularly the annotation-driven publish/subscribe system.

1. Initialization

First, create an instance of the Redis class. You can do this in two ways:

With a URI

Redis redis = new Redis("redis://user:password@localhost:6379");
redis.init();
redis.start();

With Host and Port

Redis redis = new Redis("localhost", 6379);
redis.init();
redis.start();

2. Defining a Packet

Create a class that extends Packet. This will be your message format.

public class ChatMessagePacket extends Packet {
    private final String sender;
    private final String message;

    public ChatMessagePacket(String sender, String message) {
        this.sender = sender;
        this.message = message;
    }

    // Getters
}

3. Creating a Listener

Create a class with a method annotated with @RedisListener. The method must have a single parameter, which is the type of packet it should listen for.

public class ChatListener {

    @RedisListener(channel = "chat-messages")
    public void onChatMessage(ChatMessagePacket packet) {
        System.out.println(packet.getSender() + ": " + packet.getMessage());
    }
}

Then, register an instance of your listener class:

redis.registerListener(new ChatListener());

4. Creating a Sender

Create an interface with a method annotated with @RedisSender. The method must have a single parameter, which is the type of packet it will send.

public interface ChatSender {

    @RedisSender(channel = "chat-messages")
    void sendChatMessage(ChatMessagePacket packet);
}

Then, create a sender instance:

ChatSender sender = redis.createSender(ChatSender.class);

You can then use the sender to publish messages:

sender.sendChatMessage(new ChatMessagePacket("user1", "Hello, world!"));

Clone this wiki locally