redis 和 ehcache
redis 基于socket 的一种分布式缓存,适用于分布式系统的一种分布式缓存,在处理多系统的情况上,消息处理机制 有很好的解决方案
ehcache基于jvm 的一种缓存方式 适用于单系统 由于是基于磁盘的 所以效率高于redis 但是分布式处理上面会比redis 弱一些 如果仅仅是单系统 不是分布式系统可以优先考虑ehcache
spring boot 集成ehcache 3.7
1.resources 目录下面创建 ehcache.xml 文件
<?xml version="1.0" encoding="UTF-8"?>
<config
xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xmlns:jsr107='http://www.ehcache.org/v3/jsr107'
xmlns='http://www.ehcache.org/v3'
xsi:schemaLocation="
http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.7.xsd
http://www.ehcache.org/v3/jsr107 http://www.ehcache.org/schema/ehcache-107-ext-3.7.xsd">
<persistence directory="${java.io.tmpdir}/sparepart-ehcache"/> // 添加缓存路径
<cache alias="shiro-activeSessionCache"> // shrio缓存登陆
<key-type serializer="org.ehcache.impl.serialization.CompactJavaSerializer">
java.lang.Object
</key-type>
<value-type serializer="org.ehcache.impl.serialization.CompactJavaSerializer">
java.lang.Object
</value-type>
<resources>
<heap unit="entries">10000</heap>
<disk unit="GB">1</disk>
</resources>
</cache>
<cache alias="SysRole">
<key-type>java.lang.Object</key-type>
<value-type>com.xxx.sparepart.entity.SysRole</value-type>
<heap>5000</heap>
</cache>
<cache alias="TempTokes">
<key-type>
java.lang.Object
</key-type>
<value-type>
java.lang.Object
</value-type>
<heap>5000</heap>
</cache>
</config>
2.springboot 中 application.properties 中引用ehcache.xml
spring.cache.jcache.config=classpath:ehcache.xml
3.spring boot 中主程序入口加上注解@EnableCaching
@SpringBootApplication(scanBasePackages = "com.h3c.sparepart")
@EnableWebMvc
@EnableCaching
@EnableTransactionManagement
public class SparePartApplication extends SpringBootServletInitializer {}
4.一般情况下使用缓存多在service层里面 因为所有的业务路基也多发在该层、
@Service
@CacheConfig(cacheNames = "TempTokes") --- 这个是引用名称为TempTokes的缓存
public class ButtonTService {
@Autowired
private ButtoTRepository buttoTRepository;
@Cacheable(cacheNames = "TempTokes", key = "#id") --这个注解是先从缓存里面查询如果有key = 传入id值得缓存数据则返回 如果没有执行方法内的数据插入缓存返回
public String getClientToken(String id){
String token = TokenProccessor.getInstance().makeToken();
System.out.println("-------产生token值存入缓存-------");
System.out.println(token);
System.out.println("-------产生token值存入缓存-------");
return token;
}
@CacheEvict(key = "#id") ---这个注解是从缓存中删除key 值为id 的缓存数据
public void removeCacheToken(String id){
System.out.println("-------删除缓存token值-------");
System.out.println("-------删除缓存token值-------");
}
}