Spring Boot 基于注解的 Redis 緩存使用詳解
看文本之前,請(qǐng)先確定你看過上一篇文章《Spring Boot Redis 集成配置》并保證 Redis 集成后正??捎茫?yàn)楸疚氖腔谏衔睦^續(xù)增加的代碼。
一、創(chuàng)建 Caching 配置類
RedisKeys.Java
package com.shanhy.example.redis;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.PostConstruct;
import org.springframework.stereotype.Component;
/**
* 方法緩存key常量
*
* @author SHANHY
*/
@Component
public class RedisKeys {
// 測(cè)試 begin
public static final String _CACHE_TEST = "_cache_test";// 緩存key
public static final Long _CACHE_TEST_SECOND = 20L;// 緩存時(shí)間
// 測(cè)試 end
// 根據(jù)key設(shè)定具體的緩存時(shí)間
private Map<String, Long> expiresMap = null;
@PostConstruct
public void init(){
expiresMap = new HashMap<>();
expiresMap.put(_CACHE_TEST, _CACHE_TEST_SECOND);
}
public Map<String, Long> getExpiresMap(){
return this.expiresMap;
}
}
CachingConfig.java
package com.shanhy.example.redis;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.cache.interceptor.SimpleKeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.core.RedisTemplate;
/**
* 注解式環(huán)境管理
*
* @author 單紅宇(CSDN catoop)
* @create 2016年9月12日
*/
@Configuration
@EnableCaching
public class CachingConfig extends CachingConfigurerSupport {
/**
* 在使用@Cacheable時(shí),如果不指定key,則使用找個(gè)默認(rèn)的key生成器生成的key
*
* @return
*
* @author 單紅宇(CSDN CATOOP)
* @create 2017年3月11日
*/
@Override
public KeyGenerator keyGenerator() {
return new SimpleKeyGenerator() {
/**
* 對(duì)參數(shù)進(jìn)行拼接后MD5
*/
@Override
public Object generate(Object target, Method method, Object... params) {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(".").append(method.getName());
StringBuilder paramsSb = new StringBuilder();
for (Object param : params) {
// 如果不指定,默認(rèn)生成包含到鍵值中
if (param != null) {
paramsSb.append(param.toString());
}
}
if (paramsSb.length() > 0) {
sb.append("_").append(paramsSb);
}
return sb.toString();
}
};
}
/**
* 管理緩存
*
* @param redisTemplate
* @return
*/
@Bean
public CacheManager cacheManager(RedisTemplate<String, Object> redisTemplate, RedisKeys redisKeys) {
RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
// 設(shè)置緩存默認(rèn)過期時(shí)間(全局的)
rcm.setDefaultExpiration(1800);// 30分鐘
// 根據(jù)key設(shè)定具體的緩存時(shí)間,key統(tǒng)一放在常量類RedisKeys中
rcm.setExpires(redisKeys.getExpiresMap());
List<String> cacheNames = new ArrayList<String>(redisKeys.getExpiresMap().keySet());
rcm.setCacheNames(cacheNames);
return rcm;
}
}
二、創(chuàng)建需要緩存數(shù)據(jù)的類
TestService.java
package com.shanhy.example.service;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import com.shanhy.example.redis.RedisKeys;
@Service
public class TestService {
/**
* 固定key
*
* @return
* @author SHANHY
* @create 2017年4月9日
*/
@Cacheable(value = RedisKeys._CACHE_TEST, key = "'" + RedisKeys._CACHE_TEST + "'")
public String testCache() {
return RandomStringUtils.randomNumeric(4);
}
/**
* 存儲(chǔ)在Redis中的key自動(dòng)生成,生成規(guī)則詳見CachingConfig.keyGenerator()方法
*
* @param str1
* @param str2
* @return
* @author SHANHY
* @create 2017年4月9日
*/
@Cacheable(value = RedisKeys._CACHE_TEST)
public String testCache2(String str1, String str2) {
return RandomStringUtils.randomNumeric(4);
}
}
說明一下,其中 @Cacheable 中的 value 值是在 CachingConfig的cacheManager 中配置的,那里是為了配置我們的緩存有效時(shí)間。其中 methodKeyGenerator 為 CachingConfig 中聲明的 KeyGenerator。
另外,Cache 相關(guān)的注解還有幾個(gè),大家可以了解下,不過我們常用的就是 @Cacheable,一般情況也可以滿足我們的大部分需求了。還有 @Cacheable 也可以配置表達(dá)式根據(jù)我們傳遞的參數(shù)值判斷是否需要緩存。
注: TestService 中 testCache 中的 mapper.get 大家不用關(guān)心,這里面我只是訪問了一下數(shù)據(jù)庫而已,你只需要在這里做自己的業(yè)務(wù)代碼即可。
三、測(cè)試方法
下面代碼,隨便放一個(gè) Controller 中
package com.shanhy.example.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.jedis.RedisClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.shanhy.example.service.TestService;
/**
* 測(cè)試Controller
*
* @author 單紅宇(365384722)
* @create 2017年4月9日
*/
@RestController
@RequestMapping("/test")
public class TestController {
private static final Logger LOG = LoggerFactory.getLogger(TestController.class);
@Autowired
private RedisClient redisClient;
@Autowired
private TestService testService;
@GetMapping("/redisCache")
public String redisCache() {
redisClient.set("shanhy", "hello,shanhy", 100);
LOG.info("getRedisValue = {}", redisClient.get("shanhy"));
testService.testCache2("aaa", "bbb");
return testService.testCache();
}
}
至此完畢!
最后說一下,這個(gè) @Cacheable 基本是可以放在所有方法上的,Controller 的方法上也是可以的(這個(gè)我沒有測(cè)試 ^_^)。
源碼下載地址:http://git.oschina.net/catoop/springboot-cache-redis
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java實(shí)現(xiàn)合并兩個(gè)有序序列算法示例
這篇文章主要介紹了Java實(shí)現(xiàn)合并兩個(gè)有序序列算法,簡單描述了序列合并算法的原理與java合并有序序列的具體操作步驟及相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2017-09-09
將字符串?dāng)?shù)字格式化為樣式1,000,000,000的方法
這篇文章主要介紹了將字符串?dāng)?shù)字格式化為樣式1,000,000,000的方法,有需要的朋友可以參考一下2014-01-01
java: 程序包c(diǎn)om.fasterxml.jackson.annotation不存在的解決辦法
當(dāng)我們?cè)趯?dǎo)入程序之后,系統(tǒng)給出錯(cuò)誤提示:java: 程序包c(diǎn)om.fasterxml.jackson.annotation不存在,本文主要介紹了Java程序包不存在的三種解決方法,需要的朋友可以參考下2024-02-02
eclipse實(shí)現(xiàn)ElGamal數(shù)字簽名
這篇文章主要為大家詳細(xì)介紹了eclipse實(shí)現(xiàn)ElGamal數(shù)字簽名,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-06-06
SpringCloud與Dubbo集成Nacos時(shí)服務(wù)重復(fù)注冊(cè)問題的分析與解決
Nacos作為阿里巴巴開源的服務(wù)注冊(cè)與發(fā)現(xiàn)工具,廣泛應(yīng)用于Spring Cloud和Dubbo等微服務(wù)框架中,然而,在實(shí)際開發(fā)中,我們可能會(huì)遇到服務(wù)重復(fù)注冊(cè)的問題,下面我們就來詳細(xì)分析一下這一問題2025-03-03
mybatis整合spring實(shí)現(xiàn)開啟mapper.xml映射文件掃描
這篇文章主要介紹了mybatis整合spring實(shí)現(xiàn)開啟mapper.xml映射文件掃描,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-10-10
SpringCache緩存抽象之CacheManager與自定義鍵生成方式
本文將深入探討Spring Cache的核心組件CacheManager及自定義鍵生成策略,幫助開發(fā)者掌握緩存配置與優(yōu)化技巧,從而構(gòu)建高效可靠的緩存系統(tǒng),希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2025-04-04

