【Spring Boot實戰與進階】Redis配置Fastjson進行序列化和反序列化

Spring Boot是很優秀的框架,它的出現簡化了新Spring應用的初始搭建以及開發過程,大大減少了代碼量,目前已被大多數企業認可和使用。這個專欄將對Spring Boot框架從淺入深,從實戰到進階,不但我們要懂得如何去使用,還要去剖析框架源碼,學習其優秀的設計思想。

彙總目錄鏈接:【Spring Boot實戰與進階】學習目錄


  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、Java Bean

@Data
public class Student {
    private Integer studentId;
    private String studentName;
}

4、引入依賴

  pom.xml引入redis和fastjson的依賴,application.yml配置文件別忘了配置Redis的地址。

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

 <dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>fastjson</artifactId>
</dependency>

5、配置文件

spring:
  redis:
    host: 127.0.0.1
    port: 6379

6、項目啓動類

@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();
    }
}

7、查看Redis的數據

{"@type":"com.example.bootredis.Student","studentId":101,"studentName":"學生A"}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章