【Spring】Redis的兩個典型應用場景--good


 

Redis簡介

Redis是目前業界使用最廣泛的內存數據存儲。相比memcached,Redis支持更豐富的數據結構,例如hashes, lists, sets等,同時支持數據持久化。除此之外,Redis還提供一些類數據庫的特性,比如事務,HA,主從庫。可以說Redis兼具了緩存系統和數據庫的一些特性,因此有着豐富的應用場景。本文介紹Redis在Spring Boot中兩個典型的應用場景。

場景1:數據緩存

第一個應用場景是數據緩存,最典型的當屬緩存數據庫查詢結果。對於高頻讀低頻寫的數據,使用緩存可以第一,加速讀取過程,第二,降低數據庫壓力。通過引入spring-boot-starter-redis依賴和注冊RedisCacheManager,Redis可以無縫的集成進Spring的緩存系統,自動綁定@Cacheable, @CacheEvict等緩存注解。

引入依賴:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-redis</artifactId>
</dependency>

Redis配置(application.properties):

# REDIS (RedisProperties)
spring.redis.host=localhost
spring.redis.password=
spring.redis.database=0

注冊RedisCacheManager:

@Configuration
@EnableCaching
public class CacheConfig {

    @Autowired
    private JedisConnectionFactory jedisConnectionFactory;

    @Bean
    public RedisCacheManager cacheManager() {
        RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate());
        return redisCacheManager;
    }

    @Bean
    public RedisTemplate<Object, Object> redisTemplate() {
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<Object, Object>();
        redisTemplate.setConnectionFactory(jedisConnectionFactory);
        // 使用String格式序列化緩存鍵
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        return redisTemplate;
    }

}

@Cachable, @CacheEvict使用,Redis中的存儲結構可參見場景2中的配圖:

@Cacheable(value="signonCache", key="'petstore:signon:'+#username", unless="#result==null")
public Signon findByName(String username) {
    return dao.fetchOneByUsername(username);
}

@CacheEvict(value="signonCache", key="'petstore:signon:'+#user.username")
public void update(Signon user) {
    dao.update(user);
}
  • @Cacheable: 插入緩存
    • value: 緩存名稱
    • key: 緩存鍵,一般包含被緩存對象的主鍵,支持Spring EL表達式
    • unless: 只有當查詢結果不為空時,才放入緩存
  • @CacheEvict: 失效緩存

Tip: Spring Redis默認使用JDK進行序列化和反序列化,因此被緩存對象需要實現java.io.Serializable接口,否則緩存出錯。

Tip: 當被緩存對象發生改變時,可以選擇更新緩存或者失效緩存,但一般而言,后者優於前者,因為執行速度更快。

Watchout! 在同一個Class內部調用帶有緩存注解的方法,緩存並不會生效。

場景2:共享Session

共享Session是第二個典型應用場景,這是利用了Redis的堆外內存特性。要保證分布式應用的可伸縮性,帶狀態的Session對象是繞不過去的一道坎。
一種方式是將Session持久化到數據庫中,缺點是讀寫成本太高
另一種方式是去Session化,比如Play直接將Session存到客戶端的Cookie中,缺點是存儲信息的大小受限。將Session緩存到Redis中,既保證了可伸縮性,同時又避免了前面兩者的限制。

引入依賴:

<dependency>
    <groupId>org.springframework.session</groupId>
    <artifactId>spring-session-data-redis</artifactId>
</dependency>

Session配置:

@Configuration
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 86400)
public class SessionConfig {
}
  • maxInactiveIntervalInSeconds: 設置Session失效時間,使用Redis Session之后,原Boot的server.session.timeout屬性不再生效

Redis中的session對象:

小結

上面結合示例代碼介紹了數據緩存,共享Session兩個Redis的典型應用場景,除此之外,還有分布式鎖,全局計數器等高級應用場景,以后在其他文章中再詳細介紹。

參考

http://emacoo.cn/blog/spring-redis

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM