Gestione della cache in Spring Boot e Java

Mattepuffo's logo
Gestione della cache in Spring Boot e Java

Gestione della cache in Spring Boot e Java

In Spring Boot abbiamo delle "dipendenze" apposite per gestire la cache.

In questo articolo vediamo come usarle.

Faremo una richiesta al database, e poi una modifica del record per testarne il funzionamento.

Io sto usando JPA per la connessione, ma non è obbligatorio.

Inoltre qui sotto vi indico solo le dipendenze per il caching, vi lascio a voi il discorso connessione.

Comunque vi riporto tutto il codice.

Se usate Maven:

<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-context</artifactId>
	<version>6.2.3</version>
</dependency>

<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-context-support</artifactId>
	<version>6.2.3</version>
</dependency>

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-cache</artifactId>
	<version>3.3.2</version>
</dependency>

Poi nel file application.properties impostiamo la connessione:

spring.application.name=test-springboot-java
spring.datasource.url=jdbc:mysql://HOST:3306/DB_NOME
spring.datasource.username=USER
spring.datasource.password=PWD
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect

Questo il model per la tabella:

package com.example.test_springboot_java.models;

import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
@Entity
@Table(name = "persone")
public class Persona {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private int id;

  private String email;
}

Io sto udando Lombock, ma non è obbligatorio.

Il repository:

package com.example.test_springboot_java.repositories;

import com.example.test_springboot_java.models.Persona;
import org.springframework.data.jpa.repository.JpaRepository;

public interface PersonaRepository extends JpaRepository<Persona, Integer> {
}

Il Service:

package com.example.test_springboot_java.service;

import com.example.test_springboot_java.models.Persona;
import com.example.test_springboot_java.repositories.PersonaRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class PersonaService {

  @Autowired
  PersonaRepository repository;

  @Cacheable(value = "persone")
  public Optional<Persona> getById(int id) {
    return repository.findById(id);
  }

  @CacheEvict(value = "persone")
  public void updateById(int id) {
    Persona persona = repository.getReferenceById(id);
    persona.setEmail("e@e.it");
    repository.save(persona);
  }
}

Come vedete la nuova email l'ho cablata nel codice per semplicità; ovviamente andrà presa dalla richiesta HTTP.

Nell'update faccio l'evit della cache, indicando di cosa faccio la cancellazione; se non lo fate ed eseguite di nuovo la richiesta, avrete lo stesso valore anche dopo l'update.

Fate un pò di prove in autonomia.

Questo il controller per fare i test:

package com.example.test_springboot_java.controllers;

import com.example.test_springboot_java.models.Persona;
import com.example.test_springboot_java.service.PersonaService;
import org.json.simple.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;

@RestController
@RequestMapping(path = "/test")
public class TestController {

  @Autowired
  PersonaService service;

  @GetMapping(path = "/", produces = MediaType.APPLICATION_JSON_VALUE)
  @ResponseStatus(HttpStatus.OK)
  public String index() {
    Optional<Persona> persona = service.getById(1);

    JSONObject obj = new JSONObject();
    obj.put(persona.get().getId(), persona.get().getEmail());

    return String.valueOf(obj);
  }

  @GetMapping(path = "/update", produces = MediaType.APPLICATION_JSON_VALUE)
  @ResponseStatus(HttpStatus.OK)
  public String update() {
    service.updateById(1);
    return "OK";
  }

}

Ho impostato due routes sempre in GET per semplicità.

Questo il nostro main, dove abilitiamo il caching:

package com.example.test_springboot_java;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@EnableCaching
public class TestSpringbootJavaApplication {

	public static void main(String[] args) {
		SpringApplication.run(TestSpringbootJavaApplication.class, args);
	}

}

Il caching di Spring Boot fa i controlli in autonomia sull'esistenza di un oggetto in cache.

Grazie al forumt di HTML.it per le dritte.

Enjoy!


Condividi

Commentami!