spring boot 学习手册
  • 介绍
  • 基础教程
    • 1.RESTfull API简单项目的快速搭建
    • 2.配置文件详解:Properties和YAML
    • 3.配置文件-多环境配置
    • 4.日志配置-logback和log4j2
  • web应用开发
    • 1.模板引擎
    • 2.模板引擎FreeMarker
    • 3.模板引擎Thymeleaf
    • 4.模板引擎jsp
    • 5.错误处理
    • 6.Servlets, Filters, listeners
    • 7.CORS支持
    • 8.文件上传
    • 9.Interceptor拦截器
    • 10.AOP统一处理Web请求日志
    • 11.全局统一异常处理
    • 12. Retry重试
    • 13.RestTemplate
  • 关系型数据库
    • 1.JdbcTemplate
    • 2.Spring-data-jpa
      • @Id 和 @GeneratedValue 详解
      • 配置与注解备注
      • 全局统一前缀策略
      • 映射关系详解
      • 查询、分页、排序
      • JPA 资料
      • 进阶:jpa自定义行为方法
      • 进阶:锁
      • 进阶:Hibernate Validator
    • 3.事务处理
  • NoSQL数据库
    • 1.Redis
    • 2.Mongodb
  • Cache
    • 1.EhCache
    • 2.Redis
  • 异步消息服务
    • 1.JMS(ActiveMQ)
    • 2.AMQP(RabbitMQ)
  • Mybatis
    • Mybatis 初使用
    • Mybatis环境搭建
    • Mybatis开发流程
    • 业务开发流程
    • Mybatis资料
  • 进阶
    • 1.调用REST服务-使用代理
    • 2.发送邮件
    • 3.Spring Session实现集群-redis
    • 4.如何进行远程调试
    • 5.生产准备-基于HTTP的监控
    • 6.Spring Boot集成mybatis
    • 7.Spring Boot集成Druid
    • 8.Spring Boot集成Swagger
    • 9.生产部署-注意事项和如何使用脚本
  • 升华
    • Jenkins部署Spring Boot
    • 异步处理Http请求
    • FastDFS
    • Docker
    • 定时任务(corn job)
    • 批处理
    • @Async实现异步调用
  • 单元测试
    • WireMock伪造服务
  • 安全
    • 1.Spring Security
      • 认证
    • 2.Apache Shiro
  • TaskExecutor 异步线程池
  • 其他
    • 1.修改启动时显示
    • 2.获取配置文件中的值
    • 3.嵌入式容器
    • 4.配置SSL
    • 5.websocket
    • 6.Spring IO Platform
  • RESTfull API 开发
  • 附录:Eclipse - Spring Tool Suite工具的安装
  • 附录:Eclipse部署Maven
  • 附录:SpringBoot相关模块
  • 附录:注解笔记
  • 资料
  • 开发技巧
  • maven插件
Powered by GitBook
On this page
  • 一、 添加依赖
  • 二、 配置文件:
  • 三、 启用注解支持:
  • 资料

Was this helpful?

  1. Cache

1.EhCache

一、 添加依赖

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

二、 配置文件:

spring.cache.type=ehcache
spring.cache.ehcache.config=classpath:config/ehcache.xml

ehcache.xml

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

    <cache name="demoCache"
           eternal="false"
           maxEntriesLocalHeap="0"
           timeToIdleSeconds="200"></cache>

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

配置信息介绍

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
    updateCheck="false">
    <diskStore path="java.io.tmpdir/Tmp_EhCache" />

    <!-- 默认配置 -->
    <defaultCache maxElementsInMemory="5000" eternal="false"
        timeToIdleSeconds="120" timeToLiveSeconds="120"
        memoryStoreEvictionPolicy="LRU" overflowToDisk="false" />

    <cache name="baseCache" maxElementsInMemory="10000"
        maxElementsOnDisk="100000" />

</ehcache>
name:缓存名称。  
maxElementsInMemory:缓存最大个数。  
eternal:对象是否永久有效,一但设置了,timeout将不起作用。  
timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。  
timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。  
overflowToDisk:当内存中对象数量达到maxElementsInMemory时,Ehcache将会对象写到磁盘中。  
diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。  
maxElementsOnDisk:硬盘最大缓存个数。  
1diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.  
1diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。  
1memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。  
1clearOnFlush:内存数量最大时是否清除。

