redis序列化配置
package com.example.demo.config;
import com.example.demo.common.util.RedisUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
public class RedisConfig {
// 使用Jackson2JsonRedisSerialize替换默认JDK序列化
@Bean
public RedisTemplate<Object,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
RedisTemplate<Object,Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
// key采用String的序列化方式
redisTemplate.setKeySerializer(new StringRedisSerializer());
// hash的key也采用String的序列化方式
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
// value序列化方式采用jackson
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
// hash的hash的value序列化方式采用jackson
redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
return redisTemplate;
}
}
redis封裝工具類
package com.example.demo.common.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
/**
* Redis操作工具类
*/
@Component
public class RedisUtil {
@Autowired
private RedisTemplate<Object, Object> redisTemplate;
// 存入数据到缓存
public void setValue(String key, Object value) {
redisTemplate.opsForValue().set(key, value);
}
// 通过key获得数据
public Object getValue(String key) {
return redisTemplate.opsForValue().get(key);
}
// 存入数据到缓存并设置过期时间(单位为秒)
public void setValueAndExpire(String key, Object value, long time){
redisTemplate.opsForValue().set(key, value,time, TimeUnit.SECONDS);
}
// 删除缓存
public void delete(String key){
redisTemplate.delete(key);
}
}