Swift provides a simple way to broadcast typed payloads across a Redis Pub/Sub network and dispatch them to annotated listeners with priority ordering. Swift interacts with Redis using the Lettuce library.
A payload is any Java object you want to send across the network.
public class MessagePayload {
private final String message;
}A listener is a class that implements PayloadListener and contains methods annotated with @PayloadHandler
public class ChatListener implements PayloadListener {
@PayloadHandler(priority = PayloadPriority.NORMAL)
public void onChat(ChatMessagePayload payload) {
System.out.println(payload.getMessage());
}
}Each handler method:
- Must be annotated with
@PayloadHandler - Must take exactly one parameter
- That parameter defines the payload type it handles
Handlers are executed from HIGHEST to LOWEST.
public enum PayloadPriority {
HIGHEST,
HIGH,
NORMAL,
LOW,
LOWEST
}RedisClient redisClient = RedisClient.create("redis://localhost:6379");
JsonProvider jsonProvider = new GsonJsonProvider();
Swift swift = new Swift(
"my-network", // Redis channel (network)
"unit-1", // Sender identifier (unit)
redisClient,
jsonProvider
);network - Redis Pub/Sub channel that payloads will be broadcast on.
unit - Identifier of the payload sender.
swift.registerListener(new ChatMessageListener());Or multiple at once:
swift.registerListeners(
new ChatMessageListener(),
new UserConnectionListener()
);Listeners can be registered at runtime and are thread-safe.
swift.broadcastPayload(new ChatMessagePayload("Hello world"));This:
- Serializes the payload using the provided
JsonProvider. - Wraps it in a
Messageobject. - Publishes it to Redis.