网创优客建站品牌官网
为成都网站建设公司企业提供高品质网站建设
热线:028-86922220
成都专业网站建设公司

定制建站费用3500元

符合中小企业对网站设计、功能常规化式的企业展示型网站建设

成都品牌网站建设

品牌网站建设费用6000元

本套餐主要针对企业品牌型网站、中高端设计、前端互动体验...

成都商城网站建设

商城网站建设费用8000元

商城网站建设因基本功能的需求不同费用上面也有很大的差别...

成都微信网站建设

手机微信网站建站3000元

手机微信网站开发、微信官网、微信商城网站...

建站知识

当前位置:首页 > 建站知识

SpringBoot中如何使用EhCache-创新互联

这篇文章给大家介绍SpringBoot中如何使用EhCache,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

为同安等地区用户提供了全套网页设计制作服务,及同安网站建设行业解决方案。主营业务为成都网站制作、成都网站建设、外贸营销网站建设、同安网站设计,以传统方式定制建设网站,并提供域名空间备案等一条龙服务,秉承以专业、用心的态度为用户提供真诚的服务。我们深信只要达到每一位用户的要求,就会得到认可,从而选择与我们长期合作。这样,我们也可以走得更远!

一、EhCache使用演示

EhCache是一个纯Java的进程内缓存框架,具有快速、精干等特点,Hibernate中的默认Cache就是使用的EhCache。

本章节示例是在Spring Boot集成Spring Cache的源码基础上进行改造。源码地址:https://github.com/imyanger/springboot-project/tree/master/p20-springboot-cache

使用EhCache作为缓存,我们先引入相关依赖。

 org.springframework.boot  spring-boot-starter-web  net.sf.ehcache  ehcache  org.springframework.boot  spring-boot-starter-cache

然后创建EhCache的配置文件ehcache.xml。

         

然后SpringBoot配置文件中,指明缓存类型并声明Ehcache配置文件的位置。

server: port: 10900spring: profiles:  active: dev cache:  type: ehcache  ehcache:   config: classpath:/ehcache.xml

这样就可以开始使用Ehcache了,测试代码与Spring Boot集成Spring Cache一致。

SpringBoot启动类,@EnableCaching开启Spring Cache缓存功能。

@EnableCaching@SpringBootApplicationpublic class SpringbootApplication {  public static void main(String[] args) {    String tmpDir = System.getProperty("java.io.tmpdir");    System.out.println("临时路径:" + tmpDir);    SpringApplication.run(SpringbootApplication.class, args);  }}

CacheApi接口调用类,方便调用进行测试。

@RestController@RequestMapping("cache")public class CacheApi {  @Autowired  private CacheService cacheService;  @GetMapping("get")  public User get(@RequestParam int id){    return cacheService.get(id);  }  @PostMapping("set")  public User set(@RequestParam int id, @RequestParam String code, @RequestParam String name){    User u = new User(code, name);    return cacheService.set(id, u);  }  @DeleteMapping("del")  public void del(@RequestParam int id){    cacheService.del(id);  }  }

CacheService缓存业务处理类,添加缓存,更新缓存和删除。

@Slf4j@Servicepublic class CacheService {  private Map dataMap = new HashMap (){    {      for (int i = 1; i < 100 ; i++) {        User u = new User("code" + i, "name" + i);        put(i, u);      }    }   };  // 获取数据  @Cacheable(value = "cache", key = "'user:' + #id")  public User get(int id){    log.info("通过id{}查询获取", id);    return dataMap.get(id);  }  // 更新数据  @CachePut(value = "cache", key = "'user:' + #id")  public User set(int id, User u){    log.info("更新id{}数据", id);    dataMap.put(id, u);    return u;   }  //删除数据  @CacheEvict(value = "cache", key = "'user:' + #id")  public void del(int id){    log.info("删除id{}数据", id);    dataMap.remove(id);  }  }

关于SpringBoot中如何使用EhCache就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。


网站标题:SpringBoot中如何使用EhCache-创新互联
标题路径:http://bjjierui.cn/article/pgppg.html

其他资讯