SpringBoot整合Redis
引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--用来解决序列化问题-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.75</version>
</dependency>
注意事项:引入依赖报错的时候,可能是SpringBoot版本和Redis版本的问题,建议换一下版本
配置文件
spring.redis.database=0
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=
注意事项:密码就算没有,密码配置也最好写上
序列化工具
@Data
public class Fast2JsonSerialize<T> implements RedisSerializer<T> {
private static final Charset DEFAULT_CHARSET=Charset.forName("UTF-8");
private Class<T> clazz;
public Fast2JsonSerialize(Class<T> clazz){
super();
this.clazz=clazz;
}
static{
ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
}
@Override
public byte[] serialize(T t) throws SerializationException {
if(t==null){
return new byte[0];
}
return JSON.toJSONString(t,SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
}
@Override
public T deserialize(byte[] bytes) throws SerializationException {
if(bytes==null||bytes.length<=0){
return null;
}
String string = new String(bytes, DEFAULT_CHARSET);
return (T)JSON.parseObject(string,clazz);
}
}
注意事项:ParserConfig.getGlobalInstance().setAutoTypeSupport(true) 一定要设置为true
Redis配置类
@Configuration
public class RedisConfig {
@Bean
public RedisSerializer redisSerializer(){
return new Fast2JsonSerialize<Object>(Object.class);
}
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory factory,RedisSerializer fastSerializer){
RedisTemplate template = new RedisTemplate();
template.setConnectionFactory(factory);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(fastSerializer);
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(fastSerializer);
return template;
}
}
配置完成后,可以直接使用RedisTemplate操作Redis数据库,但最好封装一下RedisTemplate;
|