好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Springboot+Mybatis集成自定义缓存Ehcache用法

今天小编给大家整理了springboot+mybatis集成自定义 缓存 ehcache用法笔记,希望对大家能有所办帮助!

一、ehcache介绍

EhCache 是一个纯Java的进程内缓存管理框架,属于开源的Java分布式缓存框架,主要用于通用缓存,Java EE和轻量级容器。

1、特点

1. 简单、快速

2. 提供多种缓存策略

3. 缓存数据可分两级:内存和磁盘

4. 缓存数据会在服务器重启的过程中重新写入磁盘

.5 可以通过RMI、可插入API等方式进行分布式缓存

6. 具有缓存和缓存管理器的侦听接口

7. 支持多缓存管理器实例,以及一个实例的多个缓存区域

8. 提供了Hibernate的缓存实现

2、应用场景

单应用或对缓存访问性能要求很高的应用

适合简单共享

适合缓存内容不大的场景,比如MyBatis自定义缓存、系统配置信息、页面缓存。

二、springboot+mybatis集成ehcache步骤

Spring Boot 的缓存机制

高速缓存抽象不提供实际存储,并且依赖于由org.springframework.cache.Cache和org.springframework.cache.CacheManager接口实现的抽象。 Spring Boot根据实现自动配置合适的CacheManager,只要缓存支持通过@EnableCaching注解启用即可。

1、添加ehcache.xml配置文件

<?xml version= "1.0"  encoding= "UTF-8" ?>  <ehcache xmlns:xsi= "http://HdhCmsTestw3.org/2001/XMLSchema-instance"       xsi:noNamespaceSchemaLocation= "http://ehcache.org/ehcache.xsd" >      <diskStore path= "java.io.tmpdir"  />        <! -- 配置提供者 1、peerDiscovery,提供者方式,有两种方式:自动发现(automatic)、手动配置(manual) 2、rmiUrls,手动方式时提供者的地址,多个的话用|隔开 -->       <cacheManagerPeerProviderFactory          class= "net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"           properties= "peerDiscovery=manual,rmiUrls=//127.0.0.1:40002/userCache"  />      <! -- <cacheManagerPeerProviderFactory           class= "net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"           properties= "peerDiscovery=automatic, multicastGroupAddress=230.0.0.1, multicastGroupPort=4446,timeToLive=255" />    -->       <! -- 配置监听器 1、hostName 主机地址 2、port 端口 3、socketTimeoutMillis socket子模块的超时时间,默认是2000ms -->       <cacheManagerPeerListenerFactory          class= "net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory"           properties= "hostName=127.0.0.1, port=40001, socketTimeoutMillis=2000"  />      <! -- <cacheManagerPeerListenerFactory            class= "net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory" />  -->           <defaultCache eternal= "false"  maxElementsInMemory= "1000"           overflowToDisk= "false"  diskPersistent= "false"  timeToIdleSeconds= "0"           timeToLiveSeconds= "600"  memoryStoreEvictionPolicy= "LRU"  />        <cache           name = "userCache"           maxElementsInMemory= "1000"           eternal= "false"           timeToIdleSeconds= "300"           timeToLiveSeconds= "300"           overflowToDisk= "false"           memoryStoreEvictionPolicy= "LRU" >              <! -- 配置缓存事件监听器 replicateAsynchronously 操作是否异步,默认值为true. replicatePuts 添加操作是否同步到集群内的其他缓存,默认为true.               replicateUpdates 更新操作是否同步到集群内的其他缓存,默认为 true . replicateUpdatesViaCopy 更新之后的对象是否复制到集群中的其他缓存( true );              replicateRemovals 删除操作是否同步到集群内的其他缓存,默认为 true .  -->           <cacheEventListenerFactory              class= "net.sf.ehcache.distribution.RMICacheReplicatorFactory"               properties="                      replicateAsynchronously= true ,                      replicatePuts= true ,                      replicateUpdates= true ,                      replicateUpdatesViaCopy= true ,                      replicateRemovals= true  " />               <! -- 初始化缓存,以及自动设置 -->           <bootstrapCacheLoaderFactory              class= "net.sf.ehcache.distribution.RMIBootstrapCacheLoaderFactory"               properties= "bootstrapAsynchronously=true"  />        </cache>    </ehcache> 

2、配置 application.properyies

#cache 配置cache     spring.cache.cache-names=userCache   spring.cache.jcache.config=classpath:ehcache.xml 

3、springboot启动类增加注解@EnableCaching

@SpringBootApplication  @ComponentScan(basePackages= "com.ehcache" )//扫描组件  @EnableCaching  public  class  Ehcache TestApplication {         public   static  void main(String[] args) {          SpringApplication.run(EhcacheTestApplication.class, args);      }  } 

4、UserInfoService.java 文件增加缓存注解

@Service  public  class UserInfoService {        @Autowired      private UserDao userDao;        @CacheEvict( key = "'user_'+#uid" , value= "userCache" )       public  void del(String uid) {                 userDao.del(uid);      }        @CachePut( key = "'user_'+#user.id" , value= "userCache" )       public  void  update ( User   user ) {          userDao. update ( user );      }        @Cacheable( key = "'user_'+#id" ,value= "userCache" )       public   User  getUserById(String id){                return  userDao.findById(id);    }        @CacheEvict( key = "'user'" ,value= "userCache" )       public  String save( User   user ) {                   return  userDao.save( user );      }  } 

5、增加测试控制器TestController.java

package com.ehcache.controller;    import java.util.ArrayList;  import java.util.HashMap;  import java.util.List;  import java.util.Map;    import javax.servlet.http.HttpServletRequest;    import org.springframework.beans.factory.annotation.Autowired;  import org.springframework.cache.annotation.CachePut;  import org.springframework.cache.annotation.Cacheable;  import org.springframework.web.bind.annotation.RequestMapping;  import org.springframework.web.bind.annotation.RequestMethod;  import org.springframework.web.bind.annotation.RequestParam;  import org.springframework.web.bind.annotation.ResponseBody;  import org.springframework.web.bind.annotation.RestController;    import com.ehcache.entity. User ;  import com.ehcache.factory.CacheManagerFactory;  import com.ehcache.factory.UserFactory;  import com.ehcache.service.UserService;  import com.google.gson.Gson;    import net.sf.ehcache.Element;      @RestController  @RequestMapping( "/CacheTest" )  public  class CacheTestController {      @Autowired      private UserService userService;      Gson gson = new Gson();      CacheManagerFactory cmf = CacheManagerFactory.getInstance();      @RequestMapping(value =  "/test" , method = RequestMethod.GET)       public  String test(HttpServletRequest request){          // 新增新用户          String id = userService.save(UserFactory.createUser());           User   user  = userService.getUserById(id);           user .setUsername( "小明" );          userService. update ( user );          // 查询该用户          System. out .println(gson.toJson( user ,  User .class));                System. out .println();          // 再查询该用户           User   user  = userService.getUserById(uid);          System. out .println(gson.toJson( user ,  User .class));          System. out .println();          // 更新该用户          userService. update ( user );          // 更新成功后再查询该用户        System. out .println(gson.toJson(userService.getUserById(id),  User .class));          System. out .println();          // 删除该用户          userService.del(id);          System. out .println();          // 删除后再查询该用户        System. out .println(gson.toJson(userService.getUserById(id),  User .class));           return  id;      }  } 

个人博客网站:https://programmerblog.xyz

原文链接:https://mp.weixin.qq测试数据/s/nSC-7Rgx6G4PF40Z6DxNUQ

查看更多关于Springboot+Mybatis集成自定义缓存Ehcache用法的详细内容...

  阅读:20次