English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Spring Boot 缓存

Il framework Spring fornisce cache in modo trasparente nelle applicazioni Spring. In Spring,Astrazione di cachingÈ un meccanismo che permette di utilizzare in modo coerente vari metodi di caching senza influenzare il codice.

Astrazione di caching

Il meccanismo di astrazione di caching è adatto per Metodo Java. L'obiettivo principale dell'astrazione di caching è utilizzare le informazioni esistenti nella cacheridurreNumero di esecuzioni. È adatto per metodi costosi come CPU o Legame IO.

Ogni volta che viene chiamato il metodo, l'astrazione applica l'azione di caching al metodo. Verifica se il metodo è già stato eseguito per i parametri dati.

Se lo è, restituire direttamente il risultato della cache senza eseguire il metodo reale.Se non lo è, eseguire prima il metodo, memorizzare il risultato nella cache e restituirlo all'utente.

Attenzione: Questo metodo è adatto solo per garantire che il metodo restituisca lo stesso risultato per un input dato. Non importa quante volte viene eseguito il metodo.

Il desenvolvedor deve prestare attenzione a due cose quando si gestisce l'astrazione della cache.

Dichiarazione di cache: esso indica il metodo da cacheare. Cache configuration: Backup cache for storing and reading data.

cache

Cache is a part of temporary memory (RAM). It is located between the application and the persistent database. It stores recently used data to minimize the number of times the database is hit. In other words, caching is to store data for future reference.

Why use caching?

The main reason for using caching is to access data faster and cheaper. When multiple requests are made to highly requested resources, caching resources is usually beneficial for developers, so that it can respond quickly. Using caching in applications can enhance the performance of the application. Data access from memory is always faster than from the database. It reduces monetary costs and opportunity costs.

What data should be cached?

Data that does not change frequently.Frequently used read queries, whose query results do not change for at least a certain period of time in each call.

Cache types

There areFourThe following are types of cache:

In-memory cachingRedis Web server caching CDN cache

In-memory caching

In-memory caching can improve the performance of applications. This is a frequently used area. Memcached e Redis is an example of in-memory caching. It stores key-value pairs between the application and the database. Redis is aIn-memory, distributedAdvanced caching tools that can be used for backup and restore functions. We can also manage caches in distributed clusters.

Redis

Database caching is a mechanism that generates web pages on demand (dynamically) by obtaining data from the database. It involves the client, web application server, and database. It is a cache that stores key-value pairs between the application and the database. Redis is aMulti-tierenvironment. By distributing query workload, it improvesScalabilityePerformance. The most popular database cache is Hibernate's first-level cache.

Web server caching

Web server caching is a way to store data so thatReusemechanism. For example, the copy of the web page provided by the web server. When the user first visits this page, it will be cached. If the user requests the same content again next time, the cache will provide a copy of the page. This can avoid server overload. Web server caching can improve the speed of page delivery and reduce the work that the backend server has to do.

CDN cache

CDN representContent Delivery Network. It is a component used in modern web applications. ThroughreplicationCommon files (such as HTML pages, style sheets), it can improve the delivery of content. JavaScript, images, videos, etc.) are distributed across a set of globally distributedcache servers.

This is why CDN is becoming increasingly popular. CDN relieves the burden on the application source and improves user experience. It retrieves from the nearbyCache edgeorPoint of Presence (PoP)Provide a local copy of the content.

Cache and buffer

cacheBuffer
Cache based最近最少使用.缓冲区基于先进先出
它是页面缓存的大小。它是内存中的原始块I/O缓冲区。
它生存了很长时期。它生存了时期。
我们从缓存中读取.我们写入到缓冲区。
它存储实际文件数据。它存储文件元数据.
它提高了 read 性能。它提高了写入性能。

Spring Boot缓存注解

@EnableCaching

这是一个类级别的注解。我们可以通过使用 @EnableCaching注解在Spring Boot应用程序中启用缓存。它在 org.springframework.cache.annotation 包中定义。它与 @Configuration 类一起使用。

如果没有已定义的CacheManager实例,自动配置将启用缓存并设置 CacheManager 。它会扫描特定的提供程序,如果找不到,则会使用并发的 HashMap创建内存中缓存。

Esempio

在以下示例中, @EnableCaching 注解启用了缓存机制。

@SpringBootApplication
@EnableCaching 
public class SpringBootCachingApplication 
{
public static void main(String[] args) 
{
SpringApplication.run(SpringBootCachingApplication.class, args);
}
}

@CacheConfig

这是一个类级别的注解,提供了与缓存有关的通用设置。它告诉Spring将类的缓存存储在何处。当我们使用注解为类添加注解时,它为该类中定义的任何缓存操作提供了一组默认设置。使用注解,我们不需要多次声明。

Esempio

在下面的示例中,员工是缓存的名称。

@CacheConfig(cacheNames={"employee"}) 
public class UserService
{
//alcuni codice
}

@Caching

