《整合 spring 4(包括mvc、context、orm) + mybatis 3 示例》一文简要介绍了最新版本的 Spring MVC、IOC、MyBatis ORM 三者的整合以及声明式事务处理。现在我们需要把缓存也整合进来,缓存我们选用的是 Redis,本文将在该文示例基础上介绍 Redis 缓存 + Spring 的集成。
1. 依赖包安装
pom.xml 加入:
<!-- redis cache related.....start --> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>1.6.0.RELEASE</version> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.7.3</version> </dependency> <!-- redis cache related.....end --></div>
2. Spring 项目集成进缓存支持
要启用缓存支持,我们需要创建一个新的 CacheManager bean。CacheManager 接口有很多实现,本文演示的是和 Redis 的集成,自然就是用 RedisCacheManager 了。Redis 不是应用的共享内存,它只是一个内存服务器,就像 MySql 似的,我们需要将应用连接到它并使用某种“语言”进行交互,因此我们还需要一个连接工厂以及一个 Spring 和 Redis 对话要用的 RedisTemplate,这些都是 Redis 缓存所必需的配置,把它们都放在自定义的 CachingConfigurerSupport 中:
/** * File Name:RedisCacheConfig.java * * Copyright Defonds Corporation 2015 * All Rights Reserved * */ package com.defonds.bdp.cache.redis; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.CachingConfigurerSupport; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; /** * * Project Name:bdp * Type Name:RedisCacheConfig * Type Description: * Author:Defonds * Create Date:2015-09-21 * * @version * */ @Configuration @EnableCaching public class RedisCacheConfig extends CachingConfigurerSupport { @Bean public JedisConnectionFactory redisConnectionFactory() { JedisConnectionFactory redisConnectionFactory = new JedisConnectionFactory(); // Defaults redisConnectionFactory.setHostName("192.168.1.166"); redisConnectionFactory.setPort(6379); return redisConnectionFactory; } @Bean public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory cf) { RedisTemplate<String, String> redisTemplate = new RedisTemplate<String, String>(); redisTemplate.setConnectionFactory(cf); return redisTemplate; } @Bean public CacheManager cacheManager(RedisTemplate redisTemplate) { RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate); // Number of seconds before expiration. Defaults to unlimited (0) cacheManager.setDefaultExpiration(3000); // Sets the default expire time (in seconds) return cacheManager; } }</div>
当然也别忘了把这些 bean 注入 Spring,不然配置无效。在 applicationContext.xml 中加入以下:
<context:component-scan base-package="com.defonds.bdp.cache.redis" /></div>
3. 缓存某些方法的执行结果
设置好缓存配置之后我们就可以使用 @Cacheable 注解来缓存方法执行的结果了,比如根据省份名检索城市的 provinceCities 方法和根据 city_code 检索城市的 searchCity 方法:
// R @Cacheable("provinceCities") public List<City> provinceCities(String province) { logger.debug("province=" + province); return this.cityMapper.provinceCities(province); } // R @Cacheable("searchCity") public City searchCity(String city_code){ logger.debug("city_code=" + city_code); return this.cityMapper.searchCity(city_code); }</div>
4. 缓存数据一致性保证
CRUD (Create 创建,Retrieve 读取,Update 更新,Delete 删除) 操作中,除了 R 具备幂等性,其他三个发生的时候都可能会造成缓存结果和数据库不一致。为了保证缓存数据的一致性,在进行 CUD 操作的时候我们需要对可能影响到的缓存进行更新或者清除。
// C @CacheEvict(value = { "provinceCities"}, allEntries = true) public void insertCity(String city_code, String city_jb, String province_code, String city_name, String city, String province) { City cityBean = new City(); cityBean.setCityCode(city_code); cityBean.setCityJb(city_jb); cityBean.setProvinceCode(province_code); cityBean.setCityName(city_name); cityBean.setCity(city); cityBean.setProvince(province); this.cityMapper.insertCity(cityBean); } // U @CacheEvict(value = { "provinceCities", "searchCity" }, allEntries = true) public int renameCity(String city_code, String city_name) { City city = new City(); city.setCityCode(city_code); city.setCityName(city_name); this.cityMapper.renameCity(city); return 1; } // D @CacheEvict(value = { "provinceCities", "searchCity" }, allEntries = true) public int deleteCity(String city_code) { this.cityMapper.deleteCity(city_code); return 1; }</div>
业务考虑,本示例用的都是 @CacheEvict 清除缓存。如果你的 CUD 能够返回 City 实例,也可以使用 @CachePut 更新缓存策略。笔者推荐能用 @CachePut 的地方就不要用 @CacheEvict,因为后者将所有相关方法的缓存都清理掉,比如上面三个方法中的任意一个被调用了的话,provinceCities 方法的所有缓存将被清除。
5. 自定义缓存数据 key 生成策略
对于使用 @Cacheable 注解的方法,每个缓存的 key 生成策略默认使用的是参数名+参数值,比如以下方法:
@Cacheable("users") public User findByUsername(String username)</div>
这个方法的缓存将保存于 key 为 users~keys 的缓存下,对于 username 取值为 "赵德芳" 的缓存,key 为 "username-赵德芳"。一般情况下没啥问题,二般情况如方法 key 取值相等然后参数名也一样的时候就出问题了,如:
@Cacheable("users") public Integer getLoginCountByUsername(String username)</div>
这个方法的缓存也将保存于 key 为 users~keys 的缓存下。对于 username 取值为 "赵德芳" 的缓存,key 也为 "username-赵德芳",将另外一个方法的缓存覆盖掉。
解决办法是使用自定义缓存策略,对于同一业务(同一业务逻辑处理的方法,哪怕是集群/分布式系统),生成的 key 始终一致,对于不同业务则不一致:
@Bean public KeyGenerator customKeyGenerator() { return new KeyGenerator() { @Override public Object generate(Object o, Method method, Object... objects) { StringBuilder sb = new StringBuilder(); sb.append(o.getClass().getName()); sb.append(method.getName()); for (Object obj : objects) { sb.append(obj.toString()); } return sb.toString(); } }; }</div>
于是上述两个方法,对于 username 取值为 "赵德芳" 的缓存,虽然都还是存放在 key 为 users~keys 的缓存下,但由于 key 分别为 "类