Développeur Full Stack
En tant qu’Ingénieur Développeur FULLSTACK et depuis Janvier 2023, il est responsable d’équipe au sein du Pôle Logiciel.
JS – ANGULAR
GUIDE MISE EN CACHE AVEC
SPRING-BOOT
Qu'est-ce que la mise en cache ?
Cache de Spring
Spring boot prend en charge la mise en cache. Vous pouvez utiliser n’importe quel fournisseur de
cache externe pour mettre en cache des objets.
Voici le flux de contrôle d’une application Spring boot avec la mise en cache activée.
- JCache(EhCache 3, Hazelcast, Infinispan, and others)
- EhCache 2.x
- Hazelcast
- Infinispan
- Couchbase
- Redis
- Caffeine
- Simple
Une configuration séparée est requise si l’un de ces fournisseurs de cache est utilisé. Cet article
ne couvre que le support de la mise en cache par défaut de Spring boot.
Configuration du cache de Spring
Annotations du cache de Spring
Voici les annotations dont vous avez besoin pour ajouter le support de la mise en cache à
l’application Spring boot.
1. @EnableCaching
Cette annotation est utilisée pour informer Spring boot que nous voulons utiliser la mise en cache
dans cette application.
Cette annotation peut être appliquée sur la classe principale de Spring boot comme indiqué cidessous.
@SpringBootApplication
@ComponentScan(“com.ebenyx.template.jsf”)
@EnableCaching
public class CachingApplication {
public static void main(String[] args) {
SpringApplication.run(CachingApplication.class,
args);
}
}
On peut aussi l’appliquer sur une classe de configuration Spring comme ci-dessous.
@Configuration
@EnableCaching
public class AppConfig { }
@Configuration
@EnableCaching
public class CacheConfigurer {
@Bean
public
CacheManagerCustomizer
cacheManagerCustomizer() {
return new
CacheManagerCustomizer() {
@Override
public void customize(ConcurrentMapCacheManager
cacheManager) {
cacheManager.setAllowNullValues(false);
}
};
}
}
@Component
@EnableCaching
public class CacheCustomizer implements
CacheManagerCustomizer {
@Override
public void customize(ConcurrentMapCacheManager
cacheManager) {
cacheManager.setAllowNullValues(false);
}
}
@Configuration
@EnableCaching
public class CacheConfigurer {
@Bean
public
CacheManagerCustomizer
cacheManagerCustomizer() {
return new
CacheManagerCustomizer() {
@Override
public void customize(ConcurrentMapCacheManager
cacheManager) {
cacheManager.setAllowNullValues(false);
}
};
}
}
@Cacheable("posts")
public Post findById(Integer postId) {
// fetch post from database
}
@CachePut("posts")
public void updatePost(Post post){
// update post object
}
@CachePut possède les mêmes attributs que @Cacheable tels que la valeur, la clé, la condition,
etc., et ils se comportent de la même manière en ce qui concerne l’opération de mise à jour
4. @CacheEvict
Cette annotation est utilisée pour indiquer une opération de suppression des données du cache
et est appliquée sur la méthode qui supprime l’objet de la base de données comme indiqué cidessous.
@CacheEvict("posts")
public void deletePost(Integer postId) {
// delete post object
}
Là encore, @CacheEvict possède les mêmes attributs que @Cacheable tels que la valeur, la clé, la
condition, etc., et ils se comportent de la même manière en ce qui concerne l’opération de
suppression.
@Service
@CacheConfig(cacheNames="posts")
public class PostService {
@Cacheable
public Post findById(Integer postId) { }
}
@CachePut(value="titles", unless="#result.length() < 50")
public String getTitle(Post post) {
// fetch post with given id
}
unless nous permet de mettre en cache des objets sur la base de la sortie, contrairement à la
condition qui effectue la mise en cache sur la base de l’entrée.
N’oubliez pas que l’attribut unless n’est disponible qu’avec @CachePut.
Main class
package com.codippa;
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplicat
ion;
import
org.springframework.cache.annotation.EnableCaching;
import
org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ComponentScan("com.codippa")
public class CachingApplication {
public static void main(String[] args) {
SpringApplication.run(CachingApplication.class,
args);
}
}
Post class
package com.codippa;
public class Post {
private Integer postId;
private String title;
/**
* Constructor
*/
public Post(Integer postId, String title) {
this.postId = postId; this.title = title;
}
// getter and setter methods
}
Controller class
package com.codippa;
import org.springframework.stereotype.Controller;
import
org.springframework.web.bind.annotation.DeleteMapping;
import
org.springframework.web.bind.annotation.GetMapping;
import
org.springframework.web.bind.annotation.PathVariable;
import
org.springframework.web.bind.annotation.PostMapping;
import
org.springframework.web.bind.annotation.ResponseBody;
import
org.springframework.beans.factory.annotation.Autowired;
@Controller
public class PostController {
@Autowired PostService service;
@GetMapping("/posts/{id}")
public @ResponseBody Post findById(@PathVariable("id")
Integer postId) {
return service.findById(postId);
}
@PostMapping("/updatepost")
public void updatePost(Post post) {
service.updatePost(post);
}
@DeleteMapping("/posts/{id}")
public void deleteById(@PathVariable("id") Integer
postId) {
service.deleteById(postId);
}
}
Service class
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class PostService {
@Cacheable("posts")
public Post findById(Integer postId) {
System.out.println("#### Fetching Post ######");
return new Post(postId, "Demo post");
}
@CachePut("posts")
public void updatePost(Post post) {
// update post
}
@CacheEvict("posts")
public void deleteById(Integer postId) {
// delete post
}
}
Pour vérifier que la mise en cache fonctionne,
cliquez sur URL,
http://localhost:8080/posts/1 et regardez la console.
Elle devrait afficher
#### Fetching Post ######