? ? ? ? ? ? ? ?
今天小編給大家整理了springboot+mybatis集成自定義緩存ehcache用法筆記,希望對大家能有所辦幫助!
一、ehcache介紹
EhCache 是一個純Java的進程內緩存管理框架,屬于開源的Java分布式緩存框架,主要用于通用緩存,Java EE和輕量級容器。
1、特點
1. 簡單、快速
3. 提供多種緩存策略
4. 緩存數據可分兩級:內存和磁盤
5. 緩存數據會在服務器重啟的過程中重新寫入磁盤
6. 可以通過RMI、可插入API等方式進行分布式緩存
7. 具有緩存和緩存管理器的偵聽接口
8. 支持多緩存管理器實例,以及一個實例的多個緩存區域
9. 提供了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://www.w3.org/2001/XMLSchema-instance"xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"><diskStore path="java.io.tmpdir" /><!-- 配置提供者 1、peerDiscovery,提供者方式,有兩種方式:自動發現(automatic)、手動配置(manual) 2、rmiUrls,手動方式時提供者的地址,多個的話用|隔開 --><cacheManagerPeerProviderFactoryclass="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"properties="peerDiscovery=manual,rmiUrls=//127.0.0.1:40002/userCache" /><!-- <cacheManagerPeerProviderFactoryclass="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 --><cacheManagerPeerListenerFactoryclass="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory"properties="hostName=127.0.0.1, port=40001, socketTimeoutMillis=2000" /><!-- <cacheManagerPeerListenerFactoryclass="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory"/> --><defaultCache eternal="false" maxElementsInMemory="1000"overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0"timeToLiveSeconds="600" memoryStoreEvictionPolicy="LRU" /><cachename="userCache"maxElementsInMemory="1000"eternal="false"timeToIdleSeconds="300"timeToLiveSeconds="300"overflowToDisk="false"memoryStoreEvictionPolicy="LRU"><!-- 配置緩存事件監聽器 replicateAsynchronously 操作是否異步,默認值為true. replicatePuts 添加操作是否同步到集群內的其他緩存,默認為true.replicateUpdates 更新操作是否同步到集群內的其他緩存,默認為true. replicateUpdatesViaCopy 更新之后的對象是否復制到集群中的其他緩存(true);replicateRemovals 刪除操作是否同步到集群內的其他緩存,默認為true. --><cacheEventListenerFactoryclass="net.sf.ehcache.distribution.RMICacheReplicatorFactory"properties="replicateAsynchronously=true,replicatePuts=true,replicateUpdates=true,replicateUpdatesViaCopy=true,replicateRemovals=true " /><!-- 初始化緩存,以及自動設置 --><bootstrapCacheLoaderFactoryclass="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 EhcacheTestApplication {public static void main(String[] args) {SpringApplication.run(EhcacheTestApplication.class, args);}
}
4、UserInfoService.java 文件增加緩存注解
@Service
public class UserInfoService {@Autowiredprivate 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 {@Autowiredprivate 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;}
}
IT技術分享社區
個人博客網站:https://programmerblog.xyz
文章推薦程序員效率:畫流程圖常用的工具程序員效率:整理常用的在線筆記軟件遠程辦公:常用的遠程協助軟件,你都知道嗎?51單片機程序下載、ISP及串口基礎知識硬件:斷路器、接觸器、繼電器基礎知識