Spring 緩存框架

緩存是讓數據更接近于使用者;工作機制是先從緩存中讀取數據,如果沒有再從慢速設備上讀取實際數據(數據也會存入緩存);緩存的是那些經常讀取且不經常修改的數據/那些昂貴(CPU/IO)的且對于相同的請求有相同的計算結果的數據。

先介紹幾個重要概念:

  • 緩存命中率: 從緩存中讀取次數 / 總讀取次數,這是衡量緩存效率的核心指標
  • 緩存清理策略: FIFO、LRU、LFU
  • TTL:存活期,即從緩存中創建時間點開始直到它到期的一個時間段
  • TTI:空閑期,即一個數據多久沒被訪問將從緩存中移除的時間。

自 Spring 3.1 起,提供了 Cache 抽象和基于注解的 Cache 支持,帶來如下好處:

  • 提供基本的 Cache 抽象,方便切換各種底層 Cache;
  • 通過注解 Cache 可以實現類似于事務一樣,緩存邏輯透明的應用到我們的業務代碼上,且只需要更少的代碼就可以完成;
  • 提供事務回滾時也自動回滾緩存;
  • 支持比較復雜的緩存邏輯。

快速上手

github 代碼地址

一、Maven 配置

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
          http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.bigcrab.spring</groupId>
    <artifactId>cache-demo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <springframework.version>4.3.6.RELEASE</springframework.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${springframework.version}</version>
        </dependency>
    </dependencies>

</project>

二、Spring 的 applicationContext.xml 配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
       http://www.springframework.org/schema/beans/spring-beans.xsd 
       http://www.springframework.org/schema/context 
       http://www.springframework.org/schema/context/spring-context.xsd">

       <context:component-scan base-package="com.bigcrab.spring.cache"/>

</beans>

三、最簡單的緩存代碼配置

package com.bigcrab.spring.cache;

import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurer;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.cache.interceptor.CacheErrorHandler;
import org.springframework.cache.interceptor.CacheResolver;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.stream.Collectors;


/**
 * Created by luantao on 2017/3/6.
 */
@Configuration
@EnableCaching(proxyTargetClass = true)
public class AppConfig implements CachingConfigurer {

    private CacheManager cacheManager;

    @PostConstruct
    public void init() {
        cacheManager = new ConcurrentMapCacheManager();
    }

    @Override
    public CacheManager cacheManager() {
        return null;
    }

    @Override
    public CacheResolver cacheResolver() {
        return context -> context.getOperation().getCacheNames()
                .stream()
                .map(cacheManager::getCache)
                .collect(Collectors.toList());
    }

    @Override
    public KeyGenerator keyGenerator() {
        return null;
    }

    @Override
    public CacheErrorHandler errorHandler() {
        return null;
    }

}

四、User 數據定義

package com.bigcrab.spring.cache;

/**
 * Created by luantao on 2017/3/6.
 */
public class User {

    private Long id;

    private String name;

    public User(Long id, String name) {
        this.id = id;
        this.name = name;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

五、User 管理服務實現

package com.bigcrab.spring.cache;

import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by luantao on 2017/3/6.
 */
@Service
public class UserService {

    private Map<Long, User> users = new ConcurrentHashMap<>();

    public User addUser(User user) {
        users.put(user.getId(), user);
        return user;
    }

    @Cacheable(value = "user", key = "#id")
    public User getUser(Long id) {
        System.out.println("get user in user service");
        return users.get(id);
    }

}

六、測試邏輯

package com.bigcrab.spring.cache;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created by luantao on 2017/3/6.
 */
@Component
public class UserClient {

    @Autowired
    private UserService userService;


    public void run() {
        addUsers();
        getUsers();
    }

    private void addUsers() {
        for (long i = 0; i < 100; ++i) {
            String name = String.format("user_%d", i);
            userService.addUser(new User(i, name));
        }
    }

    private void getUsers() {
        getUser(1L);
        getUser(20L);
        getUser(101L);
        getUser(1L);
        getUser(20L);
        getUser(101L);
    }

    private void getUser(long id) {
        System.out.println("=== start getting user who's id is " + id + " ===");
        User user = userService.getUser(id);
        String log = String.format("user id = %d, user name = %s", id, user != null ? user.getName() : null);
        System.out.println(log);
    }

}

七、主函數

package com.bigcrab.spring.cache;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Created by luantao on 2017/3/6.
 */
public class Main {

    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserClient client = ctx.getBean(UserClient.class);
        client.run();
    }

}

八、測試結果

=== start getting user who's id is 1 ===
get user in user service
user id = 1, user name = user_1
=== start getting user who's id is 20 ===
get user in user service
user id = 20, user name = user_20
=== start getting user who's id is 101 ===
get user in user service
user id = 101, user name = null
=== start getting user who's id is 1 ===
user id = 1, user name = user_1
=== start getting user who's id is 20 ===
user id = 20, user name = user_20
=== start getting user who's id is 101 ===
user id = 101, user name = null

條件緩存

Srping Cache 框架允許通過 condition 或者 unless 字段增加一些緩存控制策略。

  • @Cacheable 將在執行方法之前(#result還拿不到返回值)判斷 condition,如果返回 true,則查緩存:
@Cacheable(value = "user", key = "#id", condition = "#id lt 10")  
public User conditionFindById(final Long id)  
  • @CachePut 將在執行完方法后(#result就能拿到返回值了)判斷 condition,如果返回 true,則放入緩存:
@CachePut(value = "user", key = "#id", condition = "#result.name ne 'foo'")  
public User conditionSave(final User user)   
  • @CachePut 將在執行完方法后(#result就能拿到返回值了)判斷 unless,如果返回 false,則放入緩存:
@CachePut(value = "user", key = "#user.id", unless = "#result.name eq 'foo'")  
public User conditionSave(final User user)   
  • @CacheEvict, beforeInvocation=false表示在方法執行之后調用(#result能拿到返回值了);且判斷condition,如果返回true,則移除緩存:
@CacheEvict(value = "user", key = "#user.id", beforeInvocation = false, condition = "#result.name ne 'foo'")  
public User conditionDelete(final User user)   

組合注解

可以使用 @Caching 把多個緩存注解組合在一起,如下:

@Caching(
            put = {
                    @CachePut(value = "user", key = "#user.id"),
                    @CachePut(value = "user_name", key = "#user.name")
            }
    )
    public User addUser(User user) {
        users.put(user.getId(), user);
        return user;
    }

也可以自己定義一個注解,這樣使用的地方就會簡潔很多:

@Caching(
        put = {
                @CachePut(value = "user", key = "#user.id"),
                @CachePut(value = "user_name", key = "#user.name")
        }
)
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface CacheUser {
}

addUser 就改為:

@CacheUser
    public User addUser(User user) {
        users.put(user.getId(), user);
        return user;
    }
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,973評論 19 139
  • 1. Java基礎部分 基礎部分的順序:基本語法,類相關的語法,內部類的語法,繼承相關的語法,異常的語法,線程的語...
    子非魚_t_閱讀 31,767評論 18 399
  • 1. 簡介 1.1 什么是 MyBatis ? MyBatis 是支持定制化 SQL、存儲過程以及高級映射的優秀的...
    笨鳥慢飛閱讀 5,657評論 0 4
  • Spring Boot 參考指南 介紹 轉載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 46,970評論 6 342
  • 1 緩存介紹# MyBatis支持聲明式數據緩存(declarative data caching)。當一條SQL...
    七寸知架構閱讀 2,173評論 2 51