This section dives into the Coherence Spring Boot module. It explains how to use Coherence’s dedicated support for Spring Boot, e.g., Autoconfiguration.

1. Getting Started

In order to start using Coherence with Spring Boot you have to add the coherence-spring-boot-starter dependency as well as the desired version of Coherence.

Example 1. Adding the Coherence Spring Boot Starter Dependency
Maven
<dependencies>
    <dependency>
        <groupId>com.oracle.coherence.spring</groupId>
        <artifactId>coherence-spring-boot-starter</artifactId>
        <version>4.0.0-SNAPSHOT</version>
    </dependency>
    <dependency>
        <groupId>com.oracle.coherence.ce</groupId>
        <artifactId>coherence</artifactId>
        <version>22.09</version>
    </dependency>
</dependencies>
Gradle
dependencies {
    compile("com.oracle.coherence.spring:coherence-spring-boot-starter:4.0.0-SNAPSHOT")
    compile("com.oracle.coherence.ce:coherence:22.09")
}
As Coherence Spring takes advantage of the new Coherence Bootstrap API, it requires Oracle Coherence CE version 20.12 or higher.

2. Using Coherence with Spring Boot

By adding the coherence-spring-boot-starter dependency, AutoConfiguration will be activated via the CoherenceAutoConfiguration class. This will also bind the CoherenceProperties class for further configuration. The YAML configuration for Spring Boot’s Coherence support may look like the following:

coherence:
  logging:
    destination: slf4j
    logger-name: MyCoherence
  sessions:
  - name: default
    config: "coherence-cache-config.xml"
    priority: 1
  - name: test
    config: "test-coherence-config.xml"
    priority: 2
  properties:
    coherence.log.limit: 400
    coherence.log.level: 1

The following configuration properties are available.

Table 1. Coherence Configuration Properties
Key Default Value Description

coherence.logging.destination

slf4j

The type of the logging destination.

coherence.logging.severity-level

Specifies which logged messages are emitted to the log destination. The legal values are -1 to 9. No messages are emitted if -1 is specified. More log messages are emitted as the log level is increased.

coherence.logging.logger-name

Coherence

Specifies a logger name within chosen logging system

coherence.logging.message-format

Specifies how messages that have a logging level specified are formatted before passing them to the log destination.

coherence.logging.character-limit

Specifies the maximum number of characters that the logger daemon processes from the message queue before discarding all remaining messages in the queue

coherence.sessions.<type>

N/A

Indicates the type of the session. One of the following: grpc, server, client

coherence.sessions.<type>[0].name

Name of the session.

coherence.sessions.<type>[0].config

The Coherence cache configuration URI for the session

coherence.sessions.<type>[0].priority

SessionConfiguration#DEFAULT_PRIORITY

The priority order to be used when starting the session. Sessions will be started with the lowest priority first.

coherence.sessions.<type>[0].scope-name

The scope name for the session.

coherence.instance.type

Depends on session type. As soon as you specify a server session, it defaults to cluster

Type of the Coherence instance: cluster or client

coherence.server.startup-timeout

5m

Overrides the default startup-timeout when starting Coherence.

Session-related configuration properties are defined based on the session type in:

Many properties are translated into native Coherence properties. If both Spring Boot property AND a native property coherence.properties.* are configured, the Spring Boot property is used.

If the provided Spring Boot configuration properties are not sufficient for your needs, you can also specify any of the native Coherence properties. For a list of available native properties, please consult the reference guide chapter on System Property Overrides.

3. Support of the Spring Boot ConfigData API

Since Spring Boot 2.4.x, you can define your own custom config locations. This allows you to import these config locations as property sources. As such, Coherence Spring allows you to use a Coherence cluster as a source of configuration data for your Spring Boot based applications.

Please also consult the Spring Boot reference guide on Externalized Configuration, especially the chapter on Importing Additional Data.
Please also see the chapter on Coherence Spring Cloud Config.

You can trigger the import of remote configuration properties with the Spring Boot property spring.config.import using the value coherence:. You will also need the corresponding Coherence config-client configured to specify any remote connection settings for your Coherence cluster as well as settings specifying how properties will be applied, e.g., the name of the application used to fetch remote properties.

spring:
  config:
    import: "coherence:"
coherence:
  config-client:
    application-name: berlin
    profile: kona

Many properties have sensible default values. Please see class CoherenceConfigClientProperties for details.