三、 启用注解支持:

@EnableCaching:启用缓存注解

添加在main方法上面

具体代码实现

cache/DemoUserLogCache.java 接口

package com.shuju.test2.cache;


import com.shuju.test2.bean.DemoUserLog;

public interface DemoUserLogCache {

    /**
     * 查询
     *
     * @param id
     * @return
     */
    DemoUserLog selectById(Integer id);

    /**
     * 更新
     *
     * @param roncooUserLog
     * @return
     */
    DemoUserLog updateById(DemoUserLog roncooUserLog);

    /**
     * 删除
     *
     * @param id
     * @return
     */
    String deleteById(Integer id);
}

cache/impl/DemoUserLogCacheImpl.java

package com.shuju.test2.cache.impl;

import com.shuju.test2.bean.DemoUserLog;
import com.shuju.test2.cache.DemoUserLogCache;
import com.shuju.test2.dao.DemoUserLogDao;
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;

@CacheConfig(cacheNames = "demoCache")
@Repository
public class DemoUserLogCacheImpl implements DemoUserLogCache {

    @Autowired
    private DemoUserLogDao demoUserLogDao;

    @Cacheable(key = "#p0")
    @Override
    public DemoUserLog selectById(Integer id) {
        System.out.println("查询功能,缓存找不到,直接读库, id=" + id);
        return demoUserLogDao.findById(id).get();
    }

    @CachePut(key = "#p0")
    @Override
    public DemoUserLog updateById(DemoUserLog demoUserLog) {
        System.out.println("更新功能,更新缓存,直接写库, id=" + demoUserLog);
        return demoUserLogDao.save(demoUserLog);
    }

    @CacheEvict(key = "#p0")
    @Override
    public String deleteById(Integer id) {
        System.out.println("删除功能,删除缓存,直接写库, id=" + id);
        return "清空缓存成功";
    }
}

注解说明:

  • @CacheConfig:缓存配置

  • @Cacheable:应用到读取数据的方法上,即可缓存的方法,如查找方法:先从缓存中读取,如果没有再调 用方法获取数据,然后把数据添加到缓存中。适用于查找

  • @CachePut:主要针对方法配置,能够根据方法的请求参数对其结果进行缓存,和 @Cacheable 不同的是,它每次都会触发真实方法的调用。适用于更新和插入

  • @CacheEvict:主要针对方法配置,能够根据一定的条件对缓存进行清空。适用于删除

创建用于测试的controller/ApiController.java

package com.shuju.test2.controller;

import java.util.Date;
import java.util.HashMap;

import com.shuju.test2.bean.DemoUserLog;
import com.shuju.test2.cache.DemoUserLogCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class ApiController {

    @Autowired
    private DemoUserLogCache demoUserLogCache;

    @RequestMapping(value = "/select", method = RequestMethod.GET)
    public DemoUserLog get(@RequestParam(defaultValue = "1") Integer id) {
        return demoUserLogCache.selectById(id);
    }

    @RequestMapping(value = "/update", method = RequestMethod.GET)
    public DemoUserLog update(@RequestParam(defaultValue = "1") Integer id) {
        DemoUserLog bean = demoUserLogCache.selectById(id);
        bean.setUserName("测试");
        bean.setCreateTime(new Date());
        demoUserLogCache.updateById(bean);
        return bean;
    }

    @RequestMapping(value = "/del", method = RequestMethod.GET)
    public String del(@RequestParam(defaultValue = "1") Integer id) {
        return demoUserLogCache.deleteById(id);
    }
}

资料

手动清除缓存

@Autowired
private CacheManager cacheManager;
@RequestMapping("/remoKey")
public void remoKey() {
    cacheManager.getCache("cachename").clear();
}
PreviousCacheNext2.Redis

Last updated 6 years ago

Was this helpful?

spring boot学习(十三)SpringBoot缓存(EhCache 2.x 篇)