1. Redis
Redis using Lettuce library.
1.1. Usage
1) Add the dependency:
<dependency>
<groupId>io.jooby</groupId>
<artifactId>jooby-redis</artifactId>
<version>3.5.5</version>
</dependency>
2) Set redis property
redis = "redis://localhost:6379"
3) Install and use Redis
import io.jooby.redis.RedisModule;
import io.lettuce.core.api.StatefulRedisConnection;
{
install(new RedisModule()); (1)
get("/", ctx -> {
StatefulRedisConnection redis = require(StatefulRedisConnection.class); (2)
// work with redis
});
}
1 | Install Redis |
2 | Use Redis |
The io.lettuce.core.pubsub.StatefulRedisPubSubConnection
is also available.
1.2. Redis URI
Redis URI are allowed to pass it directly or from application configuration file:
{ new RedisModule("redis://localhost:6379"); }
Or read it from configuration:
{ new RedisModule("redis"); }
Either redis
or redis.uri
must be present in your application configuration file and must be a
valid Redis URI.
1.3. Multiple Connections
Support for multiple connection is done using multiple configuration keys:
import io.jooby.redis.RedisModule;
import io.lettuce.core.api.StatefulRedisConnection;
{
install(new RedisModule("foo"));
install(new RedisModule("bar"));
get("/", ctx -> {
StatefulRedisConnection foo = require(StatefulRedisConnection.class, "foo");
// work with redis
});
}
Where foo
and bar
are redis URI in your application configuration file:
foo = "redis://server1:6379"
bar = "redis://server2:6379"
1.4. HTTP Session
The Redis module provides a HTTP Session Store.
import io.jooby.redis.RedisModule;
import io.jooby.redis.RedisSessionStore;
import io.lettuce.core.RedisClient;
{
install(new RedisModule()); (1)
setSessionStore(new RedisSessionStore(require(RedisClient.class))); (2)
get("/", ctx -> {
Session httpSession = ctx.session(); (3)
// HTTP session is backed by Redis
});
}
1 | Install Redis module |
2 | Configure session store to use Redis |
3 | Session data is persisted in Redis |
More Options:
-
setTimeout(Duraction): Set session timeout. Default is:
30 minutes
-
setNamespace(String): Set key prefix. Default is:
sessions
-
setToken(SessionToken): Set session token. Default is a cookie token:
jooby.sid