Spring Boot缓存实战 EhCache示例

发布时间 - 2026-01-11 02:47:15    点击率:

Spring boot默认使用的是SimpleCacheConfiguration,即使用ConcurrentMapCacheManager来实现缓存。但是要切换到其他缓存实现也很简单

pom文件

在pom中引入相应的jar包

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

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

  <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
  </dependency>

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

  <dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache</artifactId>
  </dependency>

</dependencies>

配置文件

EhCache所需要的配置文件,只需要放到类路径下,Spring Boot会自动扫描。

<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
  <cache name="people" maxElementsInMemory="1000"/>
</ehcache>

也可以通过在application.properties文件中,通过配置来指定EhCache配置文件的位置,如:

spring.cache.ehcache.config= # ehcache配置文件地址

Spring Boot会自动为我们配置EhCacheCacheMannager的Bean。

关键Service

package com.xiaolyuh.service.impl;

import com.xiaolyuh.entity.Person;
import com.xiaolyuh.repository.PersonRepository;
import com.xiaolyuh.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class PersonServiceImpl implements PersonService {
  @Autowired
  PersonRepository personRepository;

  @Override
  @CachePut(value = "people", key = "#person.id")
  public Person save(Person person) {
    Person p = personRepository.save(person);
    System.out.println("为id、key为:" + p.getId() + "数据做了缓存");
    return p;
  }

  @Override
  @CacheEvict(value = "people")//2
  public void remove(Long id) {
    System.out.println("删除了id、key为" + id + "的数据缓存");
    //这里不做实际删除操作
  }

  @Override
  @Cacheable(value = "people", key = "#person.id")//3
  public Person findOne(Person person) {
    Person p = personRepository.findOne(person.getId());
    System.out.println("为id、key为:" + p.getId() + "数据做了缓存");
    return p;
  }
}

Controller

package com.xiaolyuh.controller;

import com.xiaolyuh.entity.Person;
import com.xiaolyuh.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class CacheController {

  @Autowired
  PersonService personService;

  @Autowired
  CacheManager cacheManager;

  @RequestMapping("/put")
  public long put(@RequestBody Person person) {
    Person p = personService.save(person);
    return p.getId();
  }

  @RequestMapping("/able")
  public Person cacheable(Person person) {
    System.out.println(cacheManager.toString());
    return personService.findOne(person);
  }

  @RequestMapping("/evit")
  public String evit(Long id) {

    personService.remove(id);
    return "ok";
  }

}

启动类

@SpringBootApplication
@EnableCaching// 开启缓存,需要显示的指定
public class SpringBootStudentCacheApplication {

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

测试类

package com.xiaolyuh;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import java.util.HashMap;
import java.util.Map;

import org.junit.Before;
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.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import net.minidev.json.JSONObject;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootStudentCacheApplicationTests {

  @Test
  public void contextLoads() {
  }

  private MockMvc mockMvc; // 模拟MVC对象,通过MockMvcBuilders.webAppContextSetup(this.wac).build()初始化。

  @Autowired
  private WebApplicationContext wac; // 注入WebApplicationContext 

//  @Autowired 
//  private MockHttpSession session;// 注入模拟的http session 
//   
//  @Autowired 
//  private MockHttpServletRequest request;// 注入模拟的http request\ 

  @Before // 在测试开始前初始化工作 
  public void setup() {
    this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
  }

  @Test
  public void testAble() throws Exception {
    for (int i = 0; i < 2; i++) {
      MvcResult result = mockMvc.perform(post("/able").param("id", "2"))
          .andExpect(status().isOk())// 模拟向testRest发送get请求
          .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))// 预期返回值的媒体类型text/plain;
          // charset=UTF-8
          .andReturn();// 返回执行请求的结果

      System.out.println(result.getResponse().getContentAsString());
    }
  }

}

打印日志

从上面可以看出第一次走的是数据库,第二次走的是缓存

源码:https://github.com/wyh-spring-ecosystem-student/spring-boot-student/tree/releases

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