当我们同时需要两个注解 @CachePut o @CacheEvict 时使用同样的方法。换句话说,当我们要使用相同类型的多个注解时使用。

但是 Java不允许为给定声明相同类型的多个注解方法。为避免此问题,我们使用 @Caching 注解。

Esempio

在下面的示例中,我们使用了注解 @Caching 并将所有 @CacheEvict 注解分组。

@Caching(evict = {@CacheEvict("phone_number"), @CacheEvict(value="directory", key="#student.id")})public String getAddress(Student student) 
{
//alcuni codice
}

@Cacheable

È un'annotazione di livello metodo. Definisce un cache per il valore di ritorno del metodo. Il framework Spring gestisce le richieste e le risposte del metodo specificate negli attributi dell'annotazione. L'annotazione @Cacheable contiene più opzioni. Ad esempio, possiamo utilizzare value o cacheNames fornitonome cache.

Possiamo anche specificare l'attributo key proprietà utilizzate per identificare univocamente ogni voce nel cache. Se non viene specificata una chiave, Spring utilizzerà un meccanismo di default per creare una chiave.

Esempio

Nell'esempio seguente, abbiamo cacheato< cacheStudentInfo,e id metodo studentInfo()Il valore di ritorno è una chiave unica utilizzata per identificare il cache.

@Cacheable(value="cacheStudentInfo", key="#id")public List studentInfo()
{
//alcuni codice 
return studentDetails;
}

Possiamo anche applicare condizioni utilizzando l'attributo condition dell'annotazione. Quando applichiamo condizioni nell'annotazione, si chiamaCache conditionale.

Ad esempio, se la lunghezza del nome del parametro è inferiore a 20, il seguente metodo verrà cacheato:

@Cacheable(value="student", condition="#name.length<20")public Student findStudent(String name)
{
//alcuni codice
}

@CacheEvict

È un'annotazione di livello metodo. Quando vogliamo eliminare dati obsoleti o non utilizzati dal cache, la utilizzeremo. Deve avere uno o più cache influenzate dall'operazione. Possiamo anche specificare una chiave o una condizione. Se vogliamo un'eliminazione cache ampia, l'annotazione @CacheEvict fornisce un nome chiamato allEntries del parametro. Eliminerà tutti gli elementi, non solo un elemento specifico basato sulla chiave.

Un punto importante su @CacheEvict è che può essere utilizzato insieme a metodi void, poiché questo metodo agisce come trigger. Evita di restituire un valore. D'altra parte, l'annotazione @Cacheable richiede un valore di ritorno, che viene utilizzato per aggiungere/aggiornare i dati nel cache. Possiamo utilizzare l'annotazione @CacheEvict nel modo seguente:

Scerne l'intero cache:

@CacheEvict(allEntries=true)

espellere le voci tramite chiave:

@CacheEvict(key="#student.stud_name")

Esempio

Le seguenti metodologie con annotazioni prelevano dal cache student_data cancellare tutti i dati.

@CacheEvict(value="student_data", allEntries=true) //rimuovere tutte le voci dalla cache
public String getNames(Student student) 
{
//alcuni codice
}

@CachePut

È un'annotazione di livello di metodo. Quando vogliamoAggiornamentocaching senza interferire con l'esecuzione del metodo, utilizzarla. Questo significa che il metodo verrà sempre eseguito e i suoi risultati verranno messi nella cache. Supporta le proprietà dell'annotazione @Cacheable.

Occorre notare che a causa del comportamento diverso degli annotazioni @Cacheable e @CachePut, sono diverse. Ci sono piccole differenze tra gli annotazioni @Cacheable e @CachePut, ossia @ Cacheable Commentosaltare l'esecuzione del metodomentre @CachePut CommentoEseguire questo metodoe poi mettono i risultati nella cache.

Esempio

Le seguenti metodologie aggiornano la cache stessa.

@CachePut(cacheNames="employee", key="#id") //aggiornamento cachepublic Employee updateEmp(ID id, EmployeeData data)
{
//alcuni codice
}

Dipendenza di cache Spring Boot

Per abilitare il meccanismo di cache in un'applicazione Spring Boot, è necessario aggiungere la dipendenza di cache nel file pom.xml. Abilita la cache e configura CacheManager.

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

Esempio di cache Spring Boot

Creiamo un'applicazione Spring Boot e implementiamo al suo interno il meccanismo di cache.

Passo 1: Aprire Spring Initializr http://start.spring.io 。

Passo 2: Selezionare la versione di Spring Boot 2.3.0.M1。

Passo 2: FornireGruppoNome. Forniamo com.w3codebox。

Passo 3: FornireComponente ID. Forniamo spring-boot-cache-example。

Passo 5: Aggiungere dipendenze Spring Web e Abstract Spring Cache.

Passo 6: Fare clic Generate (Generare) pulsante. Quando facciamo clic su "Generare", esso impacchetta la specifica delle confezioni Jar apri il file e scaricalo sul sistema locale.

