Spring Boot緩存實戰 EhCache

Spring boot默認使用的是SimpleCacheConfiguration,即便用ConcurrentMapCacheManager來實現緩存。可是要切換到其餘緩存實現也很簡單java

pom文件

在pom中引入相應的jar包mysql

<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會自動掃描。git

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

也能夠經過在application.properties文件中,經過配置來指定EhCache配置文件的位置,如:github

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

Spring Boot會自動爲咱們配置EhCacheCacheMannager的Bean。web

關鍵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());
        }
    }

}

打印日誌

從上面能夠看出第一次走的是數據庫,第二次走的是緩存spring

源碼: https://github.com/wyh-spring-ecosystem-student/spring-boot-student/tree/releasessql

spring-boot-student-cache-ehcache 工程數據庫

爲監控而生的多級緩存框架 layering-cache這是我開源的一個多級緩存框架的實現,若是有興趣能夠看一下apache

相關文章
相關標籤/搜索