SpringBoot2整合Redis緩存三步驟代碼詳解
更新時間:2020年03月04日 09:33:36 作者:趙小胖0914
這篇文章主要介紹了SpringBoot2整合Redis緩存三步驟,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
遵循SpringBoot三板斧
第一步加依賴
<!-- Redis --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <!-- redis依賴commons-pool 這個依賴一定要添加 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> <version>2.6.0</version> </dependency>
第二步寫注解
@EnableCaching//開啟緩存支持
第三步寫配置
spring:
redis:
database: 0
host: 192.168.1.11
port: 6379
password:
timeout: 600
lettuce:
pool:
max-active: 50
max-wait: -1
max-idle: 8
min-idle: 0
編寫Redis配置類
/**
* @Author: zc
* @Date: 2019/11/3 14:12
* @Description: SpringBoot2.0 Redis緩存配置
* @EnableCaching:開啟緩存支持
*/
@Slf4j
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
@Value("${sys.dataCaching.expireTime:0}")
private int expireTime;
@Resource
private LettuceConnectionFactory lettuceConnectionFactory;
@Override
@Bean
public KeyGenerator keyGenerator() {//設(shè)置自定義key{ClassName + methodName + params}
return (target, method, params) -> {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(",Method:");
sb.append(method.getName());
sb.append(",Params[");
for (int i = 0; i < params.length; i++) {
sb.append(params[i].toString());
if (i != (params.length - 1)) {
sb.append(",");
}
}
sb.append("]");
log.debug("Data Caching Redis Key : {}", sb.toString());
return sb.toString();
};
}
//自定義keyGenerator,Key生成器
@Bean
public KeyGenerator updateByIdkeyGenerator() {
return (target, method, params) -> {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(",Method:");
sb.append("getById");
sb.append(",Params[");
try {
Field id = params[0].getClass().getDeclaredField("id");
id.setAccessible(true);
sb.append(id.get(params[0]).toString());
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
sb.append("]");
log.debug("Data Caching Redis Key : {}", sb.toString());
return sb.toString();
};
}
//自定義keyGenerator,Key生成器
@Bean
public KeyGenerator deleteByIdkeyGenerator() {
return (target, method, params) -> {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(",Method:");
sb.append("getById");
sb.append(",Params[");
for (int i = 0; i < params.length; i++) {
sb.append(params[i].toString());
if (i != (params.length - 1)) {
sb.append(",");
}
}
sb.append("]");
log.debug("Data Caching Redis Key : {}", sb.toString());
return sb.toString();
};
}
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
//設(shè)置緩存過期時間
if (expireTime > 0) {
log.info("Redis 緩存過期時間 : {}", expireTime);
//設(shè)置緩存有效期 秒
redisCacheConfiguration.entryTtl(Duration.ofSeconds(expireTime));
} else {
log.info("Redis 未設(shè)置緩存過期時間");
}
return RedisCacheManager
.builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
.cacheDefaults(redisCacheConfiguration).build();
}
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {//創(chuàng)建RedisTemplate
// 設(shè)置序列化
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(
Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
// 配置redisTemplate
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
redisTemplate.setConnectionFactory(lettuceConnectionFactory);
RedisSerializer<?> stringSerializer = new StringRedisSerializer();
// key序列化
redisTemplate.setKeySerializer(stringSerializer);
// value序列化
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
// Hash key序列化
redisTemplate.setHashKeySerializer(stringSerializer);
// Hash value序列化
redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}
如何使用查詢緩存
@CacheConfig(cacheNames = "demoDao")
@Component
public class DemoDao implements IDemoDAO<> {
@Autowired
DemoMapper mapper;
//用默認配置的keyGenerator
@Cacheable
@Override
public Demo getById(Integer id) {
return mapper.getById(id);
}
//使用配置的keyGenerator,清空緩存
@CacheEvict(keyGenerator = "updateByIdkeyGenerator")
@Override
public int update(T entity) {
return mapper.update(entity);
}
//使用配置的keyGenerator,清空緩存
@CacheEvict(keyGenerator = "deleteByIdkeyGenerator")
@Override
public int deleteById(Integer id) {
return mapper.deleteById(id);
}
}
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:
- SpringBoot項目中使用redis緩存的方法步驟
- SpringBoot 開啟Redis緩存及使用方法
- springboot+mybatis+redis 二級緩存問題實例詳解
- SpringBoot AOP控制Redis自動緩存和更新的示例
- SpringBoot+SpringCache實現(xiàn)兩級緩存(Redis+Caffeine)
- 詳解SpringBoot集成Redis來實現(xiàn)緩存技術(shù)方案
- SpringBoot使用Redis緩存的實現(xiàn)方法
- SpringBoot使用Redis緩存MySql的方法步驟
- springboot使用shiro-整合redis作為緩存的操作
- SpringBoot redis分布式緩存實現(xiàn)過程解析
- SpringBoot Redis緩存數(shù)據(jù)實現(xiàn)解析
- SpringBoot結(jié)合Redis實現(xiàn)緩存
相關(guān)文章
SpringBoot?快速實現(xiàn)?api?接口加解密功能
在項目中,為了保證數(shù)據(jù)的安全,我們常常會對傳遞的數(shù)據(jù)進行加密,Spring?Boot接口加密,可以對返回值、參數(shù)值通過注解的方式自動加解密,這篇文章主要介紹了SpringBoot?快速實現(xiàn)?api?接口加解密功能,感興趣的朋友一起看看吧2023-10-10
springboot配置文件中使用${}注入值的兩種方式小結(jié)
這篇文章主要介紹了springboot配置文件中使用${}注入值的兩種方式小結(jié),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03
Springboot集成任務調(diào)度實現(xiàn)過程
這篇文章主要介紹了Springboot集成任務調(diào)度實現(xiàn)過程,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-04-04

