SpringBoot Redis配置Fastjson进行序列化和反序列化实现
FastJson是阿里开源的一个高性能的JSON框架,FastJson数据处理速度快,无论序列化(把JavaBean对象转化成Json格式的字符串)和反序列化(把JSON格式的字符串转化为JavaBean对象),都是当之无愧的fast;功能强大(支持普通JDK类,包括javaBean,Collection,Date或者enum);零依赖(没有依赖其他的任何类库)。
1、写一个自定义序列化类
/** *自定义序列化类 *@param*/ publicclassFastJsonRedisSerializer implementsRedisSerializer { publicstaticfinalCharsetDEFAULT_CHARSET=Charset.forName("UTF-8"); privateClass clazz; publicFastJsonRedisSerializer(Class clazz){ super(); this.clazz=clazz; } @Override publicbyte[]serialize(Tt)throwsSerializationException{ if(null==t){ returnnewbyte[0]; } returnJSON.toJSONString(t,SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET); } @Override publicTdeserialize(byte[]bytes)throwsSerializationException{ if(null==bytes||bytes.length<=0){ returnnull; } Stringstr=newString(bytes,DEFAULT_CHARSET); return(T)JSON.parseObject(str,clazz); } }
2、写一个Redis配置类
@Configuration publicclassRedisConfiguration{ @Bean publicRedisTemplate
3、Student类
@Data publicclassStudent{ privateIntegerstudentId; privateStringstudentName; }
4、pom.xml引入redis和fastjson的依赖,application.yml配置文件别忘了配置Redis的地址。
5、BootRedisApplication启动类
@SpringBootApplication publicclassBootRedisApplication{ publicstaticvoidmain(String[]args){ ConfigurableApplicationContext context=SpringApplication.run(BootRedisApplication.class,args); Studentstudent=newStudent(); student.setStudentId(101); student.setStudentName("学生A"); RedisTemplatecRedisTemplate=context.getBean("redisTemplate",RedisTemplate.class); cRedisTemplate.opsForValue().set("student-1",student); context.close(); } }
6、查看Redis的数据
{"@type":"com.example.bootredis.Student","studentId":101,"studentName":"学生A"}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。