一、案例

  1.1  引入maven依赖

<!-- caching -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>

  1.2  配置application.properties

#echache缓存
spring.cache.type=ehcache
spring.cache.ehcache.config=classpath:config/ehcache.xml

  1.3  配置config/ehcache.xml

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd">
<cache name="roncooCache" eternal="false" maxEntriesLocalHeap="0"
timeToIdleSeconds="50"></cache>
<!-- eternal:true表示对象永不过期,此时会忽略timeToIdleSeconds和 timeToLiveSeconds属性,默认为false -->
<!-- maxEntriesLocalHeap:堆内存中最大缓存对象数,0没有限制 --> <!-- timeToIdleSeconds: 设定允许对象处于空闲状态的最长时间,以秒为 单位。当对象自从最近一次被访问后,如果处于空闲状态的时间超过了
timeToIdleSeconds属性值,这个对象就会过期,EHCache将把它从缓存中清空。 只有当eternal属性为false,该属性才有效。如果该属性值为0,则表示对象可以
无限期地处于空闲状态 -->
</ehcache>

  1.4  启用@EnableCaching 注解支持

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

  1.5  编写实体类

  • 如下代码,写完后运行Springboot01Application.java会自动在数据库生成表结构
package com.shyroke.entity;

import java.io.Serializable;
import java.util.Date; import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @Entity
@JsonIgnoreProperties({ "handler","hibernateLazyInitializer" })
@Table(name="user")
public class UserBean { @Id
@GeneratedValue
private Integer id; @Column
private Date createTime; @Column
private String userName; @Column
private String userIp; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public Date getCreateTime() {
return createTime;
} public void setCreateTime(Date createTime) {
this.createTime = createTime;
} public String getUserName() {
return userName;
} public void setUserName(String userName) {
this.userName = userName;
} public String getUserIp() {
return userIp;
} public void setUserIp(String userIp) {
this.userIp = userIp;
} @Override
public String toString() {
return "RoncooUserLog [id=" + id + ", createTime=" + createTime + ", userName=" + userName + ", userIp=" + userIp + "]";
} }

  1.6  编写控制器

package com.shyroke.controller;

import java.util.Date;
import java.util.List; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; import com.shyroke.dao.UserMapper;
import com.shyroke.entity.UserBean;
import com.shyroke.service.CacheUserService; @Controller
@RequestMapping(value = "/")
public class IndexController { @Autowired
private CacheUserService cacheUserService; @RequestMapping(value = "/select")
@ResponseBody
public UserBean get() {
return cacheUserService.getUserById(1);
} @RequestMapping(value = "/update")
@ResponseBody
public UserBean update() {
UserBean bean = cacheUserService.getUserById(1);
bean.setUserName("测试");
bean.setCreateTime(new Date());
cacheUserService.update(bean);
return bean;
} @RequestMapping(value = "/del")
@ResponseBody
public String del() {
return cacheUserService.deleteById(1);
} }

  1.7  编写服务接口和实现类

package com.shyroke.service;

import com.shyroke.entity.UserBean;

public interface CacheUserService {
/**
* 查询
*
* @param id
* @return
*/
public UserBean getUserById(int id); /**
* 更新
*
* @param user
* @return
*/ public UserBean update(UserBean user); /**
* 删除
*
* @param id
* @return
*/ public String deleteById(int id);
}
package com.shyroke.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service; import com.shyroke.dao.UserMapper;
import com.shyroke.entity.UserBean;
import com.shyroke.service.CacheUserService; @CacheConfig(cacheNames = "roncooCache")
@Service
public class CacheUserServiceImpl implements CacheUserService{ @Autowired
private UserMapper userMapper; @Cacheable(key = "#p0")
@Override
public UserBean getUserById(int id) {
System.out.println("查询功能,缓存找不到,直接读库, id=" + id);
return userMapper.getOne(id);
} @CachePut(key = "#p0")
@Override
public UserBean update(UserBean user) {
System.out.println("更新功能,更新缓存,直接写库, id=" + user);
return userMapper.save(user);
} @CacheEvict(key = "#p0")
@Override
public String deleteById(int id) {
System.out.println("删除功能,删除缓存,直接写库, id=" + id);
userMapper.delete(id);
return "删除成功";
} }

  1.8  编写userMapper.java

package com.shyroke.dao;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository; import com.shyroke.entity.UserBean; public interface UserMapper extends JpaRepository<UserBean, Integer>{ }

  1.9  结果

  • 现在数据库中插入一条数据


  • 第一次访问,所以没有缓存,故发出一条sql语句查询。
  • 然后在访问“http://localhost:8888/select” 结果如下:

没有发出sql语句,说明是从缓存中读取的数据。



  • 测试更新结果

  • 更新完毕之后,返回更新后的数据,然后在返回“http://localhost:8888/select”

  • 没有发出查询语句,而且查询的结果的更新世间与执行“http://localhost:8888/update”更新操作后的时间一致,说明查询的是最新的更新后的数据,所以表示“http://localhost:8888/update”更新操作会先更新缓存。

