栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

1.pom.xml



  net.sf.ehcache
  ehcache

2.ehcache.xml



 
  
 
  
  
    
  
  
  
 
  

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

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

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;
 
 

@Component
public class CacheService {
 
  @Autowired
  private CacheManager cacheManager;
  
  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;
  }
 
  
  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));
    
    //将所有缓存项从内存刷新到磁盘存储,并从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;
  }
}

结果:

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/133500.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号