# Spring  # Boot缓存  # Boot  # EhCache  # 在Mybatis中使用自定义缓存ehcache的方法  # SpringBoot2 整合Ehcache组件  # 轻量级缓存管理的原理解析  # Spring Boot集成Ehcache缓存解决方式  # SpringBoot中Shiro缓存使用Redis、Ehcache的方法  # 使用ehcache三步搞定springboot缓存的方法示例  # 详解Spring Boot Oauth2缓存UserDetails到Ehcache  # spring-boot整合ehcache实现缓存机制的方法  # Java Ehcache缓存框架入门级使用实例  # 详解SpringBoot缓存的实例代码(EhCache 2.x 篇)  # Spring+EHcache缓存实例详解  # 详解Spring MVC 集成EHCache缓存  # Java缓存ehcache的使用步骤  # 的是  # 配置文件  # 也很  # 可以通过  # 不做  # 只需要  # 可以看出  # 所需要  # 来实现  # 大家多多  # 切换到  # 返回值  # service  # PersonService  # Person  # beans  # impl  # PersonRepository  # repository  # import 


相关栏目: 【 网站优化151355 】 【 网络推广146373 】 【 网络技术251813 】 【 AI营销90571


相关推荐: 如何有效防御Web建站篡改攻击?  Windows驱动无法加载错误解决方法_驱动签名验证失败处理步骤  香港服务器网站生成指南:免费资源整合与高速稳定配置方案  手机怎么制作网站教程步骤,手机怎么做自己的网页链接?  制作旅游网站html,怎样注册旅游网站?  如何在香港免费服务器上快速搭建网站?  CSS3怎么给轮播图加过渡动画_transition加transform实现【技巧】  如何在阿里云虚拟服务器快速搭建网站?  头像制作网站在线观看,除了站酷,还有哪些比较好的设计网站?  Laravel如何配置任务调度?(Cron Job示例)  Java解压缩zip - 解压缩多个文件或文件夹实例  如何用PHP快速搭建CMS系统?  Laravel如何集成Inertia.js与Vue/React?(安装配置)  iOS UIView常见属性方法小结  google浏览器怎么清理缓存_谷歌浏览器清除缓存加速详细步骤  如何在云虚拟主机上快速搭建个人网站?  教你用AI将一段旋律扩展成一首完整的曲子  如何在VPS电脑上快速搭建网站?  奇安信“盘古石”团队突破 iOS 26.1 提权  文字头像制作网站推荐软件,醒图能自动配文字吗?  如何获取上海专业网站定制建站电话?  Python制作简易注册登录系统  微信小程序 wx.uploadFile无法上传解决办法  用v-html解决Vue.js渲染中html标签不被解析的问题  Laravel模型关联查询教程_Laravel Eloquent一对多关联写法  网站制作壁纸教程视频,电脑壁纸网站?  如何快速上传建站程序避免常见错误?  百度输入法ai组件怎么删除 百度输入法ai组件移除工具  Laravel如何生成URL和重定向?(路由助手函数)  edge浏览器无法安装扩展 edge浏览器插件安装失败【解决方法】  Laravel Blade模板引擎语法_Laravel Blade布局继承用法  如何在阿里云服务器自主搭建网站?  Laravel Octane如何提升性能_使用Laravel Octane加速你的应用  Laravel中Service Container是做什么的_Laravel服务容器与依赖注入核心概念解析  Laravel与Inertia.js怎么结合_使用Laravel和Inertia构建现代单页应用  如何在新浪SAE免费搭建个人博客?  制作网站软件推荐手机版,如何制作属于自己的手机网站app应用?  Laravel如何实现数据导出到PDF_Laravel使用snappy生成网页快照PDF【方案】  简历在线制作网站免费版,如何创建个人简历?  如何正确选择百度移动适配建站域名?  php485函数参数是什么意思_php485各参数详细说明【介绍】  LinuxShell函数封装方法_脚本复用设计思路【教程】  Laravel如何使用Seeder填充数据_Laravel模型工厂Factory批量生成测试数据【方法】  微信h5制作网站有哪些,免费微信H5页面制作工具?  Laravel如何处理跨站请求伪造(CSRF)保护_Laravel表单安全机制与令牌校验  Mybatis 中的insertOrUpdate操作  如何确保西部建站助手FTP传输的安全性?  如何快速打造个性化非模板自助建站?  如何获取免费开源的自助建站系统源码?  详解Oracle修改字段类型方法总结