全网整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:400-708-3566

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

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


# Spring  # Boot缓存  # Boot  # EhCache  # 在Mybatis中使用自定义缓存ehcache的方法  # SpringBoot2 整合Ehcache组件  # 轻量级缓存管理的原理解析  # Spring Boot集成Ehcache缓存解决方式  # SpringBoot中Shiro缓存使用Redis、Ehcache的方法  # 使用ehcache三步搞定springboot缓存的方法示例  # 详解Spring Boot Oauth2缓存UserDetails到Ehcache  # spring-boot整合ehcache实现缓存机制的方法  # Java Ehcache缓存框架入门级使用实例  # 详解SpringBoot缓存的实例代码(EhCache 2.x 篇)  # Spring+EHcache缓存实例详解  # 详解Spring MVC 集成EHCache缓存  # Java缓存ehcache的使用步骤  # 的是  # 配置文件  # 也很  # 可以通过  # 不做  # 只需要  # 可以看出  # 所需要  # 来实现  # 大家多多  # 切换到  # 返回值  # service  # PersonService  # Person  # beans  # impl  # PersonRepository  # repository  # import 


相关文章: 微信小程序制作网站有哪些,微信小程序需要做网站吗?  制作网站怎么制作,*游戏网站怎么搭建?  广州网站制作的公司,现在专门做网站的公司有没有哪几家是比较好的,性价比高,模板也多的?  高端智能建站公司优选:品牌定制与SEO优化一站式服务  视频网站制作教程,怎么样制作优酷网的小视频?  如何通过多用户协作模板快速搭建高效企业网站?  定制建站流程步骤详解:一站式方案设计与开发指南  宝塔建站教程:一键部署配置流程与SEO优化实战指南  建站之星如何配置系统实现高效建站?  建站主机助手选型指南:2025年热门推荐与高效部署技巧  自助网站制作软件,个人如何自助建网站?  建站中国官网:模板定制+SEO优化+建站流程一站式指南  音响网站制作视频教程,隆霸音响官方网站?  免费制作统计图的网站有哪些,如何看待现如今年轻人买房难的情况?  ,怎么在广州志愿者网站注册?  如何基于云服务器快速搭建个人网站?  建站之星logo尺寸如何设置最合适?  个人网站制作流程图片大全,个人网站如何注销?  西安专业网站制作公司有哪些,陕西省建行官方网站?  已有域名如何快速搭建专属网站?  建站主机如何选?性能与价格怎样平衡?  如何在云指建站中生成FTP站点?  如何在Tomcat中配置并部署网站项目?  Dapper的Execute方法的返回值是什么意思 Dapper Execute返回值详解  小米网站链接制作教程,请问miui新增网页链接调用服务有什么用啊?  专业网站制作服务公司,有哪些网站可以免费发布招聘信息?  定制建站方案优化指南:企业官网开发与建站费用解析  Thinkphp 中 distinct 的用法解析  制作营销网站公司,淘特是干什么用的?  ppt在线制作免费网站推荐,有什么下载免费的ppt模板网站?  如何用PHP快速搭建高效网站?分步指南  网站图片在线制作软件,怎么在图片上做链接?  建站之星安装后如何配置SEO及设计样式?  如何在万网开始建站?分步指南解析  建站之星云端配置指南:模板选择与SEO优化一键生成  桂林网站制作公司有哪些,桂林马拉松怎么报名?  用v-html解决Vue.js渲染中html标签不被解析的问题  网页制作模板网站推荐,网页设计海报之类的素材哪里好?  宝华建站服务条款解析:五站合一功能与SEO优化设置指南  建站VPS选购需注意哪些关键参数?  专业企业网站设计制作公司,如何理解商贸企业的统一配送和分销网络建设?  建站之星伪静态规则如何设置?  rsync同步时出现rsync: failed to set times on “xxxx”: Operation not permitted  如何通过宝塔面板实现本地网站访问?  电脑免费海报制作网站推荐,招聘海报哪个网站多?  宁波免费建站如何选择可靠模板与平台?  公司门户网站制作流程,华为官网怎么做?  建站之星导航菜单设置与功能模块配置全攻略  c++怎么用jemalloc c++替换默认内存分配器【性能】  香港服务器部署网站为何提示未备案? 

您的项目需求

*请认真填写需求信息,我们会在24小时内与您取得联系。