Redis - L2 cache

Configure the redis server to use by setting ebean.redis properties in main/resources/application.yaml like below:

Note that for property configuration to work when we programmatically create Database via DatabaseFactory and DatabaseConfig, then we need to make sure that we use DatabaseConfig.loadFromProperties() to load the properties.

ebean:
  redis:
    server: test-server
    port: 99
    minIdle: 2
    maxIdle: 20
    maxTotal: 20
    maxWaitMillis: 300

For testing purposes set ebean.test.redis property to latest in in test/resources/application-test.yaml. This will get ebean-test to automatically start a redis docker container for use with L2 caching.

ebean:
  test:
    redis: latest
    platform: h2 # h2, postgres, mysql, oracle, sqlserver, sqlite
    ddlMode: dropCreate # none | dropCreate | migrations | create
    dbName: my_app

ebean-redis dependency

Add ebean-redis as a dependency. This will automatically register itself with ebean as the L2 cache service.

<dependency>
  <groupId>io.ebean</groupId>
  <artifactId>ebean-redis</artifactId>
  <version>14.1.0</version>
</dependency>

@Cache

Entity beans annotated with @Cache will now use redis for L2 caching.

@Cache(enableQueryCache = true, nearCache = true, naturalKey = "name")
@Entity
public class Person extends EBase {

  public enum Status {
    NEW,
    ACTIVE,
    INACTIVE
  }

  @Index(unique = true)
  String name;

  Status status;

  LocalDate localDate;

  String notes;

  public Person(String name) {
    this.name = name;
    this.status = Status.NEW;
  }
  ...
}

Docker container

We can programmatically start a docker container version of Redis.

The below uses ebean-test-docker dependency which already comes with ebean-test. If we do not have a dependency on ebean-test then add io.ebean:ebean-test-docker:5.0 as a dependency.

package main;

import io.ebean.docker.commands.RedisContainer;

public class Main {

  public static void main(String[] args) {

    RedisContainer container = RedisContainer.newBuilder("latest")
      .build();

      container.start();
  }
}