Spring Boot緩存實(shí)戰(zhàn) EhCache示例
Spring boot默認(rèn)使用的是SimpleCacheConfiguration,即使用ConcurrentMapCacheManager來(lái)實(shí)現(xiàn)緩存。但是要切換到其他緩存實(shí)現(xiàn)也很簡(jiǎn)單
pom文件
在pom中引入相應(yīng)的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會(huì)自動(dòng)掃描。
<?xml version="1.0" encoding="UTF-8"?> <ehcache> <cache name="people" maxElementsInMemory="1000"/> </ehcache>
也可以通過(guò)在application.properties文件中,通過(guò)配置來(lái)指定EhCache配置文件的位置,如:
spring.cache.ehcache.config= # ehcache配置文件地址
Spring Boot會(huì)自動(dòng)為我們配置EhCacheCacheMannager的Bean。
關(guān)鍵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() + "數(shù)據(jù)做了緩存");
return p;
}
@Override
@CacheEvict(value = "people")//2
public void remove(Long id) {
System.out.println("刪除了id、key為" + id + "的數(shù)據(jù)緩存");
//這里不做實(shí)際刪除操作
}
@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() + "數(shù)據(jù)做了緩存");
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";
}
}
啟動(dòng)類
@SpringBootApplication
@EnableCaching// 開啟緩存,需要顯示的指定
public class SpringBootStudentCacheApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootStudentCacheApplication.class, args);
}
}
測(cè)試類
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對(duì)象,通過(guò)MockMvcBuilders.webAppContextSetup(this.wac).build()初始化。
@Autowired
private WebApplicationContext wac; // 注入WebApplicationContext
// @Autowired
// private MockHttpSession session;// 注入模擬的http session
//
// @Autowired
// private MockHttpServletRequest request;// 注入模擬的http request\
@Before // 在測(cè)試開始前初始化工作
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發(fā)送get請(qǐng)求
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))// 預(yù)期返回值的媒體類型text/plain;
// charset=UTF-8
.andReturn();// 返回執(zhí)行請(qǐng)求的結(jié)果
System.out.println(result.getResponse().getContentAsString());
}
}
}
打印日志

從上面可以看出第一次走的是數(shù)據(jù)庫(kù),第二次走的是緩存
源碼:https://github.com/wyh-spring-ecosystem-student/spring-boot-student/tree/releases
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- 在Mybatis中使用自定義緩存ehcache的方法
- SpringBoot2 整合Ehcache組件,輕量級(jí)緩存管理的原理解析
- Spring Boot集成Ehcache緩存解決方式
- SpringBoot中Shiro緩存使用Redis、Ehcache的方法
- 使用ehcache三步搞定springboot緩存的方法示例
- 詳解Spring Boot Oauth2緩存UserDetails到Ehcache
- spring-boot整合ehcache實(shí)現(xiàn)緩存機(jī)制的方法
- Java Ehcache緩存框架入門級(jí)使用實(shí)例
- 詳解SpringBoot緩存的實(shí)例代碼(EhCache 2.x 篇)
- Spring+EHcache緩存實(shí)例詳解
- 詳解Spring MVC 集成EHCache緩存
- Java緩存ehcache的使用步驟
相關(guān)文章
詳解如何使用Jersey客戶端請(qǐng)求Spring Boot(RESTFul)服務(wù)
本篇文章主要介紹了詳解如何使用Jersey客戶端請(qǐng)求Spring Boot(RESTFul)服務(wù),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-01-01
MyBatis獲取插入記錄的自增長(zhǎng)字段值(ID)
本文分步驟給大家介紹了MyBatis獲取插入記錄的自增長(zhǎng)字段值的方法,在文中給大家提到了mybatis返回插入數(shù)據(jù)的自增長(zhǎng)id,需要的朋友可以參考下2017-11-11
SpringBoot RestTemplate 簡(jiǎn)單包裝解析
這篇文章主要介紹了SpringBoot RestTemplate 簡(jiǎn)單包裝解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-08-08
Springdoc替換swagger的實(shí)現(xiàn)步驟分解
最近在spring看到的,spring要對(duì)api文檔動(dòng)手了,有些人說(shuō)swagger不好用,其實(shí)也沒那么不好用,有人說(shuō)代碼還是有點(diǎn)侵入性,這倒是真的,我剛試了springdoc可以說(shuō)還是有侵入性但是也可以沒有侵入性,這就看你對(duì)文檔有什么要求了2023-02-02
Java Synchronize下的volatile關(guān)鍵字詳解
這篇文章主要介紹了Java Synchronize下的volatile關(guān)鍵字詳解,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-03-03
maven多模塊項(xiàng)目依賴管理與依賴?yán)^承詳解
這篇文章主要介紹了maven多模塊項(xiàng)目依賴管理與依賴?yán)^承詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-12-12
Java控制臺(tái)輸入數(shù)組并逆序輸出的方法實(shí)例
這篇文章主要介紹了Java手動(dòng)輸入數(shù)組并逆向輸出的方法實(shí)例,需要的朋友可以參考下。2017-08-08
Netty4之如何實(shí)現(xiàn)HTTP請(qǐng)求、響應(yīng)
這篇文章主要介紹了Netty4之如何實(shí)現(xiàn)HTTP請(qǐng)求、響應(yīng)問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-04-04
Java實(shí)現(xiàn)定時(shí)任務(wù)最簡(jiǎn)單的3種方法
幾乎在所有的項(xiàng)目中,定時(shí)任務(wù)的使用都是不可或缺的,如果使用不當(dāng)甚至?xí)斐少Y損,下面這篇文章主要給大家介紹了關(guān)于Java實(shí)現(xiàn)定時(shí)任務(wù)最簡(jiǎn)單的3種方法,本文通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-06-06

