Cache your JHipster with Caffeine
Tags: jhipster, cache, java, spring
Published: 2021-08-13 10:24:05

Hi my fellow hipsters, 
JHipster could not be hype if we don’t add frequently top features. Today I would like to introduce you a new cache option in JHipster, named Caffeine. I understand how you can be impatient to know all about this, but keep calm, take a coffee and enjoy.

## CaffeWho ?

Caffeine is a cache solution for boosting your application performances. According to the official Github project :
> Caffeine provides an in-memory cache using a Google Guava inspired API. The improvements draw on our experience designing [Guava’s cache](https://github.com/google/guava/wiki/CachesExplained) and [ConcurrentLinkedHashMap](https://code.google.com/p/concurrentlinkedhashmap).

The project counts 27 contributors and more than 6k stars on Github. The first version was released on march 2015.

Fortunately for us a [Spring cache](https://docs.spring.io/spring/docs/current/spring-framework-reference/integration.html#cache-store-configuration-caffeine) implementation is available.

Learn more at [https://github.com/ben-manes/caffeine](https://github.com/ben-manes/caffeine)

## Why using a cache ?

Using a cache is a must have for me. With JHipster we always give importance to this kind of [solutions](https://www.jhipster.tech/using-cache/). Using efficiently a cache will improve a lot your performances, especially when you have need to retrieve data that are not updated so frequently.

## How using Caffeine with JHipster

As usual, we have made it easy to use for you. You just need to update your JHipster to the last version and start generating a project. At the spring cache abstraction question, a new answer is available:

![JHipster CLI](https://cdn-images-1.medium.com/max/4704/1*LOCgq81cfB5KVN7XWprlVw.png)

As you can see Caffeine is for local cache with a single node, this mean you should not choose it if you need to scale up your application, especially with microservices. Caffeine is an alternative to EhCache, that’s why the code generated with both options are quite close.

### How do you like your coffee?

Just like other caches with JHipster you can easily configure it.
The cache configuration is available in the following class: *your_package.config.CacheConfiguration.*

``` java
public CacheConfiguration(JHipsterProperties jHipsterProperties) {
    JHipsterProperties.Cache.Caffeine caffeine = jHipsterProperties.getCache().getCaffeine();

    CaffeineConfiguration caffeineConfiguration = new CaffeineConfiguration();
    caffeineConfiguration.setMaximumSize(OptionalLong.of(caffeine.getMaxEntries()));
    caffeineConfiguration.setExpireAfterWrite(OptionalLong.of(TimeUnit.SECONDS.toNanos(caffeine.getTimeToLiveSeconds())));
    caffeineConfiguration.setStatisticsEnabled(true);
    jcacheConfiguration = caffeineConfiguration;
}
```

As we can see, we can tune both maximum_size and expire_after_write options. This two option values are loaded from JHipster properties.
You can change these values by accessing to *application-dev.yml* or *application-prod.yml.*

``` yaml
jhipster:
  cache: # Cache configuration
    caffeine: # Caffeine configuration
      time-to-live-seconds: 3600 # By default objects stay 1 hour in the cache
      max-entries: 100 # Number of objects in each cache entry
```

### More Caffeine pleaaaaase

If you want to create more caches for your items in cache configuration, you have two ways: DIY (do it yourself) or using the great entities generation with the JDL.
For this article I choose the second way (of course you did the same).

This part is not really related to Caffeine, Spring Cache offers a great abstraction layer, that’s why you can have similar part with the EhCache (for example).

There is my simple JDL configuration:

```
entity Region {
	regionName String
}

entity Country {
	countryName String
}

relationship OneToOne {
	Country{region} to Region
}
```

Let’s import it to our application: *jhipster import-jdl my_jdl.jh*

Our new classes are now created. Let’s take a look to the cache config:

``` java
createCache(cm, com.mycompany.myapp.domain.Region.class.getName());
createCache(cm, com.mycompany.myapp.domain.Country.class.getName());
```

Here, JHipster add a new cache, defined by the entity name, in the Spring cacheManager. The only thing we have to do, is to tell to Spring where we want to use the cache.
Let’s create a new query in the country repository:

``` java
@Cacheable("com.mycompany.myapp.repository.Country")
Country findCountriesByCountryNameIsStartingWith(String countryNameStarter);
```

So, every time I will call this method with the same parameter, from my repository, I will get values from the cache if values have already been retrieved before. Our cache is successfully configured and used.

## Conclusion

Using a cache is a real way to improving performances and avoiding overload your database. With JHipster we always focus on performance issues and that’s why we want the best caches solutions for our users.
Caffeine is now offered by JHipster as a solution cache.

Special thanks to [Sudharaka Palamakumbura](https://www.linkedin.com/in/sudharakap/) who did the PR to integrate Caffeine. If you want to, like Sudharaka, help the project to grow up, come on the [Github project](https://github.com/jhipster/generator-jhipster).