溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

SpringBoot2.0 基礎案例(13):基于Cache注解模式,管理Redis緩存

發布時間:2020-07-12 05:29:03 來源:網絡 閱讀:584 作者:知了一笑 欄目:編程語言
本文源碼
GitHub地址:知了一笑
https://github.com/cicadasmile/spring-boot-base

一、Cache緩存簡介

從Spring3開始定義Cache和CacheManager接口來統一不同的緩存技術;
Cache接口為緩存的組件規范定義,包含緩存的各種操作集合;
Cache接口下Spring提供了各種緩存的實現;
RedisCache,EhCacheCache ,ConcurrentMapCache等;

二、核心API

1、Cache緩存接口
定義緩存操作。實現有:RedisCache、EhCacheCache、ConcurrentMapCache等
2、CacheManager
緩存管理器,管理各種緩存(cache)組件
3、Cacheable 主要針對方法配置,能夠根據方法的請求參數對其進行緩存

Cacheable 執行流程
1)方法運行之前,按照cacheNames指定的名字先去查詢Cache 緩存組件
2)第一次獲取緩存如果沒有Cache組件會自動創建
3)Cache中查找緩存的內容,使用一個key,默認就是方法的參數
4)key是按照某種策略生成的;默認是使用keyGenerator生成的,這里使用自定義配置
5)沒有查到緩存就調用目標方法;
6)將目標方法返回的結果,放進緩存中

Cacheable 注解屬性
cacheNames/value:指定方法返回結果使用的緩存組件的名字,可以指定多個緩存
key:緩存數據使用的key
key/keyGenerator:key的生成器,可以自定義
cacheManager:指定緩存管理器
cacheResolver:指定緩存解析器
condition:指定符合條件的數據才緩存
unless:否定緩存;當unless指定的條件為true,方法的返回值就不會被緩存
sync:是否使用異步模式

4、CacheEvict
清除緩存

CacheEvict:緩存清除
key:指定要清除的數據
allEntries = true:指定清除這個緩存中所有的數據
beforeInvocation = false:方法之前執行清除緩存,出現異常不執行
beforeInvocation = true:代表清除緩存操作是在方法運行之前執行,無論方法是否出現異常,緩存都清除

5、CachePut
保證方法被調用,又希望結果被緩存。
與Cacheable區別在于是否每次都調用方法,常用于更新,寫入

CachePut:執行方法且緩存方法執行的結果
修改了數據庫的某個數據,同時更新緩存;
執行流程
 1)先調用目標方法
 2)然后將目標方法的結果緩存起來

6、EnableCaching
開啟基于注解的緩存
7、keyGenerator
緩存數據時key生成策略
8、CacheConfig
統一配置本類的緩存注解的屬性

三、與SpringBoot2.0整合

1、核心依賴

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

2、Cache緩存配置

import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.lang.reflect.Method;
@Configuration
public class CacheConfig {
    /**
     * 自定義 Cache 的 key 生成器
     */
    @Bean("oneKeyGenerator")
    public KeyGenerator getKeyGenerator (){
        return new KeyGenerator() {
            @Override
            public Object generate(Object obj, Method method, Object... objects) {
                return "KeyGenerator:"+method.getName();
            }
        } ;
    }
}

3、啟動類注解開啟Cache

@EnableCaching            // 開啟Cache 緩存注解
@SpringBootApplication
public class CacheApplication {
    public static void main(String[] args) {
        SpringApplication.run(CacheApplication.class,args) ;
    }
}

4、Cache注解使用代碼

1)封裝增刪改查接口

import com.boot.cache.entity.User;
public interface UserService {
    // 增、改、查、刪
    User addUser (User user) ;
    User updateUser (Integer id) ;
    User selectUser (Integer id) ;
    void deleteUser (Integer id);
}

2)Cache注解使用案例

import com.boot.cache.entity.User;
import com.boot.cache.service.UserService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
    // 使用自定義的key生成策略
    // 緩存結果key:addUser::KeyGenerator:addUser
    @CachePut(value = "addUser",keyGenerator="oneKeyGenerator")
    @Override
    public User addUser(User user) {
        return user ;
    }
    // 緩存結果key:updateUser::2
    @CachePut(value = "updateUser",key = "#result.id")
    @Override
    public User updateUser(Integer id) {
        User user = new User() ;
        user.setId(id);
        user.setName("smile");
        return user;
    }
    // 緩存結果key: selectUser::3
    @Cacheable(cacheNames = "selectUser",key = "#id")
    @Override
    public User selectUser(Integer id) {
        User user = new User() ;
        user.setId(id);
        user.setName("cicadaSmile");
        return user;
    }
    // 刪除指定key: selectUser::3
    @CacheEvict(value = "selectUser",key = "#id",beforeInvocation = true)
    @Override
    public void deleteUser(Integer id) {

    }
}

5、測試代碼塊

@RunWith(SpringJUnit4Cla***unner.class)
@SpringBootTest(classes = CacheApplication.class)
public class CacheTest {
    @Resource
    private UserService userService ;
    // 分別測試:增、改、查、刪,四個方法
    @Test
    public void testAdd (){
        User user = new User() ;
        user.setId(1);
        user.setName("cicada");
        userService.addUser(user) ;
    }
    @Test
    public void testUpdate (){
        userService.updateUser(2) ;
    }
    @Test
    public void testSelect (){
        userService.selectUser(3) ;
    }
    @Test
    public void testDelete (){
        userService.deleteUser(3) ;
    }
}

四、源代碼地址

GitHub地址:知了一笑
https://github.com/cicadasmile/spring-boot-base
碼云地址:知了一笑
https://gitee.com/cicadasmile/spring-boot-base

SpringBoot2.0 基礎案例(13):基于Cache注解模式,管理Redis緩存

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女