Skip to content

CDI Support

Mark Paluch edited this page Jun 13, 2020 · 3 revisions

CDI support for Lettuce is available for RedisClient and RedisClusterClient. You need to provide a RedisURI in order to get Lettuce injected.

RedisURI producer

Implement a simple producer (either field producer or producer method) of RedisURI:

@Produces
public RedisURI redisURI() {
    return RedisURI.Builder.redis("localhost").build();
}

Lettuce also supports qualified RedisURI's:

@Produces
@PersonDB
public RedisURI redisURI() {
    return RedisURI.Builder.redis("localhost").build();
}

Injection

After declaring your RedisURI's you can start using Lettuce in your classes:

public class InjectedClient {

    @Inject
    private RedisClient redisClient;

    @Inject
    private RedisClusterClient redisClusterClient;

    @Inject
    @PersonDB
    private RedisClient redisClient;

    private RedisConnection<String, String> connection;

    @PostConstruct
    public void postConstruct() {
        connection = redisClient.connect();
    }

    public void pingRedis() {
        connection.ping();
    }

    @PreDestroy
    public void preDestroy() {
        if (connection != null) {
            connection.close();
        }
    }
}

Activating Lettuce’s CDI extension

By default, you just drop Lettuce on your classpath and declare at least one RedisURI bean. That’s all.

The CDI extension registers one bean pair (RedisClient and RedisClusterClient) per discovered RedisURI. This means, if you do not declare any RedisURI producers, the CDI extension won’t be activated at all. This way you can use Lettuce in CDI-capable containers without even activating the CDI extension.

All produced beans (RedisClient and RedisClusterClient) remain active as long as your application is running since the beans are @ApplicationScoped.

Clone this wiki locally