springboot 整合 redis的第一种方式
基于注解的cacheManger
导入redis依赖和fastjson依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.7</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
配置KeyGenerator,将在返回结果为多条数据时使用
@Component("ListKeyGenerator")
public class ListKeyGenerator implements KeyGenerator {
@Override
public Object generate(Object o, Method method, Object... objects) {
return "list";
}
}
引入阿里的FastJson2JsonRedisSerializer 序列化器
/**
* FastJson2JsonRedisSerializer
* Redis使用FastJson序列化
* by zhengkai.blog.csdn.net
*/
public class FastJson2JsonRedisSerializer<T> implements RedisSerializer<T> {
private ObjectMapper objectMapper = new ObjectMapper();
public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
private Class<T> clazz;
static {
ParserConfig.getGlobalInstance();
}
public FastJson2JsonRedisSerializer(Class<T> clazz) {
super();
this.clazz = clazz;
}
public byte[] serialize(T t) throws SerializationException {
if (t == null) {
return new byte[0];
}
return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
}
public T deserialize(byte[] bytes) throws SerializationException {
if (bytes == null || bytes.length <= 0) {
return null;
}
String str = new String(bytes, DEFAULT_CHARSET);
return JSON.parseObject(str, clazz);
}
public void setObjectMapper(ObjectMapper objectMapper) {
Assert.notNull(objectMapper, "'objectMapper' must not be null");
this.objectMapper = objectMapper;
}
protected JavaType getJavaType(Class<?> clazz) {
return TypeFactory.defaultInstance().constructType(clazz);
}
}
配置redis配置类,并且使用FastJson2JsonRedisSerializer序列化器
@Configuration
@EnableCaching
public class RedisConfig {
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
RedisSerializer<String> redisSerializer = new StringRedisSerializer();
// 引用FastJson2JsonRedisSerializer序列化器,目的是将数据以json存入redis中
FastJson2JsonRedisSerializer fastJsonSeial = new FastJson2JsonRedisSerializer(Object.class);
// Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
fastJsonSeial.setObjectMapper(objectMapper);
// 配置序列化
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(fastJsonSeial));
RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
.cacheDefaults(config)
.build();
return cacheManager;
}
}
在service层中使用注解
@Service
// 整合redis 相当于在redis创建一个文件夹
@CacheConfig(cacheNames = "User")
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userdao;
// 查询结果为多条数据时,使用KeyGenerator
@Cacheable(keyGenerator = "ListKeyGenerator")
@Override
public List<User> findUser() {
return userdao.findUser();
}
// 根据id删除缓存数据
@CacheEvict(key="#id")
@Override
public void deleteUser(String id) {
userdao.deleteUser(id);
}
// 根据id修改缓存数据 #user.id对应参数user里的id,#result.id对应返回对象user里的id
@CachePut(key = "#user.id")
@Override
public User updateUser(User user) {
userdao.updateUser(user);
return user;
}
// 查询结果进行缓存
@Cacheable(key = "#id")
@Override
public User findUserById(String id) {
User userById = userdao.findUserById(id);
return userById;
}
// 添加数据后,需要将缓存中的查询所有方法的缓存删除
@Caching(
put = @CachePut(key = "#user.id"),
evict = @CacheEvict(keyGenerator = "ListKeyGenerator")
)
@Override
public User addUser(User user) {
userdao.addUser(user);
return user;
}
}
redis中缓存情况
以上就是基于注解的redis整合