今天继续学习springboot整合cache,本次用的是ehcache。
首先在pom文件中导入(此处springboot项目自带版本号):
<dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> </dependency>
其次在相关配置文件写入相关配置,本人用的是yml文件:
spring:
cache:
type: ehcache
ehcache:
config: ehcache.xml
由于ehcache是springboot外的技术,需要添加配置(创建一个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" updateCheck="false"> <diskStore path="D:\ehcache"/> <!-- 默认配置--> <defaultCache eternal="false" diskPersistent="false" maxElementsInMemory="1000" overflowToDisk="false" timeToIdleSeconds="60" timeToLiveSeconds="60" memoryStoreEvictionPolicy="LRU"/> <!-- 其他配置,调用方法时如果指定缓存名字如以下:smsCode,会在这个缓存中找数据--> <cache name="smsCode" eternal="false" diskPersistent="false" maxElementsInMemory="1000" overflowToDisk="false" timeToIdleSeconds="10" timeToLiveSeconds="10" memoryStoreEvictionPolicy="LRU"/> <!--timeToIdleSeconds="10" timeToLiveSeconds="10" 缓存10s后自动消失--> </ehcache>
接下来实际操作:
@CachePut(value = "smsCode",key = "#tel") //向缓存中放,不能取出 public String sendCodeToSMS(String tel) { String code = codeUtils.generator(tel); return code; }
欢迎大家一起学习,有不足的地方请及时指出。