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
0
投稿
猜你喜欢
- 本文实例为大家分享了Android实现登录注册功能的具体代码,供大家参考,具体内容如下运行环境 Android Studio总体效果图一、
- 什么是JMMJMM全称Java Memory Model, 中文翻译Java内存模型,一种符合内存模型规范的,屏蔽了各种硬件和操作系统的访问
- IoC的概念介绍控制反转(IOC)模式(又称DI:Dependency Injection)就是Inversion of Control,控
- idea spring Initializr创建项目勾选项目所需要的依赖pom.xml文件会加载勾选的依赖,也可以不勾选后面通过自己常用的p
- GET请求不支持对象传参问题@GetMapping("/getByParam")String hello(Student
- java 进制转换实例详解十进制转成十六进制:  
- 前言:我们每天都在编写Java代码,编译,执行。很多人已经知道Java源代码文件(.java后缀)会被Java编译器编译为字节码文件(.cl
- 公司的老项目要改造多租户,于是进入了大坑,本文写点遇到的坑以及解决方案,每次遇到问题在网上搜了好久,记录下来,防止以后忘掉。(一).方案网上
- 一、Rxjava使用场景为了模拟实际场景,从wanandroid网站找了二个接口,如下:(对Wanandroid表示感谢!)public i
- MediaQuery通常情况下,不会直接将MediaQuery当作一个控件,而是使用MediaQuery.of获取当前设备的信息,用法如下:
- 前言上一篇我们认识了Kotlin编程语言,也搭建好开发环境。本篇就进入Kotlin的基础语法介绍,与其他编程语言一样,Kotlin也有自己的
- 导入redis的jar包<!-- redis --> <dependency>  
- IOS与网页JS交互随着移动APP的快速迭代开发趋势,越来越多的APP中嵌入了html网页,但在一些大中型APP中,尤其是电商类
- 一、什么是过滤器过滤器是对数据进行过滤,预处理过程,当我们访问网站时,有时候会发布一些敏感信息,发完以后有的会用*替代,还有就是登陆权限控制
- 本文实例讲述了Android+SQLite数据库实现的生词记事本功能。分享给大家供大家参考,具体如下:主activity命名为Dict:代码
- 第1部分 ArrayList介绍ArrayList简介ArrayList 是一个数组队列,相当于 动态数组。与Java中的数组相比,它的容量
- 前言最近在逛博客的时候看到了有关Redis方面的面试题,其中提到了Redis在内存达到最大限制的时候会使用LRU等淘汰机制,然后找了这方面的
- 被kafka-client和springkafka版本坑上周刚刚欢天喜地的在linux上部了kafka,这周打算用spring-boot框架
- 静态库和动态库的区别1、静态库的扩展名一般为".a"或者".lib";动态库的扩展名一般为"
- 本文实例讲述了C#获取网页源代码的方法。分享给大家供大家参考。具体如下:public string GetPageHTML(string u