Spring Boot缓存实战 EhCache示例

 更新时间:2017年08月14日 15:33:45   作者:xiaolyuh  
本篇文章主要介绍了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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • JAVA简单实现MD5注册登录加密实例代码

    JAVA简单实现MD5注册登录加密实例代码

    本篇文章主要介绍了JAVA简单实现MD5注册登录加密实例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-03-03
  • Java 如何使用JDBC连接数据库

    Java 如何使用JDBC连接数据库

    这篇文章主要介绍了Java 如何使用JDBC连接数据库,帮助大家更好的理解和学习使用Java,感兴趣的朋友可以了解下
    2021-02-02
  • JDK源码中一些实用的“小技巧”总结

    JDK源码中一些实用的“小技巧”总结

    这篇文章主要给大家总结介绍了关于JDK源码中一些实用的“小技巧”,文中通过示例代码介绍的非常详细,对大家学习或者使用jdk源码具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧。
    2018-03-03
  • SpringBoot的三大开发工具小结

    SpringBoot的三大开发工具小结

    本文主要介绍了SpringBoot的三大开发工具,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-02-02
  • 详解使用zxing库生成QR-Code二维码

    详解使用zxing库生成QR-Code二维码

    这篇文章主要介绍了详解使用zxing库生成QR-Code二维码的相关资料,需要的朋友可以参考下
    2017-05-05
  • 使用@ConditionalOnProperty控制是否加载的操作

    使用@ConditionalOnProperty控制是否加载的操作

    这篇文章主要介绍了使用@ConditionalOnProperty控制是否加载的操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-06-06
  • 基于Java实现计数排序,桶排序和基数排序

    基于Java实现计数排序,桶排序和基数排序

    这篇文章主要为大家详细介绍了计数排序,桶排序和基数排序的多种语言的实现(JavaScript、Python、Go语言、Java),感兴趣的小伙伴可以了解一下
    2022-12-12
  • Java反射技术原理与用法实例分析

    Java反射技术原理与用法实例分析

    这篇文章主要介绍了Java反射技术原理与用法,结合实例形式分析了Java反射技术的基本概念、功能、原理、用法及操作注意事项,需要的朋友可以参考下
    2020-04-04
  • MyBatis查询返回Map示例代码

    MyBatis查询返回Map示例代码

    这篇文章主要给大家介绍了关于MyBatis查询返回Map的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2018-10-10
  • Java中System.currentTimeMillis()计算方式与时间单位转换讲解

    Java中System.currentTimeMillis()计算方式与时间单位转换讲解

    本文详细讲解了Java中System.currentTimeMillis()计算方式与时间单位转换,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-12-12

最新评论