关于缓存

关于缓存

缓存是实际工作中非常常用的一种提高性能的方法。而在java中,所谓缓存,就是将程序或系统经常要调用的对象存在内存中,再次调用时可以快速从内存中获取对象,不必再去创建新的重复的实例。这样做可以减少系统开销,提高系统效率。

在增删改查中,数据库查询占据了数据库操作的80%以上,而非常频繁的磁盘I/O读取操作,会导致数据库性能极度低下。而数据库的重要性就不言而喻了:

  • 数据库通常是企业应用系统最核心的部分
  • 数据库保存的数据量通常非常庞大
  • 数据库查询操作通常很频繁,有时还很复杂

在系统架构的不同层级之间,为了加快访问速度,都可以存在缓存


spring cache特性与缺憾

现在市场上主流的缓存框架有ehcache、redis、memcached。spring cache可以通过简单的配置就可以搭配使用起来。其中使用注解方式是最简单的。



Cache注解


从以上的注解中可以看出,虽然使用注解的确方便,但是缺少灵活的缓存策略,

缓存策略:

  • TTL(Time To Live ) 存活期,即从缓存中创建时间点开始直到它到期的一个时间段(不管在这个时间段内有没有访问都将过期)
  • TTI(Time To Idle) 空闲期,即一个数据多久没被访问将从缓存中移除的时间

项目中可能有很多缓存的TTL不相同,这时候就需要编码式使用编写缓存。

条件缓存

