一、springboot缓存简介
在 Spring Boot中,通过@EnableCaching注解自动化配置合适的缓存管理器(CacheManager),Spring Boot根据下面的顺序去侦测缓存提供者:
* Generic
* JCache (JSR-107)
* EhCache 2.x
* Hazelcast
* Infinispan
* Redis
* Guava
* Simple
关于 Spring Boot 的缓存机制:
高速缓存抽象不提供实际存储,并且依赖于由org.springframework.cache.Cache和org.springframework.cache.CacheManager接口实现的抽象。 Spring Boot根据实现自动配置合适的CacheManager,只要缓存支持通过@EnableCaching注释启用即可。
二、实例
1、application.properyies
server.port=8850 #cache 多个用逗号分开
spring.cache.cache-names=userCache
spring.cache.jcache.config=classpath:ehcache.xml # datasource
spring.datasource.name=ehcahcetest
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3312/ehcahcetest
spring.datasource.username=root
spring.datasource.password=123456 # mybatis
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
mybatis.config-location=classpath:mybatis/mybatis-config.xml
#mybatis.type-aliases-package=
2、springboot启动类
@SpringBootApplication
@ComponentScan(basePackages="com.ehcache")//扫描组件
@EnableCaching
public class EhcacheTestApplication { public static void main(String[] args) {
SpringApplication.run(EhcacheTestApplication.class, args);
}
}
3、加了缓存注解的service
@Service
public class UserService { @Autowired
private UserDao userDao; @CacheEvict(key="'user_'+#uid", value="userCache")
public void del(String uid) {
// TODO Auto-generated method stub
userDao.del(uid);
} @CachePut(key="'user_'+#user.uid", value="userCache")
public void update(User user) {
userDao.update(user);
} @Cacheable(key="'user_'+#uid",value="userCache")
public User getUserById(String uid){
System.err.println("缓存里没有"+uid+",所以这边没有走缓存,从数据库拿数据");
return userDao.findById(uid); } @CacheEvict(key="'user'",value="userCache")
public String save(User user) {
// TODO Auto-generated method stub
return userDao.save(user);
} }
4、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,手动方式时提供者的地址,多个的话用|隔开 -->
<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>
5、OperationController.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("/o")
public class OperationController { @Autowired
private UserService userService; Gson gson = new Gson(); CacheManagerFactory cmf = CacheManagerFactory.getInstance(); @RequestMapping(value = "/test", method = RequestMethod.GET)
public String test(HttpServletRequest request){ // 保存一个新用户
String uid = userService.save(UserFactory.createUser());
User user = userService.getUserById(uid);
user.setUsername("xiaoli");
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(uid), User.class));
System.out.println();
// 删除该用户
userService.del(uid);
System.out.println();
// 删除好了再查询该用户
System.out.println(gson.toJson(userService.getUserById(uid), User.class));*/ // 再保存一个新用户
// String uid1 = userService.save(UserFactory.createUser()); return uid;
} @RequestMapping(value = "/test1", method = RequestMethod.GET)
public String test1(HttpServletRequest request,String key){ String res = ""; Element element = cmf.getElement("userCache", "map");
if(element == null){
Map<String, String> map = new HashMap<String, String>();
map.put(key, key);
cmf.setElement("userCache", new Element("map", map));
}else{
Map<String, String> map = (Map<String, String>) element.getValue();
res = map.get(key);
if(res == null){
map.put(key, key);
// 多次测试发现,存在同名Element是,重复put的是无法复制的,因此当遇到两个节点同步不上的时候,先remove后put。
cmf.getCache("userCache").remove("map");
cmf.setElement("userCache", new Element("map", map));
res = "0;null";
}
}
return res;
} }