Spring Boot 缓存技术:Spring Boot:@Cacheable 与@CacheEvict

摘要:
1@Cacheable@Cacheable函数:将方法的返回值添加到Ehcache作为缓存值属性:在Ehcache配置文件中指定缓存策略。如果没有给定值,name表示使用默认缓存策略。


1 @Cacheable

@Cacheable 作用:把方法的返回值添加到 Ehcache 中做缓存

Value 属性:指定一个 Ehcache 配置文件中的缓存策略,如果么有给定 value,name 则 表示使用默认的缓存策略。

image


Key 属性:给存储的值起个名称。在查询时如果有名称相同的,那么则知己从缓存中将 数据返回


业务层


@Override 
@Cacheable(value="users",key="#pageable.pageSize")
 public Page<Users> findUserByPage(Pageable pageable) {
     return this.usersRepository.findAll(pageable);
}


测试代码

@Test
public void testFindUserByPage(){
Pageable pageable = new PageRequest(0, 2);
 //第一次查询 
System.out.println(this.usersService.findUserByPage(pageable).getTotalElements());
//第二次查询 
System.out.println(this.usersService.findUserByPage(pageable).getTotalElements());
//第三次查询
 pageable = new PageRequest(1, 2);
System.out.println(this.usersService.findUserByPage(pageable).getTotalElements()); }
}


@CacheEvict

@CacheEvict 作用:清除缓存




业务层


package com.alan.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.alan.dao.UsersRepository;
import com.alan.pojo.Users;
import com.alan.service.UsersService;
/**
 * UsersService接口实现类
 *
 *
 */
@Service
public class UsersServiceImpl implements UsersService {

	@Autowired
	private UsersRepository usersRepository;

	@Override
	public List<Users> findUserAll() {
		return this.usersRepository.findAll();
	}

	@Override
	//@Cacheable:对当前查询的对象做缓存处理
	@Cacheable(value="users" )
	public Users findUserById(Integer id) {
		return this.usersRepository.findOne(id);
	}

	@Override
	@Cacheable(value = "users",key="#pageable.pageSize")
	public Page<Users> findUserByPage(Pageable pageable) {
		return this.usersRepository.findAll(pageable);
	}

	@Override
	//@CacheEvict(value="users",allEntries=true) 清除缓存中以 users 缓 存策略缓存的对象
	@CacheEvict(value="users",allEntries=true)
	public void saveUsers(Users users) {
		this.usersRepository.save(users);
	}

}

测试代码


@Test

public void testFindAll(){

//第一次查询 

System.out.println(this.usersService.findUserAll().size());

Users users = new Users();

users.setAddress("南京");

users.setAge(43);

users.setName("朱七");

this.usersService.saveUsers(users);

//第二次查询 

System.out.println(this.usersService.findUserAll().size());

}


image


源代码:

image


pom.xml

<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 http://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>1.5.10.RELEASE</version>
	</parent>
	<groupId>com.bjsxt</groupId>
	<artifactId>23-spring-boot-ehcache</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<properties>
		<java.version>1.7</java.version>
		<thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>
		<thymeleaf-layout-dialect.version>2.0.4</thymeleaf-layout-dialect.version>
	</properties>

	<dependencies>
		<!-- 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.0.9</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>
		<dependency>
			<groupId>javax.xml.bind</groupId>
			<artifactId>jaxb-api</artifactId>
			<version>2.3.0</version>
		</dependency>
		<dependency>
			<groupId>com.sun.xml.bind</groupId>
			<artifactId>jaxb-impl</artifactId>
			<version>2.3.0</version>
		</dependency>
		<dependency>
			<groupId>com.sun.xml.bind</groupId>
			<artifactId>jaxb-core</artifactId>
			<version>2.3.0</version>
		</dependency>
		<dependency>
			<groupId>javax.activation</groupId>
			<artifactId>activation</artifactId>
			<version>1.1.1</version>
		</dependency>
	</dependencies>
</project>


ehcache.xml

<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>


application.properties

spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/ssm
spring.datasource.username=root
spring.datasource.password=123456

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


Table___mysqlSql

create table `t_users` (
	`id` double ,
	`name` varchar (1500),
	`age` double ,
	`address` varchar (1560)
);
insert into `t_users` (`id`, `name`, `age`, `address`) values('1','张山','20','广东省佛山市顺德区');
insert into `t_users` (`id`, `name`, `age`, `address`) values('2','李思','20','广东省广州市天河区');
insert into `t_users` (`id`, `name`, `age`, `address`) values('3','王武','20','广东省佛山市南海区');
insert into `t_users` (`id`, `name`, `age`, `address`) values('4','赵柳','20','广东省梅州市');
insert into `t_users` (`id`, `name`, `age`, `address`) values('5','钱海','20','广东省韶关市');
insert into `t_users` (`id`, `name`, `age`, `address`) values('6','孙思','20','广东省深证市');






App

package com.alan;

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