根据运行流程,如下@Cacheable将在执行方法之前( #result还拿不到返回值)判断condition,如果返回true,则查缓存;

代码
  1. @Cacheable(value = "user", key = "#id", condition = "#id lt 10")    
  2. public User conditionFindById(final Long id)  


如下@CachePut将在执行完方法后(#result就能拿到返回值了)判断condition,如果返回true,则放入缓存

代码
  1. @CachePut(value = "user", key = "#id", condition = "#result.username ne 'zhang'")    
  2. public User conditionSave(final User user)  


如下@CachePut将在执行完方法后(#result就能拿到返回值了)判断unless,如果返回false,则放入缓存;(即跟condition相反)

代码
  1. @CachePut(value = "user", key = "#user.id", unless = "#result.username eq 'zhang'")    
  2. public User conditionSave2(final User user)  


如下@CacheEvict, beforeInvocation=false表示在方法执行之后调用(#result能拿到返回值了);且判断condition,如果返回true,则移除缓存;

代码
  1. @CacheEvict(value = "user", key = "#user.id", beforeInvocation = false, condition = "#result.username ne 'zhang'")   
  2. public User conditionDelete(final User user)  


小试牛刀,综合运用:

代码
  1. @CachePut(value = "user", key = "#user.id")  
  2.    public User save(User user) {  
  3.        users.add(user);  
  4.        return user;  
  5.    }  
  6.   
  7.    @CachePut(value = "user", key = "#user.id")  
  8.    public User update(User user) {  
  9.        users.remove(user);  
  10.        users.add(user);  
  11.        return user;  
  12.    }  
  13.   
  14.    @CacheEvict(value = "user", key = "#user.id")  
  15.    public User delete(User user) {  
  16.        users.remove(user);  
  17.        return user;  
  18.    }  
  19.   
  20.    @CacheEvict(value = "user", allEntries = true)  
  21.    public void deleteAll() {  
  22.        users.clear();  
  23.    }  
  24.   
  25.    @Cacheable(value = "user", key = "#id")  
  26.    public User findById(final Long id) {  
  27.        System.out.println("cache miss, invoke find by id, id:" + id);  
  28.        for (User user : users) {  
  29.            if (user.getId().equals(id)) {  
  30.                return user;  
  31.            }  
  32.        }  
  33.        return null;  
  34.    }  


配置ehcache与redis
spring cache集成ehcache,spring-ehcache.xml主要内容:

代码
  1. <dependency>  
  2.     <groupId>net.sf.ehcache</groupId>  
  3.     <artifactId>ehcache-core</artifactId>  
  4.     <version>${ehcache.version}</version>  
  5. </dependency>  
代码
  1. <!-- Spring提供的基于的Ehcache实现的缓存管理器 -->  
  2.       
  3. <!-- 如果有多个ehcacheManager要在bean加上p:shared="true" -->  
  4. <bean id="ehcacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">  
  5.      <property name="configLocation" value="classpath:xml/ehcache.xml"/>  
  6. </bean>  
  7.       
  8. <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">  
  9.      <property name="cacheManager" ref="ehcacheManager"/>  
  10.      <property name="transactionAware" value="true"/>  
  11. </bean>  
  12.       
  13. <!-- cache注解,和spring-redis.xml中的只能使用一个 -->  
  14. <cache:annotation-driven cache-manager="cacheManager" proxy-target-class="true"/>  


spring cache集成redis,spring-redis.xml主要内容:

代码
  1. <dependency>  
  2.     <groupId>org.springframework.data</groupId>  
  3.     <artifactId>spring-data-redis</artifactId>  
  4.     <version>1.8.1.RELEASE</version>  
  5. </dependency>  
  6. <dependency>  
  7.     <groupId>org.apache.commons</groupId>  
  8.     <artifactId>commons-pool2</artifactId>  
  9.     <version>2.4.2</version>  
  10. </dependency>  
  11. <dependency>  
  12.     <groupId>redis.clients</groupId>  
  13.     <artifactId>jedis</artifactId>  
  14.     <version>2.9.0</version>  
  15. </dependency>  
代码
  1. <!-- 注意需要添加Spring Data Redis等jar包 -->  
  2. <description>redis配置</description>  
  3.   
  4. <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">  
  5.     <property name="maxIdle" value="${redis.pool.maxIdle}"/>  
  6.     <property name="maxTotal" value="${redis.pool.maxActive}"/>  
  7.     <property name="maxWaitMillis" value="${redis.pool.maxWait}"/>  
  8.     <property name="testOnBorrow" value="${redis.pool.testOnBorrow}"/>  
  9.     <property name="testOnReturn" value="${redis.pool.testOnReturn}"/>  
  10. </bean>  
  11.   
  12. <!-- JedisConnectionFactory -->  
  13. <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">  
  14.     <property name="hostName" value="${redis.master.ip}"/>  
  15.     <property name="port" value="${redis.master.port}"/>  
  16.     <property name="poolConfig" ref="jedisPoolConfig"/>  
  17. </bean>  
  18.   
  19. <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"  
  20.       p:connectionFactory-ref="jedisConnectionFactory">  
  21.     <property name="keySerializer">  
  22.         <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"></bean>  
  23.     </property>  
  24.     <property name="valueSerializer">  
  25.         <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>  
  26.     </property>  
  27.     <property name="hashKeySerializer">  
  28.         <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>  
  29.     </property>  
  30.     <property name="hashValueSerializer">  
  31.         <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>  
  32.     </property>  
  33. </bean>  
  34.   
  35. <!--spring cache-->  
  36. <bean id="cacheManager" class="org.springframework.data.redis.cache.RedisCacheManager"  
  37.       c:redisOperations-ref="redisTemplate">  
  38.     <!-- 默认缓存10分钟 -->  
  39.     <property name="defaultExpiration" value="600"/>  
  40.     <property name="usePrefix" value="true"/>  
  41.     <!-- cacheName 缓存超时配置,半小时,一小时,一天 -->  
  42.     <property name="expires">  
  43.         <map key-type="java.lang.String" value-type="java.lang.Long">  
  44.             <entry key="halfHour" value="1800"/>  
  45.             <entry key="hour" value="3600"/>  
  46.             <entry key="oneDay" value="86400"/>  
  47.             <!-- shiro cache keys -->  
  48.             <entry key="authorizationCache" value="1800"/>  
  49.             <entry key="authenticationCache" value="1800"/>  
  50.             <entry key="activeSessionCache" value="1800"/>  
  51.         </map>  
  52.     </property>  
  53. </bean>  
  54. <!-- cache注解,和spring-ehcache.xml中的只能使用一个 -->  
  55. <cache:annotation-driven cache-manager="cacheManager" proxy-target-class="true"/>  


项目中注解缓存只能配置一个,所以可以通过以下引入哪个配置文件来决定使用哪个缓存。
当然,可以通过其他配置搭配使用两个缓存机制。比如ecache做一级缓存,redis做二级缓存。


更加详细的使用与配置,可以参考项目中spring-shiro-training中有关spring cache的配置。

猜你喜欢

转载自1049097489.iteye.com/blog/2391836
今日推荐