快速启动
Maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!-- Ehcache 坐标 -->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
resouce下创建encache.xml文件。完成配置文件
<?xml version="1.0" encoding="UTF-8"?>
<ehcache updateCheck="false" name="defaultCache">
<!-- 磁盘缓存位置 -->
<diskStore path="java.io.tmpdir/ehcache"/>
<!--
maxEntriesLocalHeap:堆内存中最大缓存对象数
eternal:对象是否永久有效,一但设置了,timeout将不起作用
overflowToDisk:当缓存达到maxElementsInMemory值是,是否允许溢出到磁盘
timeToIdleSeconds:当缓存闲置n秒后销毁
timeToLiveSeconds:当缓存存活n秒后销毁
maxEntriesLocalDisk:硬盘最大缓存个数
diskPersistent:磁盘缓存在JVM重新启动时是否保持
-->
<!-- 默认缓存 -->
<defaultCache
maxEntriesLocalHeap="10000"
eternal="false"
timeToIdleSeconds="600"
timeToLiveSeconds="600"
maxEntriesLocalDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU"/>
<!-- fill-in缓存 -->
<cache name="fillIn"
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="600"
timeToLiveSeconds="600"
overflowToDisk="false"
memoryStoreEvictionPolicy="LRU"/>
</ehcache>
构建需要被缓存的方法方法:
@Cacheable(value ="UserCache")
public User getChache(){
User user=userMapper.getUserInfo();
return user;
}
value是必须有的属性(代表一个缓存的名字,可以有多个名字)
@Cacheable(value = {"get","word"})
应该也可以重复(没测试过)
两次调用调用方法:
第二次因为缓存的缘故。速度远远快于第一次。
给缓存添加key属性。(这里以p0,第一个参数加上类名和方法名作为key进行缓存的匹配命中)
测试一:
结果:
测试二:
综上:测试一缓存未命中而测试二命中了(虽然测试一第二次速度也比第一次快。但是这应该是因为第一次连接过一次数据库导致的速度加快)
spel表达式
(解析器->表达式)->数据源(可以是实例,也可以是上下文)
一,操作实例
二,操作上下文
@Test
public void demo_2(){
User user=new User();
user.setId("123");
ExpressionParser expressionParser=new SpelExpressionParser();
// 表达式
Expression idExp = expressionParser.parseExpression("id=='1'+#ending");//ending为实例
/*
* 第一次用法使用解析出实例中的属性,这种用法的时候id必须被实例填充不然会报错
* */
Object value = idExp.getValue(user);
System.out.println(value);
/*
* 第二种用法解析出上下文中的变量
* */
EvaluationContext evaluationContext=new StandardEvaluationContext();
Expression expression_context = expressionParser.parseExpression("#str+#list");
evaluationContext.setVariable("str","哈哈哈");
List list=new LinkedList();
list.add("arr1");
list.add("arr2");
evaluationContext.setVariable("list",list);
System.out.println(expression_context.getValue(evaluationContext));//两个变量输出的时候被拼接成字符串了
}