@SpringBootApplication
@EnableCaching
public class App {

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


UsersServiceTest

package com.alan.test;

import com.alan.pojo.Users;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.alan.App;
import com.alan.service.UsersService;

import java.sql.SQLOutput;

/**
 * UsersService测试
 *
 *
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes=App.class)
public class UsersServiceTest {

	@Autowired
	private UsersService usersService;

	@Test
	public void testFindUserById(){
		//第一次查询
		System.out.println(this.usersService.findUserById(1));

		//第二次查询
		System.out.println(this.usersService.findUserById(1));
	}
   @Test
	public  void testFindUserByPage(){
	   Pageable pageable=new PageRequest(0,2);
	   //第一次查询
	   System.out.println(this.usersService.findUserByPage(pageable).getTotalElements());
      //第二次查询
	   System.out.println(this.usersService.findUserByPage(pageable).getTotalElements());
	   //第三次查询
	   pageable=new PageRequest(1,3);
	   System.out.println(this.usersService.findUserByPage(pageable).getTotalElements());
	}
	@Test
	public void testFindAll(){
		//第一次查询
		System.out.println(this.usersService.findUserAll().size());
		Users users = new Users();
		users.setAddress("南京");
		users.setAge(43);
		users.setName("朱七");
		this.usersService.saveUsers(users);
		//第二次查询
		System.out.println(this.usersService.findUserAll().size());
	}
}


UsersRepository

package com.alan.dao;

import org.springframework.data.jpa.repository.JpaRepository;

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

}


Users

package com.alan.pojo;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="t_users")
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 + "]";
	}
}


UsersService

package com.alan.service;

import java.util.List;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import com.alan.pojo.Users;

public interface UsersService {

	List<Users> findUserAll();
	Users findUserById(Integer id);
	Page<Users> findUserByPage(Pageable pageable);
	void saveUsers(Users users);
}


UsersServiceImpl

package com.alan.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.alan.dao.UsersRepository;
import com.alan.pojo.Users;
import com.alan.service.UsersService;
/**
 * UsersService接口实现类
 *
 *
 */
@Service
public class UsersServiceImpl implements UsersService {

	@Autowired
	private UsersRepository usersRepository;

	@Override
	public List<Users> findUserAll() {
		return this.usersRepository.findAll();
	}

	@Override
	//@Cacheable:对当前查询的对象做缓存处理
	@Cacheable(value="users" )
	public Users findUserById(Integer id) {
		return this.usersRepository.findOne(id);
	}

	@Override
	@Cacheable(value = "users",key="#pageable.pageSize")
	public Page<Users> findUserByPage(Pageable pageable) {
		return this.usersRepository.findAll(pageable);
	}

	@Override
	//@CacheEvict(value="users",allEntries=true) 清除缓存中以 users 缓 存策略缓存的对象
	@CacheEvict(value="users",allEntries=true)
	public void saveUsers(Users users) {
		this.usersRepository.save(users);
	}

}

免责声明:文章转载自《Spring Boot 缓存技术:Spring Boot:@Cacheable 与@CacheEvict》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇h5接入微信分享sdk,报错Cannot read property of undefined (reading 'title')移动端可视化框架antv f2出现两个legend选项下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

高性能缓存架构

极客时间:《从 0 开始学架构》:高性能缓存架构 1、引言 前几章节分别从读写分离、分库分表以及数据库的选择等方面来提升系统的性能,但在某些复杂的业务场景下,单纯的提高存储系统的性能是不够的,典型的场景如下: 需要经过复杂运算后得出的数据,存储系统无能为力 读多写少的数据,存储系统有心无力。如写一次,读多次 缓存就是为了弥补存储系统在这些复杂业务场景下...

Linux使用free命令buff/cache过高

在Linux系统中,我们经常用free命令来查看系统内存的使用状态。在一个RHEL6的系统上,free命令的显示内容大概是这样一个状态: 其实:buffers/cache占用的较多,说明系统中有进程曾经读写过文件,但是不要紧,这部分内存是当空闲来用的 Linux内核会在内存将要耗尽的时候,触发内存回收的工作,以便释放出内存给急需内存的进程使用。一般情况下...

jQuery缓存数据

很多同学在项目中都喜欢将数据存储在HTMLElement属性上,如 1 2 3 4 <div data="some data">Test</div> <script> div.getAttribute('data');// some data </script> 给页面中div添加了自定义...

干货|java缓存技术详解

一、缓存是什么? 请点击此处输入图片描述 Cache ①高速缓冲存储器,其中复制了频繁使用的数据以利于快速访问。 ②位于速度相差较大的两种硬件/软件之间,用于协调两者数据传输速度差异的结构 二、缓存有哪几类? 1、基于web应用的系统架构图 请点击此处输入图片描述 2、在系统架构中,不同层级之间为了加快访问速度,缓存都可以存在。 操作系统磁盘缓存-&g...

Centos 7 解决free -m 下buff/cache缓存很高

Linux服务器运行一段时间后,由于其内存管理机制,会将暂时不用的内存转为buff/cache,这样在程序使用到这一部分数据时,能够很快的取出,从而提高系统的运行效率,所以这也正是linux内存管理中非常出色的一点,所以乍一看内存剩余的非常少,但是在程序真正需要内存空间时,linux会将缓存让出给程序使用,这样达到对内存的最充分利用,所以真正剩余的内存是f...

关于Intege.valueOf()的使用

原文链接:https://blog.csdn.net/weixin_37650458/article/details/85212730 1.Integer. valueOf()方法的作用     Integer. valueOf()可以将基本类型int转换为包装类型Integer,或者将String转换成Integer,String如果为Null或“”都会...