4. Caching with Spring Boot

If you have not already done so, please read the chapter Configuring Coherence Cache for Spring first.

In this chapter, we see how we can use caching with Coherence in Spring Boot. As long as coherence-spring-boot-starter is added to your project, and caching is enabled via @EnableCaching, Coherence Autoconfiguration will automatically provide a CoherenceCacheManager (implementing Spring’s CacheManager) to the ApplicationContext. However, the CacheManager is only added if no CacheManager was configured explicitly beforehand.

Once that is in place, you can take advantage of Spring’s Cache abstraction backed by Coherence and use Spring’s annotations such as @Cacheable, @CacheEvict, @CachePut etc.

When learning about Coherence’s Spring cache abstraction support, please familiarize yourself with the following resources:

4.1. Configure Circuit Breakers with Resilience4j

Generally, it is recommended to configure and run Coherence as part of your application as a cluster member. However, caching can also be configured using Coherence in client mode via Coherence*Extend or gRPC. However, in client mode you may encounter failures and/or reliability situations due to network issues resulting in cache failures. In those situations, it would be desirable to retrieve the data from the persistence store instead, until the connectivity is being restored. Similarly, your application may encounter request timeout issues when retrieving data from the cache.

This is where the circuit breaker pattern can be quite helpful, allowing you to gracefully degrade functionality via configurable fallback methods. Spring Boot has excellent support via Resilience4j, a fault tolerance library.

Coherence Spring includes an example application that illustrates a basic circuit breaker use-case via Resilience4j. In this example a Spring Boot-based application has REST endpoints to retrieve Books:

  • GET /api/books - Retrieve all books

  • GET /api/books/1234 - Retrieve a single book

  • DELETE /api/books/1234 - Evict a book from the Coherence cache

By default, 2 books are inserted into the in-memory database AND into the Coherence cache. The application uses Spring’s cache abstraction backed by Coherence. The application is configured to connect to Coherence on a separate node via Coherence*Extend. The use-case of the application is that when you shut down the Coherence server, the application won’t be able to retrieve cached domain data from Coherence. Instead, the Resilience4j circuit breaker will catch the connection exception and invoke a fallback method. In this case the data is returned from the main persistence store, bi-passing the Spring cache until the connection to the Coherence server has been restored.

4.1.1. Running the Example

The example application consists of 2 applications:

  • circuit-breaker-cache-demo-server - The stand-alone Coherence instance

  • circuit-breaker-cache-demo-app - The client application that will connect to the Coherence server via Coherence*Extend

Let’s first run the server:

cd samples/circuit-breaker-cache-demo/circuit-breaker-cache-demo-server
mvn spring-boot:run

Now we need to run the actual application:

cd samples/circuit-breaker-cache-demo/circuit-breaker-cache-demo-app
mvn spring-boot:run

When the application starts, 2 books are added not only to the persistence store (HSQLDB) but also to the Coherence cache. However, this is not true for the retrieve of all books in this example.

Get all books

When you retrieve a list of all books. You will see that the main relevant business method is executed and the data retrieved from the database. But at this point the collection of books is added to the Coherence cache for the first time.

List all books
curl -i \
  -H "Accept: application/json" \
  -H "Content-Type:application/json" \
  -X GET "http://localhost:8090/api/books"

Thus, when you retrieve the list of books again, you will see in the logs:

Cache entry for key 'SimpleKey []' found in cache 'allBooks'

Get a Single Book

When retrieving a single book, on the other side, the book is retrieved from the Coherence cache right away.

Get a single book
curl -i \
  -H "Accept: application/json" \
  -H "Content-Type:application/json" \
  -X GET "http://localhost:8090/api/books/1"

You will see something like:

Cache entry for key '1' found in cache 'books'

Let’s evict the book from the Coherence cache:

Evict book with id 1 from the Coherence Cache
curl -i \
  -H "Accept: application/json" \
  -H "Content-Type:application/json" \
  -X DELETE "http://localhost:8090/api/books/1"

Now, when you retrieve the book again, it will be retrieved from the persistence store instead. Let’s do something more interesting. When retrieving a single book we added a special case to the business service, where the retrieval of a book with id 42 will cause a BusinessException to be thrown.

Get a single book throwing a business exception
curl -i \
  -H "Accept: application/json" \
  -H "Content-Type:application/json" \
  -X GET "http://localhost:8090/api/books/42"