Passaggio 7: Estrai Copia il file Jar e incollalo nella workspace di STS.

Passaggio 8: Importa cartella del progetto in STS.

File->Import->Progetto Maven esistente->Sfoglia->Scegli la cartella spring-boot-cache-example->Conferma

l'importazione potrebbe richiedere un po' di tempo.

Apriamo pom.xml aprire il file, e guardare quali dipendenze abbiamo aggiunto.

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.3.0.M1</version>
    <relativePath/> <!-- lookup parent from repository -->
  </parent>
  <groupId>com.w3codebox</groupId>
  <artifactId>spring-boot-cache-example</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>spring-boot-cache-example</name>
  <description>Progetto demo per Spring Boot</description>
  <properties>
    <java.version>1.8</java.version>
  </properties>
  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-cache</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
      <exclusions>
        <exclusion>
          <groupId>org.junit.vintage</groupId>
          <artifactId>junit-vintage-engine</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>
  <repositories>
    <repository>
      <id>spring-milestones</id>
      <name>Spring Milestones</name>
      <url>https://repo.spring.io/milestone</url>
    </repository>
  </repositories>
  <pluginRepositories>
    <pluginRepository>
      <id>spring-milestones</id>
      <name>Spring Milestones</name>
      <url>https://repo.spring.io/milestone</url>
    </pluginRepository>
  </pluginRepositories>
</project>

passaggio 9: 打开 SpringBootCacheExampleApplication.java file, aggiungendo l'annotazione @EnableCaching abilita la cache.

SpringBootCacheExampleApplication.java
package com.w3codebox;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@SpringBootApplication
//abilita la cache
@EnableCaching
public class SpringBootCacheExampleApplication 
{
public static void main(String[] args) 
{
SpringApplication.run(SpringBootCacheExampleApplication.class, args);
}
}

Passaggio 10: Nella cartella cartella com.w3codebox.model src/main/java Crea un pacchetto.

Passo 11: Nel pacchetto Model, crea una classe chiamata Customer classi e definisci il seguente contenuto:

definisci treaccountno, customername, acounttypeebalance.Usa Constructor per generareCostruttore .
Con il pulsante destro del mouse clicca su file->sorgente->utilizza campo per generare costruttore->seleziona tutto->genera
GeneraGetters and Setters.
Con il pulsante destro del mouse clicca su file->sorgente->genera Getter e Setter->seleziona tutto->genera

Customer.java

package com.w3codebox.model;
public class Customer 
{
    private int accountno;
    private String customername;
    private String accounttype;
    private double balance;
    public Customer(int accountno, String customername, String accounttype, double balance) 
    {
        this.accountno = accountno;
        this.customername = customername;
        this.accounttype = accounttype;
        this.balance = balance;
    }
    public int getAccountno() 
    {
        return accountno;
    }
    public void setAccountno(int accountno) 
    {
        this.accountno = accountno;
    }
    public String getCustomername() 
    {
        return customername;
    }
    public void setCustomername(String customername) 
    {
        this.customername = customername;
    }
    public String getAccounttype() 
    {
        return accounttype;
    }
    public void setAccounttype(String accounttype) 
    {
        this.accounttype = accounttype;
    }
    public double getBalance() 
    {
        return balance;
    }
    public void setBalance(double balance) 
    {
        this.balance = balance;
    }
}

Passo 11: nella cartella src/main/java all'interno di com.w3codebox.controller il pacchetto.

Passo 12: nel pacchetto Controller, creare un file di nome CustomerController operazioni di seguito:

usando l'annotazione @RestController segnala la classe come Controller . usando l'annotazione @RequestMapping definisce la mappatura per il controllermappatura.abbiamo definito la mappatura/customerinfo .creazionecachePer utilizzare l'annotazione @Cacheable. abbiamo ottenuto i dati utilizzando l'annotazione value l'attributo definisce il nome della cache.abbiamosono stati aggiunti due dettagli dei clienti

CustomerController.java

package com.w3codebox.controller;
import java.util.Arrays;
import java.util.List;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.w3codebox.model.Customer;
@RestController
public class CustomerController 
{
    @RequestMapping("/customerinfo")
    //definisce una cache per il valore di ritorno del metodo
    @Cacheable(value="customerInfo")
    public List customerInformation()
    {
        System.out.println("customer information from cache");
        //adding customer detail in the List
          List detail=Arrays.asList(new Customer(5126890,"Charlie Puth","Current A/c", 450000.00),
                        new Customer(7620015,"Andrew Flintoff","Saving A/c", 210089.00)
                       );
        return detail;
    }
}

现在运行该应用程序。

步骤13: 打开 SpringBootCacheExampleApplication.java 文件并将其作为Java应用程序运行。

步骤14: 打开Postman,并发送带有URL http://locahost:8080/custmerinfo的 GET 请求。它返回客户详细信息,如下所示。