Spring Boot缓存实战 EhCache示例
作者:xiaolyuh 发布时间:2023-08-30 12:23:35
标签:Spring,Boot,EhCache
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
来源:http://www.jianshu.com/p/31e666f1ff57


猜你喜欢
- 详解java 中Spring jsonp 跨域请求的实例jsonp介绍  
- 在线程间通信方式中,我们了解到可以使用Semaphore信号量来实现线程间通信,Semaphore支持公平锁和非公平锁,Semaphore底
- 本项目使用的环境:开发工具:Intellij IDEA 2017.1.3springboot: 1.5.6jdk:1.8.0_161mave
- 详解Java虚拟机管理的内存运行时数据区域概述 Java虚拟机在执行Java程序的过程中会把它所管理的内
- 一.线程池简介线程池的概念线程池就是首先创建一些线程,它们的集合称为线程池,使用线程池可以很好的提高性能,线程池在系统启动时既创建大量空闲的
- 1、IO流1.流和流的分类什么是IO流?I:Input (输入)O: Ouput(输出)IO流的分类?有多种分类方式:一种方式是按照流的方向
- 背景近期因实际项目需要,在特定操作下触发定位请求,取到用户位置及附近位置。问题:经初步选型,最终决定接入百度定位,按照百度定位SDK And
- 【前言】面向资源的 Restful 风格的 api 接口本着简洁,资源,便于扩展,便于理解等等各项优势,在如今的系统服务中越来越受欢迎。.n
- C#实现组合排列的方法  
- 需求是在我按下按钮时,该变按钮颜色,使用户感觉到自己按了按钮,当松开的时候,变回原来的颜色。正常时:按下时:有人说,直接监听按钮的按下事件不
- 本文实例讲述了WinForm实现的图片拖拽与缩放功能。分享给大家供大家参考,具体如下:最近做项目的时候遇到上传施工平面布置图,查看,因为图片
- 前言:如果让大家说出一款国内比较热门的社交软件,那无疑就是QQ和微信了,说到微信,无不例外的会想到微信公众号和小程序,所以现在它们已经是很多
- 本文实例讲述了C#图像伪彩色处理方法。分享给大家供大家参考。具体如下://灰度图转伪彩色图像函数public Bitmap PGrayToC
- 前言Springboot应用在启动的时候分为两步:首先生成 SpringApplication 对象 ,运行 SpringApplicati
- 前言有位朋友,某天突然问东哥:在 Java 中,防止重复提交最简单的方案是什么?这句话中包含了两个关键信息,第一:防止重复提交;第二:最简单
- 什么是枚举类型枚举类型(Enumerated Type) 很早就出现在编程语言中,它被用来将一组类似的值包含到一种类型当中。而这种枚举类型的
- java中如何表示圆周率设计一个Shape接口和它的两个实现类Square和Circle。 要求如下(1) Shape接口中有一个抽象方法a
- 1.概念a.是个二叉树(每个节点最多有两个子节点)b.对于这棵树中的节点的节点值左子树中的所有节点值 < 根节点 < 右子树的所
- C#定义多行字符串的方式在定义的前面加上@符号: string aa = @"asdfsdfsd &n
- 前言开发中常用到主从数据库来提高系统的性能。怎么样才能方便的实现主从读写分离呢?近日工作任务较轻,有空学习学习技术,遂来研究如果实现读写分离