As you may notice, an Internal Server Error (HTTP status 500) is returned to you. Additionally, a BusinessException was thrown and handled by a Resilience4j fallback method.

Resilience4j selects fallback methods based on the specificity of the thrown Exceptions in relation to the exception declared in the fallback method. Thus, if you have multiple fallback methods, the method with the most specific exception is being chosen. Furthermore, it is important to know that expected exceptions (e.g. Business Exceptions) that you have included in the list of ignoreExceptions via application.yaml:

  • resilience4j.circuitbreaker.configs.*.ignoreExceptions

will also trigger the execution of fallBack methods, but it will not change the state of the circuit breaker.

Next, we will first shut down the Coherence server, and then we try to retrieve a single book with id 1. As you see, the JSON response is still the same (The book data is returned). However, when you look at the logs, you will see:

getBook fallback method (For Throwable) was called: Unable to locate ProxyService 'ExtendTcpCacheService' ...

So basically, the CacheManager was unable to connect to the Coherence instance and therefore the Circuit Breaker kicked in, calling the fallback method instead, and thus returning the Book not from the cache but from the persistence store.

4.1.2. Monitoring the Circuit Breaker

Spring Boot and Resilience4j also provide facilities to monitor the state of the Circuit Breaker via Spring Boot’s health-endpoint as well as its circuit breaker events endpoint:

Spring Boot Health Endpoint
{
  "status":"UP",
  "components":{
    "circuitBreakers":{
      "status":"UNKNOWN",
      "details":{
        "coherence":{
          "status":"CIRCUIT_OPEN",
          "details":{
            "failureRate":"100.0%",
            "failureRateThreshold":"5.0%",
            "slowCallRate":"0.0%",
            "slowCallRateThreshold":"100.0%",
            "bufferedCalls":3,
            "slowCalls":0,
            "slowFailedCalls":0,
            "failedCalls":3,
            "notPermittedCalls":8,
            "state":"OPEN"
          }
        }
      }
    },
    "db":{
      "status":"UP",
      "details":{
        "database":"HSQL Database Engine",
        "validationQuery":"isValid()"
      }
    },
    "diskSpace":{
      "status":"UP",
      "details":{
        "total":2000796545024,
        "free":1490744430592,
        "threshold":10485760,
        "exists":true
      }
    },
    "ping":{
      "status":"UP"
    }
  }
}

For demonstrating purposes we enabled the relevant health endpoints via Spring Boot configuration in application.yaml:

management.endpoints.web.exposure.include: "*"
management.endpoint.health.show-details: always

You may not want to do this in production. This is solely for demonstration purposes, especially as no security is configured for this application.

4.1.3. Add Resilience4j Dependencies

In order to use Resilience4j in your Coherence Spring project with Spring Boot, you need to add the following dependencies:

Example 2. Resilience4j Spring Boot Dependency
Maven
<dependency>
    <groupId>io.github.resilience4j</groupId>
    <artifactId>resilience4j-spring-boot2</artifactId>
    <version>1.7.1</version>
</dependency>
Gradle
implementation("io.github.resilience4j:resilience4j-spring-boot2:1.7.1")

4.1.4. Resilience4j Annotations

In order to add circuit-breaker capabilities to our @Cacheable business methods in DefaultBookService, we simply add the @CircuitBreaker annotations, e.g.:

@Cacheable("allBooks")
@CircuitBreaker(name = "coherence", fallbackMethod = "getAllBooksFallback")
@Override
public List<Book> getAllBooks() {
 ...
}

The key is the specified fallback method: whenever an exception occurs, the fallback method is being executed. You can have multiple fallback methods, specifying different exception types. Resilience4j will then select the fallback methods based on the specificity of the thrown exception.

When dealing with fallback method, it may at times be necessary to call other methods of the same services that you expect to be proxied, e.g. have applied annotations etc. However, when calling other methods in the same service, you are calling those methods without the relevant AOP aspects applied to them. You may either need to refactor those methods into another Spring bean or can actually inject the same service into the service. This type of injection call self injection or self autowiring has been supported since Spring 4.3.

5. Configure Hibernate Second-Level Caching

Spring’s cache abstraction is not your only option with regard to caching. Another option is to use Hibernate’s Second-Level cache support.

When using only Hibernate’s second-level cache without the requirement of using Coherence for non-Hibernate application needs, you may want to disable Coherence’s auto-configuration support for Spring Boot as it is not needed:

