隨着時間的積累,應用的使用用戶不斷增加,數據規模也越來越大,往往數據庫查詢操作會成為影響用戶使用體驗的瓶頸,此時使用緩存往往是解決這一問題非常好的手段之一。
原始的使用緩存的方式如下:這樣的緩存使用方式將數據讀取后,主動對緩存進行更新操作,這樣的方式使用方便,但是代碼的耦合性高,代碼侵入性強。
1 /** 2 * 使用緩存以id為字樣,如果id所對應的緩存信息已經存在,則不會再讀db 3 * @param id 4 * @return 5 */ 6 public UserInfo getUserInfoById(int id){ 7 UserInfo userInfo = (UserInfo) redisTemplate.opsForValue().get(id+""); 8 if(userInfo != null){ 9 return userInfo; 10 } 11 System.out.println("若下面沒出現“無緩存的時候調用”字樣且能打印出數據表示測試成功"); 12 UserInfo userInfo1 = userInfoDao.findById(id); 13 ValueOperations<String, UserInfo> valueOperations = redisTemplate.opsForValue(); 14 valueOperations.set(id+"", userInfo1); 15 return userInfo1; 16 } 17 18 @Transactional 19 public int saveUserInfo(UserInfo userInfo){ 20 //更新緩存 21 userInfoDao.saveUserInfo(userInfo); 22 int id = userInfo.getId(); 23 //userInfo 里面的id值已經發生了變化 24 System.out.println(userInfo.getId()); 25 ValueOperations<String, UserInfo> valueOperations = redisTemplate.opsForValue(); 26 valueOperations.set(id+"", userInfo); 27 redisTemplate.opsForValue().set(id+"", userInfo); 28 return id; 29 }
Spring 3開始提供了強大的基於注解的緩存支持,可以通過注解配置方式低侵入的給原有Spring應用增加緩存功能,提高數據訪問性能。
在Spring Boot中對於緩存的支持,提供了一系列的自動化配置,使我們可以非常方便的使用緩存。下面我們通過一個簡單的例子來展示,我們是如何給一個既有應用增加緩存功能的。
引入緩存
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
在application.preoperties中定義redis的配置
# REDIS (RedisProperties) # Redis數據庫索引(默認為0) spring.redis.database=0 # Redis服務器地址 spring.redis.host=127.0.0.1 # Redis服務器連接端口 spring.redis.port=6379 # Redis服務器連接密碼(默認為空) spring.redis.password= # 連接池最大連接數(使用負值表示沒有限制) spring.redis.pool.max-active=8 # 連接池最大阻塞等待時間(使用負值表示沒有限制) spring.redis.pool.max-wait=-1 # 連接池中的最大空閑連接 spring.redis.pool.max-idle=8 # 連接池中的最小空閑連接 spring.redis.pool.min-idle=0 # 連接超時時間(毫秒) spring.redis.timeout=0
自定義緩存,本文使用redis作為緩存,自定義緩存配置,繼承CachingConfigurerSupport類
1 /** 2 * 自定義緩存配置文件,繼承 CachingConfigurerSupport 3 * Created by huanl on 2017/8/22. 4 */ 5 @Configuration 6 @EnableCaching 7 public class RedisConfig extends CachingConfigurerSupport{ 8 public RedisConfig() { 9 super(); 10 } 11 12 /** 13 * 指定使用哪一種緩存 14 * @param redisTemplate 15 * @return 16 */ 17 @Bean 18 public CacheManager cacheManager(RedisTemplate<?,?> redisTemplate) { 19 RedisCacheManager rcm = new RedisCacheManager(redisTemplate); 20 return rcm; 21 } 22 23 /** 24 * 指定默認的key生成方式 25 * @return 26 */ 27 @Override 28 public KeyGenerator keyGenerator() { 29 KeyGenerator keyGenerator = new KeyGenerator() { 30 @Override 31 public Object generate(Object o, Method method, Object... objects) { 32 StringBuilder sb = new StringBuilder(); 33 sb.append(o.getClass().getName()); 34 sb.append(method.getName()); 35 for (Object obj : objects) { 36 sb.append(obj.toString()); 37 } 38 return sb.toString(); 39 } 40 }; 41 return keyGenerator; 42 } 43 44 @Override 45 public CacheResolver cacheResolver() { 46 return super.cacheResolver(); 47 } 48 49 @Override 50 public CacheErrorHandler errorHandler() { 51 return super.errorHandler(); 52 } 53 54 /** 55 * redis 序列化策略 ,通常情況下key值采用String序列化策略 56 * StringRedisTemplate默認采用的是String的序列化策略,保存的key和value都是采用此策略序列化保存的。StringRedisSerializer 57 * RedisTemplate默認采用的是JDK的序列化策略,保存的key和value都是采用此策略序列化保存的。JdkSerializationRedisSerializer 58 * @param factory 59 * @return 60 */ 61 @Bean 62 public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory factory){ 63 RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>(); 64 redisTemplate.setConnectionFactory(factory); 65 66 // // 使用Jackson2JsonRedisSerialize 替換默認序列化 67 // Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); 68 // ObjectMapper om = new ObjectMapper(); 69 // om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); 70 // om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); 71 // jackson2JsonRedisSerializer.setObjectMapper(om); 72 // 73 // 74 // //設置value的序列化方式 75 // redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); 76 // //設置key的序列化方式 77 // redisTemplate.setKeySerializer(new StringRedisSerializer()); 78 // redisTemplate.setHashKeySerializer(new StringRedisSerializer()); 79 // redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer); 80 81 //使用fastJson作為默認的序列化方式 82 GenericFastJsonRedisSerializer genericFastJsonRedisSerializer = new GenericFastJsonRedisSerializer(); 83 redisTemplate.setDefaultSerializer(genericFastJsonRedisSerializer); 84 redisTemplate.setValueSerializer(genericFastJsonRedisSerializer); 85 redisTemplate.setKeySerializer(new StringRedisSerializer()); 86 redisTemplate.setHashValueSerializer(genericFastJsonRedisSerializer); 87 redisTemplate.setHashKeySerializer(new StringRedisSerializer()); 88 redisTemplate.afterPropertiesSet(); 89 90 return redisTemplate; 91 92 } 93 94 /** 95 * 轉換返回的object為json 96 * @return 97 */ 98 @Bean 99 public HttpMessageConverters fastJsonHttpMessageConverters(){ 100 // 1、需要先定義一個converter 轉換器 101 FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter(); 102 // 2、添加fastJson 的配置信息,比如:是否要格式化返回的json數據 103 FastJsonConfig fastJsonConfig = new FastJsonConfig(); 104 fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat); 105 // 3、在convert 中添加配置信息 106 fastConverter.setFastJsonConfig(fastJsonConfig); 107 // 4、將convert 添加到converters當中 108 HttpMessageConverter<?> converter = fastConverter; 109 return new HttpMessageConverters(converter); 110 } 111 112 113 }
在Spring Boot主類中增加@EnableCaching注解開啟緩存功能
1 @SpringBootApplication 2 @Import(RedisConfig.class) 3 @MapperScan("com.redistest.dao") 4 @EnableCaching 5 public class RedisApplication { 6 7 public static void main(String[] args) { 8 SpringApplication.run(RedisApplication.class, args); 9 } 10 }
在Service類中使用緩存
@Service public class UserInfoService { @Autowired private UserInfoDao userInfoDao; @Autowired private RedisTemplate redisTemplate; /** * 優先從緩存中獲取數據,如果緩存中不存在,則從db中讀取,讀取后將結果按照key存入緩存 * @param id * @return */ @Cacheable(value = "user", key="#id + 'findById'") public UserInfo getUserInfoByIDNew(int id){ return userInfoDao.findById(id); } /** * 使用緩存以id為字樣,如果id所對應的緩存信息已經存在,則不會再讀db * @param id * @return */ public UserInfo getUserInfoById(int id){ UserInfo userInfo = (UserInfo) redisTemplate.opsForValue().get(id+""); if(userInfo != null){ return userInfo; } System.out.println("若下面沒出現“無緩存的時候調用”字樣且能打印出數據表示測試成功"); UserInfo userInfo1 = userInfoDao.findById(id); ValueOperations<String, UserInfo> valueOperations = redisTemplate.opsForValue(); valueOperations.set(id+"", userInfo1); return userInfo1; } @Transactional public int saveUserInfo(UserInfo userInfo){ //更新緩存 userInfoDao.saveUserInfo(userInfo); int id = userInfo.getId(); //userInfo 里面的id值已經發生了變化 System.out.println(userInfo.getId()); ValueOperations<String, UserInfo> valueOperations = redisTemplate.opsForValue(); valueOperations.set(id+"", userInfo); redisTemplate.opsForValue().set(id+"", userInfo); return id; } /** * * @param userInfo * @return */ @Transactional //更新后刪除指定值的緩存,獲取值得時候默認從db中獲取 //@CacheEvict(value = "user", key="#userInfo.id+'findById'") //配置於函數上,能夠根據參數定義條件來進行緩存,它與@Cacheable不同的是,它每次都會真是調用函數,所以主要用於數據新增和修改操作上。它的參數與@Cacheable類似,具體功能可參考上面對@Cacheable參數的解析 @CachePut(value = "user", key = "#userInfo.id+'findById'") public UserInfo updateUserInfo(UserInfo userInfo){ userInfoDao.updateUserInfo(userInfo); int id = userInfo.getId(); redisTemplate.opsForValue().set(id+"", userInfo); return userInfo; } }
使用的MybatisDao
@Mapper @Component public interface UserInfoDao { @Select(value = "select * from t_t_user where id=#{id}") public UserInfo findById(int id); public int saveUserInfo(UserInfo userInfo); public int updateUserInfo(UserInfo userInfo); }
mapper文件,在application.properties文件中定義mapper文件的位置
mybatis.mapper-locations=mapper.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!--命名空間:分類管理sql隔離,方便管理--> <mapper namespace="com.redistest.dao.UserInfoDao"> <!--插入--> <insert id="saveUserInfo" useGeneratedKeys="true" keyProperty="id" keyColumn="id" parameterType="com.redistest.domain.UserInfo"> INSERT INTO t_t_user (name, password, salt, role) VALUES (#{name}, #{password}, #{salt}, #{role}) </insert> <!--更新--> <update id="updateUserInfo" parameterType="com.redistest.domain.UserInfo"> UPDATE t_t_user set name=#{name}, password=#{password}, salt=#{salt}, role=#{role} where id=#{id} </update> </mapper>
Cache注解詳解
回過頭來我們再來看,這里使用到的兩個注解分別作了什么事情。
-
@CacheConfig:主要用於配置該類中會用到的一些共用的緩存配置。在這里@CacheConfig(cacheNames = "users"):配置了該數據訪問對象中返回的內容將存儲於名為users的緩存對象中,我們也可以不使用該注解,直接通過@Cacheable自己配置緩存集的名字來定義。 -
@Cacheable:配置了findByName函數的返回值將被加入緩存。同時在查詢時,會先從緩存中獲取,若不存在才再發起對數據庫的訪問。該注解主要有下面幾個參數:value、cacheNames:兩個等同的參數(cacheNames為Spring 4新增,作為value的別名),用於指定緩存存儲的集合名。由於Spring 4中新增了@CacheConfig,因此在Spring 3中原本必須有的value屬性,也成為非必需項了key:緩存對象存儲在Map集合中的key值,非必需,缺省按照函數的所有參數組合作為key值,若自己配置需使用SpEL表達式,比如:@Cacheable(key = "#p0"):使用函數第一個參數作為緩存的key值,更多關於SpEL表達式的詳細內容可參考官方文檔condition:緩存對象的條件,非必需,也需使用SpEL表達式,只有滿足表達式條件的內容才會被緩存,比如:@Cacheable(key = "#p0", condition = "#p0.length() < 3"),表示只有當第一個參數的長度小於3的時候才會被緩存,若做此配置上面的AAA用戶就不會被緩存,讀者可自行實驗嘗試。unless:另外一個緩存條件參數,非必需,需使用SpEL表達式。它不同於condition參數的地方在於它的判斷時機,該條件是在函數被調用之后才做判斷的,所以它可以通過對result進行判斷。keyGenerator:用於指定key生成器,非必需。若需要指定一個自定義的key生成器,我們需要去實現org.springframework.cache.interceptor.KeyGenerator接口,並使用該參數來指定。需要注意的是:該參數與key是互斥的cacheManager:用於指定使用哪個緩存管理器,非必需。只有當有多個時才需要使用cacheResolver:用於指定使用那個緩存解析器,非必需。需通過org.springframework.cache.interceptor.CacheResolver接口來實現自己的緩存解析器,並用該參數指定。
除了這里用到的兩個注解之外,還有下面幾個核心注解:
@CachePut:配置於函數上,能夠根據參數定義條件來進行緩存,它與@Cacheable不同的是,它每次都會真是調用函數,所以主要用於數據新增和修改操作上。它的參數與@Cacheable類似,具體功能可參考上面對@Cacheable參數的解析@CacheEvict:配置於函數上,通常用在刪除方法上,用來從緩存中移除相應數據。除了同@Cacheable一樣的參數之外,它還有下面兩個參數:allEntries:非必需,默認為false。當為true時,會移除所有數據beforeInvocation:非必需,默認為false,會在調用方法之后移除數據。當為true時,會在調用方法之前移除數據。
緩存配置
完成了上面的緩存實驗之后,可能大家會問,那我們在Spring Boot中到底使用了什么緩存呢?
在Spring Boot中通過@EnableCaching注解自動化配置合適的緩存管理器(CacheManager),Spring Boot根據下面的順序去偵測緩存提供者:
- Generic
- JCache (JSR-107)
- EhCache 2.x
- Hazelcast
- Infinispan
- Redis
- Guava
- Simple
除了按順序偵測外,我們也可以通過配置屬性spring.cache.type來強制指定。我們可以通過debug調試查看cacheManager對象的實例來判斷當前使用了什么緩存。
本文中不對所有的緩存做詳細介紹,下面以常用的EhCache為例,看看如何配置來使用EhCache進行緩存管理。
在Spring Boot中開啟EhCache非常簡單,只需要在工程中加入ehcache.xml配置文件並在pom.xml中增加ehcache依賴,框架只要發現該文件,就會創建EhCache的緩存管理器。
- 在
src/main/resources目錄下創建:ehcache.xml
|
1
2
3
4
5
6
7
8
9
|
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd">
<cache name="users"
maxEntriesLocalHeap="200"
timeToLiveSeconds="600">
</cache>
</ehcache>
|
- 在
pom.xml中加入
|
1
2
3
4
|
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
|
完成上面的配置之后,再通過debug模式運行單元測試,觀察此時CacheManager已經是EhCacheManager實例,說明EhCache開啟成功了。
對於EhCache的配置文件也可以通過application.properties文件中使用spring.cache.ehcache.config屬性來指定,比如:
|
1
|
spring.cache.ehcache.config=classpath:config/another-config.xml
|
