这篇文章主要介绍了SpringBoot Redis缓存数据实现解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
1.启用对缓存的支持
spring对缓存的支持有两种方式:
a.注解驱动的缓存
b.XML声明的缓存
本文主要介绍纯Java配置的缓存,那么必须在配置类上添加@EnableCaching,这样的话就能启动注解驱动的缓存。
2.使用Redis缓存
缓存的条目不过是一个键值对(Key-Value),其中key描述了产生value的操作和参数,因此会很自然的想到Redis。
Redis可以用来为srping缓存抽象机制缓存条目,Spring-Data-Redis提供了RedisCacheManager,这是CacheManager的一个实现。RedisCacheManager会与Redis服务器协作,通过RedisTemplate将缓存条目储存到Redis中。
为了使用RedisCacheManager,我们需要RedisTmeplate Bean配置以及RedisConnectionFactory实现类(JedisConnectionFactory Bean配置)。
3.配置将缓存条目存储在Redis服务器的缓存管理器。
前提需要在pom.xml引入
org.springframework.boot spring-boot-starter-data-redis
在application.properties中配置redis连接相关参数
#配置redis #在RedisProperties.class有redis的默认配置,默认host为localhost,默认端口为6379 spring.redis.host=127.0.0.1 spring.redis.port=6379
配置缓存管理器
package com.niugang;
import java.lang.reflect.Method;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
@Configuration
//没有@EnableCaching这个注解的话,代码不会报错,就是内容不会放入redis中
@EnableCaching
public class RedisConfig {
@Bean
public CacheManager cacheManager() {
RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate());
redisCacheManager.setDefaultExpiration(60);
return redisCacheManager;
}
@Bean
public JedisConnectionFactory jedisConnectionFactory() {
JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();
jedisConnectionFactory.afterPropertiesSet();
return jedisConnectionFactory;
}
@Bean
@SuppressWarnings({ "rawtypes", "unchecked" })
public RedisTemplate redisTemplate() {
RedisTemplate redisTemplate = new RedisTemplate();
redisTemplate.setConnectionFactory(jedisConnectionFactory());
// 使用Jackson2JsonRedisSerialize 替换默认序列化
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
// 设置value的序列化规则和 key的序列化规则
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
@Bean
public KeyGenerator wiselyKeyGenerator(){
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... params) {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : params) {
sb.append(obj.toString());
}
return sb.toString();
}
};
}
}
4.为方法添加注解以支持缓存
spring的缓存抽象在很大程度上是围绕切面构建的,在sprng中启用缓存时,会创建一个切面,它触发
一个或更多的spring的缓存注解。
spring提供了四个注解来声明缓存规则
5.填充缓存
@Cacheable和CachePut都可以填充缓存,他们之间还是确有差异的。
@Cacheable和CachePut共同的属性
6.自定义key
@Cacheable和CachePut都有一个名为key的属性,这个属性能够替代默认的key,t它是通过SpEl(Spring El表达式)表达式计算得到的。具体到我们的业务场景 save(User user),我们需要将key设置保存为User对象中的id,我们通过mysql数据库自动生成id,此时参数中的User对象还没有id.幸好有SpEl。
7.在UserService中添加如下方法。
//@Cacheable(value="findAll",keyGenerator="wiselyKeyGenerator") public ListqueryList() { return userDao.findAll(); } @CachePut(value="save",key="#result.id.toString()") @Transactional public User save(User user) { log.info("添加对象"); return userDao.save(user); } @Cacheable(value="findOne",key="#id.toString()") public User get(Integer id) { log.info("从数据查询id为:{}的对象",id); return userDao.findOne(id); } @CacheEvict(value="save",key="#id.toString()") @Transactional public void delete(int id) { log.info("从数据删除id为:{}的对象",id); userDao.delete(id); }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



