Redis 緩衝 + Spring 的整合樣本(轉載)

來源:互聯網
上載者:User

標籤:開啟   margin   實現   注意事項   redis   載入   相等   user   orm   

1. 依賴包安裝pom.xml 加入:<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> 2. Spring 項目整合進緩衝支援要啟用緩衝支援,我們需要建立一個新的 CacheManager bean。CacheManager 介面有很多實現,本文示範的是和 Redis 的整合,自然就是用 RedisCacheManager 了。Redis 不是應用的共用記憶體,它只是一個記憶體伺服器,就像 MySql 似的,我們需要將應用串連到它並使用某種“語言”進行互動,因此我們還需要一個串連工廠以及一個 Spring 和 Redis 對話要用的 RedisTemplate,這些都是 Redis 緩衝所必需的配置,把它們都放在自訂的 CachingConfigurerSupport 中:
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; @Configuration @EnableCaching public class RedisCacheConfig extends CachingConfigurerSupport { @Bean public JedisConnectionFactory redisConnectionFactory() { JedisConnectionFactory redisConnectionFactory = new JedisConnectionFactory(); 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); cacheManager.setDefaultExpiration(3000); return cacheManager; } }
當然也別忘了把這些 bean 注入 Spring,不然配置無效。在 applicationContext.xml 中加入以下<context:component-scan base-package="com.defonds.bdp.cache.redis" />
3. 緩衝某些方法的執行結果並快取資料一致性保證設定好緩衝配置之後我們就可以使用 @Cacheable 註解來緩衝方法執行的結果了,比如根據省份名檢索城市的 provinceCities 方法和根據 city_code 檢索城市的 searchCity 方法:CRUD (Create 建立,Retrieve 讀取,Update 更新,Delete 刪除) 操作中,除了 R 具備等冪性,其他三個發生的時候都可能會造成緩衝結果和資料庫不一致。為了保證快取資料的一致性,在進行 CUD 操作的時候我們需要對可能影響到的緩衝進行更新或者清除。
// 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); } @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; } 業務考慮,本樣本用的都是 @CacheEvict 清除緩衝。如果你的 CUD 能夠返回 City 執行個體,也可以使用 @CachePut 更新緩衝策略。筆者推薦能用 @CachePut 的地方就不要用 @CacheEvict,因為後者將所有相關方法的緩衝都清理掉,比如上面三個方法中的任意一個被調用了的話,provinceCities 方法的所有緩衝將被清除。
5. 自訂快取資料 key 建置原則對於使用 @Cacheable 註解的方法,每個緩衝的 key 建置原則預設使用的是參數名+參數值,比如以下方法:
@Cacheable("users") public User findByUsername(String username)
這個方法的緩衝將儲存於 key 為 users~keys 的緩衝下,對於 username 取值為 "趙德芳" 的緩衝,key 為 "username-趙德芳"。一般情況下沒啥問題,二般情況如方法 key 取值相等然後參數名也一樣的時候就出問題了,如:
@Cacheable("users") public Integer getLoginCountByUsername(String username)
這個方法的緩衝也將儲存於 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(); } }; }

這對於叢集系統、分布式系統之間共用快取很重要,真正實現了分布式緩衝。
筆者建議:緩衝方法的 @Cacheable 最好使用方法名,避免不同的方法的 @Cacheable 值一致,然後再配以以上緩衝策略。
6. 緩衝的驗證6.1 緩衝的驗證為了確定每個緩衝方法到底有沒有走緩衝,我們開啟了 MyBatis 的 SQL 日誌輸出,並且為了示範清楚,我們還清空了測試用 Redis 資料庫。
先來驗證 provinceCities 方法緩衝,Eclipse 啟動 tomcat 附加元件目完畢,使用 JMeter 調用 /bdp/city/province/cities.json 介面:

Eclipse 控制台輸出如下:

說明這一次請求沒有命中緩衝,走的是 db 查詢。JMeter 再次請求,Eclipse 控制台輸出:

標紅部分以下是這一次請求的 log,沒有訪問 db 的 log,快取命中。查看本次請求的 Redis 儲存情況:

同樣可以驗證 city_code 為 1492 的 searchCity 方法的緩衝是否有效:

圖中標紅部分是 searchCity 的緩衝儲存情況。
6.2 緩衝一致性的驗證先來驗證 insertCity 方法的緩衝配置,JMeter 調用 /bdp/city/create.json 介面:

之後看 Redis 儲存:

可以看出 provinceCities 方法的緩衝已被清理掉,insertCity 方法的緩衝奏效。
然後驗證 renameCity 方法的緩衝配置,JMeter 調用 /bdp/city/rename.json 介面:

之後再看 Redis 儲存:

searchCity 方法的緩衝也已被清理,renameCity 方法的緩衝也奏效。
7. 注意事項
  1. 要緩衝的 Java 對象必須實現 Serializable 介面,因為 Spring 會將對象先序列化再存入 Redis,比如本文中的 com.defonds.bdp.city.bean.City 類,如果不實現 Serializable 的話將會遇到類似這種錯誤:nested exception is java.lang.IllegalArgumentException: DefaultSerializer requires a Serializable payload but received an object of type [com.defonds.bdp.city.bean.City]]。
  2. 緩衝的生命週期我們可以配置,然後託管 Spring CacheManager,不要試圖通過 redis-cli 命令列去管理緩衝。比如 provinceCities 方法的緩衝,某個省份的查詢結果會被以 key-value 的形式存放在 Redis,key 就是我們剛才自訂產生的 key,value 是序列化後的對象,這個 key 會被放在 key 名為 provinceCities~keys key-value 儲存中,參考"provinceCities 方法在 Redis 中的緩衝情況"。可以通過 redis-cli 使用 del 命令將 provinceCities~keys 刪除,但每個省份的緩衝卻不會被清除。
  3. CacheManager 必須設定緩衝到期時間,否則緩衝對象將永不到期,這樣做的原因如上,避免一些野資料“永久儲存”。此外,設定緩衝到期時間也有助於資源利用最大化,因為緩衝裡保留的永遠是熱點資料。
  4. 緩衝適用於讀多寫少的場合,查詢時快取命中率很低、寫操作很頻繁等情境不適宜用緩衝。

Redis 緩衝 + Spring 的整合樣本(轉載)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.