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


相关推荐: C语言设计一个闪闪的圣诞树  Laravel怎么为数据库表字段添加索引以优化查询  ChatGPT 4.0官网入口地址 ChatGPT在线体验官网  佛山企业网站制作公司有哪些,沟通100网上服务官网?  Laravel如何使用Guzzle调用外部接口_Laravel发起HTTP请求与JSON数据解析【详解】  Win11怎么开启自动HDR画质_Windows11显示设置HDR选项  laravel怎么通过契约(Contracts)编程_laravel契约(Contracts)编程方法  如何在IIS中新建站点并解决端口绑定冲突?  如何在浏览器中启用Flash_2025年继续使用Flash Player的方法【过时】  高端智能建站公司优选:品牌定制与SEO优化一站式服务  谷歌浏览器如何更改浏览器主题 Google Chrome主题设置教程  JavaScript如何实现错误处理_try...catch如何捕获异常?  详解Nginx + Tomcat 反向代理 如何在高效的在一台服务器部署多个站点  香港服务器网站搭建教程-电商部署、配置优化与安全稳定指南  如何在阿里云虚拟服务器快速搭建网站?  Laravel如何处理异常和错误?(Handler示例)  laravel怎么为应用开启和关闭维护模式_laravel应用维护模式开启与关闭方法  如何在建站主机中优化服务器配置?  Laravel怎么进行数据库回滚_Laravel Migration数据库版本控制与回滚操作  jQuery中的100个技巧汇总  LinuxCD持续部署教程_自动发布与回滚机制  php 三元运算符实例详细介绍  高防服务器租用首荐平台,企业级优惠套餐快速部署  Laravel如何使用Gate和Policy进行权限控制_Laravel权限判定与策略规则配置  如何解决hover在ie6中的兼容性问题  手机怎么制作网站教程步骤,手机怎么做自己的网页链接?  企业在线网站设计制作流程,想建设一个属于自己的企业网站,该如何去做?  微信小程序 配置文件详细介绍  Laravel安装步骤详细教程_Laravel环境搭建指南  如何用IIS7快速搭建并优化网站站点?  Laravel全局作用域是什么_Laravel Eloquent Global Scopes应用指南  教你用AI润色文章,让你的文字表达更专业  如何在阿里云域名上完成建站全流程?  简历在线制作网站免费版,如何创建个人简历?  php读取心率传感器数据怎么弄_php获取max30100的心率值【指南】  html5怎么画眼睛_HT5用Canvas或SVG画眼球瞳孔加JS控制动态【绘制】  Laravel如何处理JSON字段_Eloquent原生JSON字段类型操作教程  php做exe能调用系统命令吗_执行cmd指令实现方式【详解】  制作公司内部网站有哪些,内网如何建网站?  网站建设整体流程解析,建站其实很容易!  如何使用 jQuery 正确渲染 Instagram 风格的标签列表  专业企业网站设计制作公司,如何理解商贸企业的统一配送和分销网络建设?  在Oracle关闭情况下如何修改spfile的参数  如何在建站之星绑定自定义域名?  如何自己制作一个网站链接,如何制作一个企业网站,建设网站的基本步骤有哪些?  Windows10如何更改计算机工作组_Win10系统属性修改Workgroup  详解vue.js组件化开发实践  如何快速查询网站的真实建站时间?  iOS UIView常见属性方法小结  如何用花生壳三步快速搭建专属网站?