溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

SpringBoot Redis配置Fastjson進行序列化和反序列化實現

發布時間:2020-09-15 19:56:00 來源:腳本之家 閱讀:595 作者:碼農云帆哥 欄目:編程語言

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"}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女