(十六)SpringBoot之使用 Caching- - EhCache的更多相关文章

  1. Java开发学习(三十六)----SpringBoot三种配置文件解析

    一. 配置文件格式 我们现在启动服务器默认的端口号是 8080,访问路径可以书写为 http://localhost:8080/books/1 在线上环境我们还是希望将端口号改为 80,这样在访问的时 ...

  2. [十六]SpringBoot 之 读取环境变量和绑定属性对象

    1.读取环境变量 凡是被spring管理的类,实现接口EnvironmentAware 重写方法 setEnvironment 可以在工程启动时,获取到系统环境变量和application配置文件中的 ...

  3. [二十六]SpringBoot 之 整合log4j

    1.引入log4j依赖 在创建Spring Boot工程时,我们引入了spring-boot-starter,其中包含了spring-boot-starter-logging,该依赖内容就是Sprin ...

  4. SpringBoot | 第二十六章:邮件发送

    前言 讲解了日志相关的知识点后.今天来点相对简单的,一般上,我们在开发一些注册功能.发送验证码或者订单服务时,都会通过短信或者邮件的方式通知消费者,注册或者订单的相关信息.而且基本上邮件的内容都是模版 ...

  5. 跟我学SpringCloud | 第十六篇:微服务利剑之APM平台(二)Pinpoint

    目录 SpringCloud系列教程 | 第十六篇:微服务利剑之APM平台(二)Pinpoint 1. Pinpoint概述 2. Pinpoint主要特性 3. Pinpoint优势 4. Pinp ...

  6. Spring Boot 2.X(十六):应用监控之 Spring Boot Actuator 使用及配置

    Actuator 简介 Actuator 是 Spring Boot 提供的对应用系统的自省和监控功能.通过 Actuator,可以使用数据化的指标去度量应用的运行情况,比如查看服务器的磁盘.内存.C ...

  7. SpringBoot:三十五道SpringBoot面试题及答案

    SpringBoot面试前言今天博主将为大家分享三十五道SpringBoot面试题及答案,不喜勿喷,如有异议欢迎讨论! Spring Boot 是微服务中最好的 Java 框架. 我们建议你能够成为一 ...

  8. spring-boot-route(十六)使用logback生产日志文件

    日志是一个系统非常重要的一部分,我们经常需要通过查看日志来定位问题,今天我们一起来学习一下Spring Boot的日志系统.有很多同学习惯性的在生产代码中使用System.out来输出日志,这是不推荐 ...

  9. 我的MYSQL学习心得(十六) 优化

    我的MYSQL学习心得(十六) 优化 我的MYSQL学习心得(一) 简单语法 我的MYSQL学习心得(二) 数据类型宽度 我的MYSQL学习心得(三) 查看字段长度 我的MYSQL学习心得(四) 数据 ...

  10. Bootstrap <基础二十六>进度条

    Bootstrap 进度条.在本教程中,你将看到如何使用 Bootstrap 创建加载.重定向或动作状态的进度条. Bootstrap 进度条使用 CSS3 过渡和动画来获得该效果.Internet ...

随机推荐

  1. java.lang.ClassNotFoundException:org.apache.struts2.dispatcher.FilterDispatcher

    老版本的Struts2升级,启动报的错. org.apache.struts2.dispatcher.FilterDispatcher 是web.xml中对struts2  2.2版本的接入点的类. ...

  2. vue开发环境、正式环境的配置及原理

    修改prod.env.js里的内容,修改后的内容如下: 'use strict' module.exports = { NODE_ENV: '"production"', EVN_ ...

  3. 如何正确查看Linux机器内存使用情况

    如何正确查看Linux机器内存使用情况 背景 只要工作上涉及到Linux机器,基本上都会有这样一个需求,查看内存使用情况,但是怎么看才正确呢?之前使用的是top命令,一直存在一个误区. 为什么top命 ...

  4. 复制粘贴引发的鸠占鹊巢——IDEA复制项目导致sources root复用了另一个项目

    复制粘贴大法一向是程序猿的利器,但有时也会引发一些拎不清的麻烦关系来.比如我们现在想新建一个项目,为了快速而对原来的uis-gateway动用了复制粘贴大法,然后改改项目名就成了uis-applica ...

  5. 阶段5 3.微服务项目【学成在线】_day18 用户授权_07-动态查询用户权限-权限数据模型

    3 动态查询用户权限 3.1 需求分析 截至目前在测试授权时使用的权限数据是静态数据,正常情况的流程是: 1.管理员给用户分配权限,权限数据写到数据库中. 2.认证服务在进行用户认证时从数据库读取用户 ...

  6. Kafka管理与监控——broker宕机后无法消费问题

    背景 因磁盘满了,导致kafka所有的服务器全部宕机了,然后重启kafka集群,服务是启动成功了,但有一些报错: broker1: broker2: broker3:一直在刷以下错误信息 虽然报了这些 ...

  7. otepad++ 配置 支持jquery、html、css、javascript、php代码提示

    官网下载:http://notepad-plus-plus.org/ 获取插件的方法:打开软件,窗口工具栏有有一个问号,点获取插件. 我使用的插件(安装方法都是官方的方法): QuickText.v0 ...

  8. 【Leetcode_easy】696. Count Binary Substrings

    problem 696. Count Binary Substrings 题意:具有相同个数的1和0的连续子串的数目: solution1:还不是特别理解... 遍历元数组,如果是第一个数字,那么对应 ...

  9. Oracle数据同步交换

    一.为了解决数据同步汇聚,数据分发,数据转换,数据维护等需求,TreeSoft将复杂的网状的同步链路变成了星型数据链路.     TreeSoft作为中间传输载体负责连接各种数据源,为各种异构数据库之 ...

  10. C#6.0-8.0新功能、ValueTuple

    C# 6.0: https://www.cnblogs.com/yinrq/p/5600530.html C# 7.0: https://www.cnblogs.com/cncc/p/7698543. ...