Springboot integra EHcache para implementar el almacenamiento en caché de paginación

Una breve reseña

@Cacheable almacena en caché el objeto actual

Función @Cacheable: agregue el valor de retorno del método a Ehcache para el almacenamiento en caché

@Cacheable (value = “xxx” , key = "xxxx")

Atributo de valor: especifique una estrategia de caché en el archivo de configuración de Ehcache, si no se proporciona ningún valor, se utiliza la estrategia de caché predeterminada

El rol de la clave: darle un nombre al valor almacenado, y si el nombre es el mismo en la consulta, el valor se toma del nombre conocido. De lo contrario, vuelva a consultar la base de datos.

Dos casos

2.1 Estructura de ingeniería

2.2 archivo pom

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.13</version>
      <scope>test</scope>
    </dependency>
    <!-- springBoot 的启动器 -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- springBoot 的启动器 -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <!-- springBoot 的启动器 -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <!-- 测试工具的启动器 -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
    </dependency>
    <!-- mysql -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
    </dependency>
    <!-- druid连接池 -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.10</version>
    </dependency>
    <!-- Spring Boot 缓存支持启动器 -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-cache</artifactId>
    </dependency>
    <!-- Ehcache 坐标 -->
    <dependency>
      <groupId>net.sf.ehcache</groupId>
      <artifactId>ehcache</artifactId>
    </dependency>

2.3 dao

package com.ljf.spring.boot.demo.dao;

import com.ljf.spring.boot.demo.model.Users;
import org.springframework.data.jpa.repository.JpaRepository;

/**
 * 参数一 T :当前需要映射的实体
 * 参数二 ID :当前映射的实体中的OID的类型
 *
 */
public interface UserRepository extends JpaRepository<Users,Integer> {

}

2.4 modelo

package com.ljf.spring.boot.demo.model;

import javax.persistence.*;
import java.io.Serializable;

/**
 * @ClassName: Users
 * @Description: TODO
 * @Author: liujianfu
 * @Date: 2020/09/02 08:50:18 
 * @Version: V1.0
 **/
    @Entity
    @Table(name="tb_users_tb")
    public class Users implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Integer id;

    @Column(name = "name")
    private String name;

    @Column(name = "age")
    private Integer age;

    @Column(name = "address")
    private String address;


    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "Users [id=" + id + ", name=" + name + ", age=" + age + ", address=" + address + "]";
    }
}

2.5 servicio

Capa de interfaz:

package com.ljf.spring.boot.demo.service;

import com.ljf.spring.boot.demo.model.Users;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.util.List;

public interface UserService {
    List<Users> findUserAll();
    public Page<Users> findUserByPage(Pageable pageable );
}

Capa de implementación:

package com.ljf.spring.boot.demo.service.impl;

import com.ljf.spring.boot.demo.dao.UserRepository;
import com.ljf.spring.boot.demo.model.Users;
import com.ljf.spring.boot.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @ClassName: UserServiceImpl
 * @Description: TODO
 * @Author: liujianfu
 * @Date: 2020/09/02 08:57:11 
 * @Version: V1.0
 **/
@Service
public class UserServiceImpl  implements UserService {
    @Autowired
    private UserRepository userRepository;
    @Override
    //@Cacheable 对当前的对象做缓存处理
    //@Cacheable 作用:把方法的返回值添加到 Ehcache 中做缓存
    // Value 属性:指定一个 Ehcache 配置文件中的缓存策略,如果没有给定 value,那么则表示使用默认的缓存策略
    @Cacheable(value = "users")
    public List<Users> findUserAll() {
        return this.userRepository.findAll();
    }

   // @Cacheable(value="users",key="#pageable") //默认key的值为pageable
   // @Cacheable(value="users",key="#pageable.pageSize") //指定key的值为#pageable.pageSize
    public Page<Users> findUserByPage(Pageable pageable ){
        return this.userRepository.findAll(pageable);
    }

}

2.6 Archivo de configuración

1.archivo de configuración de la aplicación

#spring的配置mysql
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test_db?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
#ali
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.cache.ehcache.cofnig=ehcache.xml

2.archivo de caché ehcache

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">

    <diskStore path="java.io.tmpdir"/>

  <!--defaultCache:echcache的默认缓存策略  -->
    <defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            maxElementsOnDisk="10000000"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </defaultCache>
    <!-- 自定义缓存策略 -->
    <cache name="users"
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            maxElementsOnDisk="10000000"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </cache>
</ehcache>

2.7 Clase de inicio

package com.ljf.spring.boot.demo;

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

/**
 * Hello world!
 *
 */
@SpringBootApplication
@EnableCaching
public class StartApp
{
    public static void main( String[] args )
    {
        SpringApplication.run(StartApp.class, args);
        System.out.println( "Hello World!" );

    }
}

2.8 Categoría de prueba

    @Test
    public void queryByPage(){
        Pageable pageable= PageRequest.of(0, 10);
        Page<Users> list=us.findUserByPage(pageable);
        System.out.println("第1次:"+list.getContent().get(0).getAddress());
        Page<Users> list2=us.findUserByPage(pageable);
        System.out.println("第2次:"+list2.getContent().get(0).getAddress());
         pageable= PageRequest.of(0, 5);
        Page<Users> list3=us.findUserByPage(pageable);
        System.out.println("第3次:"+list3.getContent().get(0).getAddress());
    }

Sin almacenamiento en caché, la consulta se ejecutó 3 veces para consultar la base de datos

2.9 Agregar caché

En el método de paginación, si se almacena en caché, el paginable que se ha paginado se usa como clave

A través de los resultados de la ejecución, podemos ver que la base de datos se consulta por primera vez y la memoria se consulta por segunda vez. Cuando la paginación pageable = PageRequest.of (0, 10); se cambia a pageable = PageRequest.of (0, 5) ;, cuando se ejecuta de nuevo, vuelva a consultar la base de datos

 

Supongo que te gusta

Origin blog.csdn.net/u011066470/article/details/115066760
Recomendado
Clasificación