SpringBoot Redis配置Fastjson進行序列化和反序列化實現(xiàn)
FastJson是阿里開源的一個高性能的JSON框架,F(xiàn)astJson數(shù)據(jù)處理速度快,無論序列化(把JavaBean對象轉(zhuǎn)化成Json格式的字符串)和反序列化(把JSON格式的字符串轉(zhuǎn)化為Java Bean對象),都是當(dāng)之無愧的fast;功能強大(支持普通JDK類,包括javaBean, Collection, Date 或者enum);零依賴(沒有依賴其他的任何類庫)。
1、寫一個自定義序列化類
/**
* 自定義序列化類
* @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、寫一個Redis配置類
@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類
@Data
public class Student {
private Integer studentId;
private String studentName;
}
4、pom.xml引入redis和fastjson的依賴,application.yml配置文件別忘了配置Redis的地址。
5、BootRedisApplication啟動類
@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("學(xué)生A");
RedisTemplate cRedisTemplate = context.getBean("redisTemplate", RedisTemplate.class);
cRedisTemplate.opsForValue().set("student-1", student);
context.close();
}
}
6、查看Redis的數(shù)據(jù)
{"@type":"com.example.bootredis.Student","studentId":101,"studentName":"學(xué)生A"}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
解決springboot與springcloud版本兼容問題(附版本兼容表)
在基于spring boot搭建spring cloud時,創(chuàng)建eureka后啟動服務(wù)發(fā)生報錯,本文給大家介紹了解決springboot與springcloud版本兼容問題的幾種方案,需要的朋友可以參考下2024-02-02
Jmeter連接Mysql數(shù)據(jù)庫實現(xiàn)過程詳解
這篇文章主要介紹了Jmeter連接Mysql數(shù)據(jù)庫實現(xiàn)過程詳解,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-08-08