Disable CoherenceAutoConfiguration
@SpringBootApplication(exclude=CoherenceAutoConfiguration.class)
public class HibernateApplication {
    public static void main(String[] args) {
        SpringApplication.run(HibernateApplication.class, args);
    }
}

In order to configure Hibernate Second-Level Caching for Coherence using Spring Boot, you simply have to set the Hibernate property hibernate.cache.region.factory_class to com.oracle.coherence.hibernate.cache.CoherenceRegionFactory.

Your Spring Boot application.yaml file may look like the following:

RegionFactory Configuration using YAML
spring:
  application:
    name: Your Spring Boot App
  jpa:
    properties:
      hibernate.cache.region.factory_class: com.oracle.coherence.hibernate.cache.CoherenceRegionFactory (1)
      hibernate.cache.use_query_cache: true
      hibernate.cache.use_second_level_cache: true
      hibernate.format_sql: true
      hibernate.generate_statistics: true
      hibernate.show_sql: true
      hibernate.use_sql_comments: false
...
1 Configuring the CoherenceRegionFactory

For more detailed information please see the Caching chapter of the Hibernate reference documentation.

5.1. Hibernate Second Level Cache Example

The Coherence Spring source code repository also provides an example application, illustrating the Coherence support for Hibernate’s Second Level caching using Spring Boot.

The example application has 1 REST endpoint that can persist, retrieve and delete a Plant object with taxonomic properties such as the genus and species.

Example of a Plant JSON response
 {"id": 1, "genus": "Sabal", "species": "minor", "commonName": "Dwarf palmetto"}

5.1.1. Run the Hibernate Application

First, let’s build the application:

Build the Coherence Server instance
 $ ./mvnw clean package -pl samples/hibernate-cache-demo

Next, run the application:

Run the Spring Boot application
 $ java -jar samples/hibernate-cache-demo/target/hibernate-cache-demo-4.0.0-SNAPSHOT.jar

The application will be available on port 9090.

Add a plant
curl -i \
  -H "Accept: application/json" \
  -H "Content-Type:application/json" \
  -X POST --data '{"genus": "Sabal", "species": "minor", "commonName": "Dwarf palmetto"}' \
  "http://localhost:9090/plants"
List all plants
curl -i \
  -H "Accept: application/json" \
  -H "Content-Type:application/json" \
  -X GET "http://localhost:9090/plants"
Get a single plant
curl -i \
  -H "Accept: application/json" \
  -H "Content-Type:application/json" \
  -X GET "http://localhost:9090/plants/1"
Delete a plant
curl -i \
  -H "Accept: application/json" \
  -H "Content-Type:application/json" \
  -X DELETE "http://localhost:9090/plants/1"

When retrieving a single plant repeatedly, you will see no SQL printed to the console. Instead, the plant is returned from the second level cache as illustrated by the printed out cache statistics.

Hibernate Cache Statistics
2021-06-28 16:12:42.545  INFO 29022 --- [nio-9090-exec-7] i.StatisticalLoggingSessionEventListener : Session Metrics {
27579 nanoseconds spent acquiring 1 JDBC connections;
0 nanoseconds spent releasing 0 JDBC connections;
0 nanoseconds spent preparing 0 JDBC statements;
0 nanoseconds spent executing 0 JDBC statements;
0 nanoseconds spent executing 0 JDBC batches;
0 nanoseconds spent performing 0 L2C puts;
1587296 nanoseconds spent performing 1 L2C hits;
0 nanoseconds spent performing 0 L2C misses;
0 nanoseconds spent executing 0 flushes (flushing a total of 0 entities and 0 collections);
0 nanoseconds spent executing 0 partial-flushes (flushing a total of 0 entities and 0 collections)
}

In order to also cache the results of query executions, you must provide query hints to Hibernate. The PlantRepository class has a custom query using such a hint for illustration purposes:

Using Query Hints
@QueryHints(@QueryHint(name = org.hibernate.annotations.QueryHints.CACHEABLE, value = "true"))
@Query("select p from Plant p")
List<Plant> getAllPlantsCacheable();

You can see the cache being used by retrieving the list of plants with an additional request parameter use-cache:

List all plants
curl -i \
  -H "Accept: application/json" \
  -H "Content-Type:application/json" \
  -X GET "http://localhost:9090/plants?use-cache=true"

6. Spring Session Support

