系列课题
spring mvc mini(一)
抽象缓存定义
- spring cache主要抽象接口
org.springframework.cache.Cache
org.springframework.cache.CacheManager - 注解
@Cacheable触发缓存填充
@CacheEvict触发缓存驱逐
@CachePut更新缓存而不会干扰方法执行
@Caching重新组合要在方法上应用的多个缓存操作
@CacheConfig在 class-level 分享一些 common cache-related 设置
配置缓存
- 注解方式
@Configuration
@EnableCaching
public class AppConfig {
}
- 配置方式【效果同上】
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">
<cache:annotation-driven/>
</beans>
EHcahe实现
参考资料Spring Cache --- 整合进程缓存Ehcache3.x
缓存标准方面:一个是JSR107,一个是Spring Cache,前面也说了Spring Cache已经成为了现实中的标准,所以市面上它的实现产品非常丰富,因此本文主要看看基于Spring Cache的实现产品的集成方案。
Spring Cache它也是支持JSR107规范的,可谓非常的友好。(请导入spring-contextr-support包)
要想了解常用的、流行的Spring Cache的实现方案有哪些,我推荐一个由SpringBoot提枚举类CacheType,它里面收纳得还是比较全面的:
public enum CacheType {
GENERIC, // 使用的SimpleCacheManager(自己手动指定Cache,可任意类型Cache实现哦)
JCACHE, // 使用org.springframework.cache.jcache.JCacheCacheManager
EHCACHE, // 使用org.springframework.cache.ehcache.EhCacheCacheManager
HAZELCAST, // 使用com.hazelcast.spring.cache.HazelcastCacheManager
INFINISPAN, // 使用org.infinispan.spring.provider.SpringEmbeddedCacheManager
COUCHBASE, // 使用com.couchbase.client.spring.cache.CouchbaseCacheManager
REDIS, // 使用org.springframework.data.redis.cache.RedisCacheManager,依赖于RedisTemplate进行操作
CAFFEINE, // 使用org.springframework.cache.caffeine.CaffeineCacheManager
@Deprecated
GUAVA, // 使用org.springframework.cache.guava.GuavaCacheManager,已经过期不推荐使用了
SIMPLE, // 使用ConcurrentMapCacheManager
NONE; // 使用NoOpCacheManager,表示禁用缓存
}
spring-context-support即使在Spring5后,默认支持的还是EhCache2.x版本(毕竟有很重的历史包袱在呢),并且没有提供3.x版本的支持,故我们依然使用ehcache2
Ehcache 配置
- pom.xml引入依赖
<!-- ehcache引入 -->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.10.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.3.25.RELEASE</version>
</dependency>
- ehcache.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true"
monitoring="autodetect">
<!--
name:缓存名称。
maxElementsInMemory:缓存最大个数。
eternal:对象是否永久有效,一但设置了,timeout将不起作用。
timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。
overflowToDisk:当内存中对象数量达到maxElementsInMemory时,Ehcache将会对象写到磁盘中。
diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。
maxElementsOnDisk:硬盘最大缓存个数。
diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.
diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。
clearOnFlush:内存数量最大时是否清除。
-->
<!--缓存路径-->
<diskStore path="/opt/webapps/cache/ehcache"/>
<defaultCache maxElementsInMemory="10000"
maxElementsOnDisk="1000000" eternal="false" overflowToDisk="false"
timeToIdleSeconds="7200" timeToLiveSeconds="7200"
memoryStoreEvictionPolicy="LRU" diskPersistent="false" diskExpiryThreadIntervalSeconds="3000"/>
<cache name="javaEpgCache" maxElementsInMemory="10000"
maxElementsOnDisk="1000000" eternal="false" overflowToDisk="false"
timeToIdleSeconds="7200" timeToLiveSeconds="7200"
memoryStoreEvictionPolicy="LRU" diskPersistent="false" diskExpiryThreadIntervalSeconds="3000">
<!-- <BootstrapCacheLoaderFactory class="net.sf.ehcache.store.DiskStoreBootstrapCacheLoaderFactory" properties="bootstrapAsynchronously=true" /> -->
</cache>
</ehcache>
- 开始配置Cache
<!-- 缓存 -->
<bean id="cacheManager"
class="org.springframework.cache.ehcache.EhCacheCacheManager" p:cache-manager-ref="ehcache"/>
<bean id="ehcache"
class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" p:config-location="classpath:config/ehcache.xml"/>
<cache:annotation-driven/>
Cache简单使用
- 创建接口
public interface ICacheExample {
String autoCache();
}
- 创建实现
@Component
public class CacheExampleImp implements ICacheExample {
@Override
@Cacheable("javaEpgCache")
public String autoCache() {
double result=Math.random();
System.out.println("进入了"+result);
return result+"";
}
}
- 调用
@Controller
public class HelloController {
@Autowired
ICacheExample iCacheExample;
@RequestMapping(value = "/welcome1") //welcome要访问的url地址
public String hello1(String uname, Model model) {//此时方法参数与传来参数名称一致
System.out.println("hello,springmvc" + uname);
+ model.addAttribute("username", "张三1112" + iCacheExample.autoCache());
return "hello"; //hello是逻辑视图名,和后缀名组合一起构成视图名 /web-inf/jsp/hello.jsp
}
}
-
运行,多次刷新显示一致
image.png
git地址:
https://code.aliyun.com/liyi1314/quicklyCreateSpringMvc.git
cache分支
redis实现
spring mvc官方并没有整合redis
- redis pom.xml
<!-- redis引入,引入版本参考spring boot,引入错误会导致报错 -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.3</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.8.23.RELEASE</version>
</dependency>
- spring-core.xml -----------移除ehcache,引入redis配置
<!-- 缓存 -->
<!-- <bean id="cacheManager"
class="org.springframework.cache.ehcache.EhCacheCacheManager" p:cache-manager-ref="ehcache"/>
<bean id="ehcache"
class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" p:config-location="classpath:config/ehcache.xml"/>-->
<!-- 引入同文件夹下的redis属性配置文件 -->
<import resource="spring-redis.xml"/>
- spring-redis.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:property-placeholder location="classpath:config/redis-config.properties"/>
<!-- redis 相关配置 -->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="${redis.maxIdle}"/>
<property name="maxWaitMillis" value="${redis.maxWait}"/>
<property name="testOnBorrow" value="${redis.testOnBorrow}"/>
</bean>
<bean id="JedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
p:host-name="${redis.host}" p:port="${redis.port}" p:password="${redis.pass}" p:pool-config-ref="poolConfig"/>
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="JedisConnectionFactory"/>
</bean>
<bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
<property name="caches">
<set>
<!--name对应的名称要在类或方法的注解中使用-->
<bean class="com.jc.config.RedisCache">
<property name="redisTemplate" ref="redisTemplate" />
<property name="name" value="javaEpgCache"/>
</bean>
</set>
</property>
</bean>
</beans>
- redis-config.properties
# Redis settings
# server IP,改成自己的
redis.host=47.105.194.139
# server port
redis.port=6379
# server pass
redis.pass=*******
# use dbIndex
redis.database=0
# 控制一个pool最多有多少个状态为idle(空闲的)的jedis实例
redis.maxIdle=300
# 表示当borrow(引入)一个jedis实例时,最大的等待时间,如果超过等待时间(毫秒),则直接抛出JedisConnectionException;
redis.maxWait=3000
# 在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的
redis.testOnBorrow=true
git地址:
https://code.aliyun.com/liyi1314/quicklyCreateSpringMvc.git
cache-redis分支
参考资料:
spring boot
spring mvc @cache+redis 整合
网友评论