Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
Ali FastJson open source framework JSON a high-performance, fast FastJson data processing speed, regardless of the sequence (to be converted into a JavaBean Json string format) and deserialization (JSON-formatted string into the object Java Bean) are worthy of the fast; powerful (JDK support the general categories, including javaBean, Collection, Date, or enum); zero-dependent (not dependent on any other libraries).
1, to write a custom serialization class
/**
* 自定义序列化类
* @param <T>
*/
public class FastJsonRedisSerializer<T> implements RedisSerializer<T> {
public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
private Class<T> clazz;
public FastJsonRedisSerializer(Class<T> clazz) {
super();
this.clazz = clazz;
}
@Override
public byte[] serialize(T t) throws SerializationException {
if (null == t) {
return new byte[0];
}
return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
}
@Override
public T deserialize(byte[] bytes) throws SerializationException {
if (null == bytes || bytes.length <= 0) {
return null;
}
String str = new String(bytes, DEFAULT_CHARSET);
return (T) JSON.parseObject(str, clazz);
}
}
2, write a Redis configuration class
@Configuration
public class RedisConfiguration {
@Bean
public RedisTemplate<Object, Object> redisTemplate(
RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
//使用fastjson序列化
FastJsonRedisSerializer fastJsonRedisSerializer = new FastJsonRedisSerializer(Object.class);
// value值的序列化采用fastJsonRedisSerializer
template.setValueSerializer(fastJsonRedisSerializer);
template.setHashValueSerializer(fastJsonRedisSerializer);
// key的序列化采用StringRedisSerializer
template.setKeySerializer(new StringRedisSerializer());
template.setHashKeySerializer(new StringRedisSerializer());
template.setConnectionFactory(redisConnectionFactory);
return template;
}
}
3, Student category
@Data
public class Student {
private Integer studentId;
private String studentName;
}
4, pom.xml fastjson dependence introduction and redis, application.yml address configuration profile Remember the Redis.
5, BootRedisApplication startup class
@SpringBootApplication
public class BootRedisApplication {
public static void main(String[] args) {
ConfigurableApplicationContext
context = SpringApplication.run(BootRedisApplication.class, args);
Student student = new Student();
student.setStudentId(101);
student.setStudentName("学生A");
RedisTemplate cRedisTemplate = context.getBean("redisTemplate", RedisTemplate.class);
cRedisTemplate.opsForValue().set("student-1", student);
context.close();
}
}
6, see Redis data
{"@type":"com.example.bootredis.Student","studentId":101,"studentName":"学生A"}