Springboot使用cache缓存过程代码实例

 更新时间:2020年06月30日 08:32:48   投稿:yaominghui  
这篇文章主要介绍了Springboot使用cache缓存过程代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

1.pom.xml

<!-- Ehcache 坐标 -->
<dependency>
  <groupId>net.sf.ehcache</groupId>
  <artifactId>ehcache</artifactId>
</dependency>

2.ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
 
  <diskStore path="java.io.tmpdir"/>
 
  <!--defaultCache:echcache的默认缓存策略 -->
  <defaultCache
      maxElementsInMemory="10000"
      eternal="false"
      timeToIdleSeconds="120"
      timeToLiveSeconds="120"
      maxElementsOnDisk="10000000"
      diskExpiryThreadIntervalSeconds="120"
      memoryStoreEvictionPolicy="LRU">
    <persistence strategy="localTempSwap"/>
  </defaultCache>
  <!--
    maxElementsInMemory设置成1,overflowToDisk设置成true,只要有一个缓存元素,就直接存到硬盘上去
    eternal设置成true,代表对象永久有效
    maxElementsOnDisk设置成0 表示硬盘中最大缓存对象数无限大
    diskPersistent设置成true表示缓存虚拟机重启期数据
  -->
  <cache name="usercache"
      maxElementsInMemory="1"
      eternal="true"
      overflowToDisk="true"
      maxElementsOnDisk="0"
      diskPersistent="true">
<!--    <persistence strategy="localTempSwap"/>--> <!--不能和diskPersistent 同时存在-->
  </cache>

diskStore是物理文件的存储路径,

cache标签中的name是多cache时区分的唯一标识, 和程序中初始化方法getCache("***")参数一致。<br>缓存参数和本地数据持久化存储需自行配置

3.application.yml

spring:
 cache:
  ehcache:
   config: classpath:/ehcache.xml

4.启动类添加

@EnableCaching

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
 
@EnableCaching
@SpringBootApplication
public class DemoApplication {
 
  public static void main(String[] args) {
    SpringApplication.run(DemoApplication.class, args);
  }
 
}

5.springcloud 中使用cache

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
 
import java.io.IOException;
 
 
/**
 * @Author: Peacock__
 * @Date: 2019/6/14 17:30
 */
@Component
public class CacheService {
 
  @Autowired
  private CacheManager cacheManager;
  /**
   * 从缓存中获取数据
   * @return
   * @throws IOException
   */
  public String getCache() throws IOException {
   String res = "";
 
    Cache cache = cacheManager.getCache("usercache");
    if(cache != null){
      Element element = cache.get("name");
      if(element != null){
        Object objectValue = element.getObjectValue();
        res = (String) objectValue;
      }
    }
    return res;
  }
 
  /**
   * 数据存入缓存
   * @param data
   * @throws IOException
   */
  public void putCache(String data) throws IOException {
    //若cacheManager被关闭,则重新创建
    if(cacheManager == null || cacheManager.getStatus().intValue() != 1){
      cacheManager = new CacheManager(new ClassPathResource("ehcache.xml").getInputStream());
    }
    Cache cache = cacheManager.getCache("usercache");
    //处理成要缓存的数据
 
    //存入缓存(注意:需要保证存入缓存的数据都是可序列化的)
    cache.put(new Element("name", data));
    /**
     * ehcache和其它缓存类似,需要flush或shutdown后才会持久化到磁盘。
     * 会生成.data 的数据文件和 .index 的索引文件,方便重启恢复。
     * ehcache恢复数据是根据.index索引文件来进行数据恢复的。
     * 当程序再次启动的时候,ehcache的一个方法会将.data文件和.index文件的修改时间进行比较,如果不符合直接将.index文件删除。
     */
    //将所有缓存项从内存刷新到磁盘存储,并从DiskStore刷新到磁盘。
//    cache.flush();
    //更新.index文件
//    cacheManager.shutdown();
  }
}

6.controller层

import java.io.IOException;
 
@RestController
public class AppController{
 
 
  @Autowired
  private CacheService cacheService;
 
  @RequestMapping("/setName")
  public String setName() {
 
    try {
      cacheService.putCache( "heshan");
    } catch (IOException e) {
      e.printStackTrace();
    }
    return "yes";
  }
  @RequestMapping("/getName")
  public String getName() {
 
    String res = null;
    try {
      res = cacheService.getCache( );
    } catch (IOException e) {
      e.printStackTrace();
    }
    return res;
  }
}

结果:

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

相关文章

  • Mybatis choose when用法实例代码

    Mybatis choose when用法实例代码

    本文通过实例代码给大家介绍了Mybatis choose when用法,需要的的朋友参考下吧
    2017-06-06
  • springmvc集成shiro登录权限示例代码

    springmvc集成shiro登录权限示例代码

    本篇文章主要介绍了springmvc集成shiro登录权限示例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-02-02
  • 通过实例深入学习Java的Struts框架中的OGNL表达式使用

    通过实例深入学习Java的Struts框架中的OGNL表达式使用

    这篇文章主要通过实例介绍了Java的Strus框架中的OGNL表达式使用,Struts框架是Java的SSH三大web开发框架之一,需要的朋友可以参考下
    2015-11-11
  • Spring Security认证器实现过程详解

    Spring Security认证器实现过程详解

    一些权限框架一般都包含认证器和决策器,前者处理登陆验证,后者处理访问资源的控制,这篇文章主要介绍了Spring Security认证器实现过程,需要的朋友可以参考下
    2022-06-06
  • Java数组操作经典例题大总结

    Java数组操作经典例题大总结

    数组是在内存中存储相同数据类型的连续的空间,声明一个数组就是在内存空间中划出一串连续的空间,下面这篇文章主要给大家介绍了关于Java数组操作经典例题的相关资料,需要的朋友可以参考下
    2022-03-03
  • 浅谈spring DI 依赖注入方式和区别

    浅谈spring DI 依赖注入方式和区别

    Spring框架对Java开发的重要性不言而喻,本文主要介绍了spring DI 依赖注入方式和区别,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-07-07
  • SpringBoot Session接口验证实现流程详解

    SpringBoot Session接口验证实现流程详解

    这篇文章主要介绍了SpringBoot+Session实现接口验证(过滤器+拦截器)文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-09-09
  • JAVA使用POI获取Excel的列数与行数

    JAVA使用POI获取Excel的列数与行数

    Apache POI 是用Java编写的免费开源的跨平台的 Java API,Apache POI提供API给Java程式对Microsoft Office格式档案读和写的功能。 下面这篇文章给大家介绍了JAVA使用POI获取Excel列数和行数的方法,有需要的朋友们可以参考借鉴,下面来一起看看吧。
    2016-12-12
  • Java运行时数据区域(内存划分)的深入讲解

    Java运行时数据区域(内存划分)的深入讲解

    听说Java运行时环境的内存划分是挺进BAT的必经之路,这篇文章主要给大家介绍了关于Java运行时数据区域(内存划分)的相关资料,需要的朋友可以参考下
    2021-06-06
  • 高效的java版排列组合算法

    高效的java版排列组合算法

    这篇文章主要为大家详细介绍了高效的java版排列组合算法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-02-02

最新评论