Coherence Spring also provides support for Spring Session. This includes auto-configuration support as well as a set of Coherence-specific configuration properties. Before you continue, please consider reading the chapter on Coherence Spring Session first.

In order to activate Spring Session support for Spring Boot, you must have the following dependencies added to your project:

Example 3. Add Coherence Spring Session Support
Maven
<dependencies>
    <dependency>
        <groupId>com.oracle.coherence.spring</groupId>
        <artifactId>coherence-spring-boot-starter</artifactId>
        <version>4.0.0-SNAPSHOT</version>
    </dependency>
    <dependency>
        <groupId>com.oracle.coherence.spring</groupId>
        <artifactId>coherence-spring-session</artifactId>
        <version>4.0.0-SNAPSHOT</version>
    </dependency>
    <dependency>
        <groupId>com.oracle.coherence.ce</groupId>
        <artifactId>coherence</artifactId>
        <version>22.09</version>
    </dependency>
</dependencies>
Gradle
dependencies {
    compile("com.oracle.coherence.spring:coherence-spring-boot-starter:4.0.0-SNAPSHOT")
    compile("com.oracle.coherence.spring:coherence-spring-session:4.0.0-SNAPSHOT")
    compile("com.oracle.coherence.ce:coherence:22.09")
}

Basically, adding the coherence-spring-session dependency will activate the CoherenceSpringSessionAutoConfiguration class. Auto-configuration will back-off in certain situations:

  • Set property coherence.spring.session.enabled to false

  • Define spring.session.store-type. Any value will deactivate auto-configuration.

The following Coherence-specific configuration properties are available:

Table 2. Coherence Configuration Properties
Key Default Value Description

coherence.spring.session.enabled

false

Set to true to enable Spring Session support

coherence.spring.session.map-name

spring:session:sessions

Name of the map used to store sessions

coherence.spring.session.flush-mode

ON_SAVE

Sessions flush mode. Determines when session changes are written to the session store.

coherence.spring.session.save-mode

ON_SET_ATTRIBUTE

The session save mode determines how session changes are tracked and saved to the session store.

7. Coherence Messaging Support

Support for injecting Coherence Publishers is enabled automatically by adding the coherence-spring-boot-starter dependency. By default, base package to scan for @CoherencePublisher annotated interfaces is derived from the main class annotated with @SpringBootApplication. Base package can be overridden by annotating configuration class with @CoherencePublisherScan as described at Messaging with Coherence Topics.

8. Coherence Metrics

By adding the coherence-spring-boot-starter and com.oracle.coherence.ce:coherence-micrometer dependencies auto-configuration will register CoherenceMicrometerMetrics and publish Coherence Metrics under the coherence. name.

To disable the auto-configured Coherence metrics even when coherence-micrometer module is on the classpath, set the following property:

application.yaml
management:
  metrics:
    enable:
      coherence: false

9. Spring Data Support

Coherence Spring’s support for Spring Data also contain auto-configuration support for Spring Boot. The auto-configuration is activated as soon as the Coherence Spring Data dependency is added to your Spring Boot project.

Example 4. Add Coherence Spring Data Support
Maven
<dependencies>
    <dependency>
        <groupId>com.oracle.coherence.spring</groupId>
        <artifactId>coherence-spring-boot-starter</artifactId>
        <version>4.0.0-SNAPSHOT</version>
    </dependency>
    <dependency>
        <groupId>com.oracle.coherence.spring</groupId>
        <artifactId>coherence-spring-data</artifactId>
        <version>4.0.0-SNAPSHOT</version>
    </dependency>
    <dependency>
        <groupId>com.oracle.coherence.ce</groupId>
        <artifactId>coherence</artifactId>
        <version>22.09</version>
    </dependency>
</dependencies>
Gradle
dependencies {
    compile("com.oracle.coherence.spring:coherence-spring-boot-starter:4.0.0-SNAPSHOT")
    compile("com.oracle.coherence.spring:coherence-spring-data:4.0.0-SNAPSHOT")
    compile("com.oracle.coherence.ce:coherence:22.09")
}

There is no need to add the @EnableCoherenceRepositories annotation, as the Coherence Spring Data auto-configuration support, will automatically detect any Coherence repositories. In fact, adding @EnableCoherenceRepositories to your Spring Boot project, will cause auto-configuration to back-off.

Auto-configuration can also be de-activated by setting environment property coherence.spring.data.repositories.enabled to false.