FastJson是阿里開源的一個高性能的JSON框架,FastJson數據處理速度快,無論序列化(把JavaBean對象轉化成Json格式的字符串)和反序列化(把JSON格式的字符串轉化為Java Bean對象),都是當之無愧的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("學生A"); RedisTemplate cRedisTemplate = context.getBean("redisTemplate", RedisTemplate.class); cRedisTemplate.opsForValue().set("student-1", student); context.close(); } }
6、查看Redis的數據
{"@type":"com.example.bootredis.Student","studentId":101,"studentName":"學生A"}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。