springboot2.0以上中使用Cache加redis實現數據緩存

前提;下列配置是基於springboot2.0以上版本實現的,springboot2.0以下版本見下一篇文檔。

首先引入依賴:

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

在application.yml(application.properties配置文件省略)

spring:
  redis:
    host: localhost
    password:
    port: 6379

主方法上加緩存註解:

package cn.cache.testcache;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@EnableCaching
public class TestcacheApplication {

    public static void main(String[] args) {
        SpringApplication.run(TestcacheApplication.class, args);
    }
}

設置緩存的配置文件:

package cn.cache.testcache.shuai;

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;

import java.time.Duration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@Configuration
public class CacheConfig extends CachingConfigurerSupport {

    /**
     * 自定義key.
     * 此方法將會根據類名+方法名+所有參數的值生成唯一的一個key
     */
    @Bean
    @Override
    public KeyGenerator keyGenerator() {
        return (o, method, objects) -> {
            StringBuilder sb = new StringBuilder();
            sb.append(o.getClass().getName());
            sb.append(":");
            sb.append(method.getName());
            for (Object obj : objects) {
                sb.append(":");
                sb.append(obj.toString());
            }
            return sb.toString();
        };
    }


    //緩存管理器
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        // 生成一個默認配置,通過config對象即可對緩存進行自定義配置
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        // 設置緩存的默認過期時間,也是使用Duration設置
//        config = config.entryTtl(Duration.ofMinutes(10))
//                .disableCachingNullValues();     // 不緩存空值

        // 設置一個初始化的緩存空間set集合
        Set<String> cacheNames =  new HashSet<>();
        cacheNames.add("my-redis-cache1");
        cacheNames.add("my-redis-cache2");

        // 對每個緩存空間應用不同的配置
        Map<String, RedisCacheConfiguration> configMap = new HashMap<>();
        // 通過Duration可以自己實現以什麼時間爲單位
        configMap.put("my-redis-cache1", config.entryTtl(Duration.ofMinutes(1)));
        configMap.put("my-redis-cache2", config.entryTtl(Duration.ofSeconds(20)));

        // 使用自定義的緩存配置初始化一個cacheManager
        RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
                .initialCacheNames(cacheNames)  // 注意這兩句的調用順序,一定要先調用該方法設置初始化的緩存名,再初始化相關的配置
                .withInitialCacheConfigurations(configMap)
                .build();
        return cacheManager;
    }
}

service層調用展示:

package cn.cache.testcache.shuai;

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

/**
 * Cacheable註解key需要SpEL表達式書寫
 */
@Service
public class CacheService {
    @Cacheable(value = "my-redis-cache1",key = "#root.methodName")// 生成的redis中的key名爲:"my-redis-cache1::getString"
    public String getString(int id){
        System.out.println("I am from userService,沒有走緩存");
        return "成功";
    }
}

spring Cache提供了一些供我們使用的SpEL上下文數據,下表直接摘自Spring官方文檔:

名稱

位置

描述

示例

methodName

root對象

當前被調用的方法名

#root.methodname

method

root對象

當前被調用的方法

#root.method.name

target

root對象

當前被調用的目標對象實例

#root.target

targetClass

root對象

當前被調用的目標對象的類

#root.targetClass

args

root對象

當前被調用的方法的參數列表

#root.args[0]

caches

root對象

當前方法調用使用的緩存列表

#root.caches[0].name

Argument Name

執行上下文

當前被調用的方法的參數,如findArtisan(Artisan artisan),可以通過#artsian.id獲得參數

#artsian.id

result

執行上下文

方法執行後的返回值(僅當方法執行後的判斷有效,如 unless cacheEvict的beforeInvocation=false)

#result

注意:

1.當我們要使用root對象的屬性作爲key時我們也可以將“#root”省略,因爲Spring默認使用的就是root對象的屬性。 如

1

@Cacheable(key = "targetClass + methodName +#p0")

2.使用方法參數時我們可以直接使用“#參數名”或者“#p參數index”。 如:

1

@Cacheable(value="users", key="#id")

1

@Cacheable(value="users", key="#p0")

SpEL提供了多種運算符

類型

運算符

關係

<,>,<=,>=,==,!=,lt,gt,le,ge,eq,ne

算術

+,- ,* ,/,%,^

邏輯

&&,||,!,and,or,not,between,instanceof

條件

?: (ternary),?: (elvis)

正則表達式

matches

其他類型

?.,?[…],![…],^[…],$[…]

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章