当前位置:首页 > 技术分析 > 正文内容

Spring Boot如何压缩Json并写入redis?

ruisui883个月前 (02-04)技术分析16

1.为什么需要压缩json?

由于业务需要,存入redis中的缓存数据过大,占用了10+G的内存,内存作为重要资源,需要优化一下大对象缓存,采用gzip压缩存储,可以将 redis 的 kv 对大小缩小大约 7-8 倍,加快存储、读取速度

2.环境搭建

详建redis模块的docker目录

version: '3'
services:
  redis:
    image: registry.cn-hangzhou.aliyuncs.com/zhengqing/redis:6.0.8                   
    container_name: redis                                                             
    restart: unless-stopped                                                                  
    command: redis-server /etc/redis/redis.conf --requirepass 123456 --appendonly no
#    command: redis-server --requirepass 123456 --appendonly yes 
    environment:                        
      TZ: Asia/Shanghai
      LANG: en_US.UTF-8
    volumes:                           
      - "./redis/data:/data"
      - "./redis/config/redis.conf:/etc/redis/redis.conf"  
    ports:                              
      - "6379:6379"

3.代码工程

实验目标

实验存入redis的json数据压缩和解压缩

pom.xml



    
        springboot-demo
        com.et
        1.0-SNAPSHOT
    
    4.0.0

    gzip

    
        8
        8
    
    
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-autoconfigure
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            org.projectlombok
            lombok
        
        
            org.springframework.boot
            spring-boot-starter-data-redis
        
        
            org.apache.commons
            commons-pool2
            2.9.0
        

    

controller

package com.et.gzip.controller;

import com.et.gzip.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
public class HelloWorldController {
    @Autowired
    private RedisTemplate redisTemplateWithJackson;

    @PostMapping("/hello")
    public User showHelloWorld(@RequestBody User user){
        log.info("user:"+ user);

        return user;
    }
    @PostMapping("/redis")
    public User redis(@RequestBody User user){
        log.info("user:"+ user);
        redisTemplateWithJackson.opsForValue().set("user",user);
        User redisUser = (User) redisTemplateWithJackson.opsForValue().get("user");
        return redisUser;
    }
}

redis压缩和解压缩配置

压缩类

package com.et.gzip.config;

import com.et.gzip.model.User;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;

import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import sun.misc.BASE64Encoder;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.text.SimpleDateFormat;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

@Slf4j
public class CompressRedis extends JdkSerializationRedisSerializer {

    public static final int BUFFER_SIZE = 4096;

    private JacksonRedisSerializer  jacksonRedisSerializer;
    public CompressRedis() {
        this.jacksonRedisSerializer = getValueSerializer();
    }

    @Override
    public byte[] serialize(Object graph) throws SerializationException {
        if (graph == null) {
            return new byte[0];
        }
        ByteArrayOutputStream bos = null;
        GZIPOutputStream gzip = null;
        try {
            // serialize
            byte[] bytes = jacksonRedisSerializer.serialize(graph);
            log.info("bytes size{}",bytes.length);
            bos = new ByteArrayOutputStream();
            gzip = new GZIPOutputStream(bos);

            // compress
            gzip.write(bytes);
            gzip.finish();
            byte[] result = bos.toByteArray();

            log.info("result size{}",result.length);
            //return result;
            return new BASE64Encoder().encode(result).getBytes();
        } catch (Exception e) {
            throw new SerializationException("Gzip Serialization Error", e);
        } finally {
            IOUtils.closeQuietly(bos);
            IOUtils.closeQuietly(gzip);
        }
    }

    @Override
    public Object deserialize(byte[] bytes) throws SerializationException {
        if (bytes == null || bytes.length == 0) {
            return null;
        }
        ByteArrayOutputStream bos = null;
        ByteArrayInputStream bis = null;
        GZIPInputStream gzip = null;
        try {
            bos = new ByteArrayOutputStream();
            byte[] compressed = new sun.misc.BASE64Decoder().decodeBuffer( new String(bytes));;
            bis = new ByteArrayInputStream(compressed);
            gzip = new GZIPInputStream(bis);
            byte[] buff = new byte[BUFFER_SIZE];
            int n;


            // uncompress
            while ((n = gzip.read(buff, 0, BUFFER_SIZE)) > 0) {
                bos.write(buff, 0, n);
            }
            //deserialize
            Object result = jacksonRedisSerializer.deserialize(bos.toByteArray());
            return result;
        } catch (Exception e) {
            throw new SerializationException("Gzip deserizelie error", e);
        } finally {
            IOUtils.closeQuietly(bos);
            IOUtils.closeQuietly(bis);
            IOUtils.closeQuietly(gzip);
        }
    }

    private static JacksonRedisSerializer getValueSerializer() {
        JacksonRedisSerializer jackson2JsonRedisSerializer = new JacksonRedisSerializer<>(User.class);
        ObjectMapper mapper=new ObjectMapper();
        jackson2JsonRedisSerializer.setObjectMapper(mapper);
        return jackson2JsonRedisSerializer;
    }

}

java序列化

package com.et.gzip.config;


import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import lombok.extern.slf4j.Slf4j;

import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

@Slf4j
public class JacksonRedisSerializer implements RedisSerializer {
    public static final Charset DEFAULT_CHARSET;
    private final JavaType javaType;
    private ObjectMapper objectMapper = new ObjectMapper();

    public JacksonRedisSerializer(Class type) {
        this.javaType = this.getJavaType(type);
    }

    public JacksonRedisSerializer(JavaType javaType) {
        this.javaType = javaType;
    }

    public T deserialize(@Nullable byte[] bytes) throws SerializationException {
        if (bytes == null || bytes.length == 0) {
            return null;
        } else {
            try {
                return this.objectMapper.readValue(bytes, 0, bytes.length, this.javaType);

            } catch (Exception var3) {
                throw new SerializationException("Could not read JSON: " + var3.getMessage(), var3);
            }
        }
    }

    public byte[] serialize(@Nullable Object t) throws SerializationException {
        if (t == null) {
            return  new byte[0];
        } else {
            try {
                return this.objectMapper.writeValueAsBytes(t);
            } catch (Exception var3) {
                throw new SerializationException("Could not write JSON: " + var3.getMessage(), var3);
            }
        }
    }

    public void setObjectMapper(ObjectMapper objectMapper) {
        Assert.notNull(objectMapper, "'objectMapper' must not be null");
        this.objectMapper = objectMapper;
    }

    protected JavaType getJavaType(Class clazz) {
        return TypeFactory.defaultInstance().constructType(clazz);
    }

    static {
        DEFAULT_CHARSET = StandardCharsets.UTF_8;
    }
}

redis序列化

package com.et.gzip.config;

import com.et.gzip.model.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;


@Configuration
public class RedisWithJacksonConfig {


    @Bean(name="redisTemplateWithJackson")
    public RedisTemplate redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {

        CompressRedis  compressRedis =  new CompressRedis();
        //redisTemplate
        RedisTemplate redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(lettuceConnectionFactory);
        RedisSerializer stringSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringSerializer);
        redisTemplate.setValueSerializer(compressRedis);
        redisTemplate.setHashKeySerializer(stringSerializer);
        redisTemplate.setHashValueSerializer(compressRedis);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
}

application.yaml

spring:
  redis:
    host: 127.0.0.1
    port: 6379
    database: 10
    password: 123456
    timeout: 10s
    lettuce:
      pool:
        min-idle: 0
        max-idle: 8
        max-active: 8
        max-wait: -1ms
server:
  port: 8088
  compression:
    enabled: true
    mime-types: application/json,application/xml,text/html,text/plain,text/css,application/x-javascript

以上只是一些关键代码,所有代码请参见下面代码仓库

代码仓库

  • github.com/Harries/spr…(gzip)

4.测试

  1. 启动spring boot应用
  2. 用postman访问http://127.0.0.1:8088/redis

可以看到redis里面存储的是gzip压缩的内容

查看控制台日志

2024-08-26 14:37:56.445 INFO 43832 --- [nio-8088-exec-5] com.et.gzip.config.CompressRedis : bytes size371
2024-08-26 14:37:56.445 INFO 43832 --- [nio-8088-exec-5] com.et.gzip.config.CompressRedis : result size58

JSON经过gzip压缩,371-->58, 数据大小减少7-8倍

5.引用

  • https://www.liuhaihua.cn/archives/711216.html

扫描二维码推送至手机访问。

版权声明:本文由ruisui88发布,如需转载请注明出处。

本文链接:http://www.ruisui88.com/post/1648.html

标签: objectmapper
分享给朋友:

“Spring Boot如何压缩Json并写入redis?” 的相关文章

体检刷卡收费管理系统

体检刷卡收费管理系统headerfooter《体检刷卡收费管理系统》是针对各医院进行体检刷卡收费管理的一套系统。软件集办卡、充值、刷卡消费、体检登记与一体。主要功能:1.基本信息:科室设置、套餐设置、单项设置、本院信息;2.体检卡管理:单位人员办卡、个人办卡、体检卡充值、体检卡禁用、体检卡开通、体检...

vue 3 学习笔记 (八)——provide 和 inject 用法及原理

在父子组件传递数据时,通常使用的是 props 和 emit,父传子时,使用的是 props,如果是父组件传孙组件时,就需要先传给子组件,子组件再传给孙组件,如果多个子组件或多个孙组件使用时,就需要传很多次,会很麻烦。像这种情况,可以使用 provide 和 inject 解决这种问题,不论组件嵌套...

如何在GitLab上回退指定版本的代码?GitLab回退指定版本问题分析

在Git中,回退到指定版本并不是删除或撤销之前的提交,而是创建一个新的提交,该提交包含指定版本的内容。这意味着您需要将当前代码更改与指定版本之间的差异进行比较,并将其合并到一个新的提交中。如果您没有更新本地代码,并且您希望将 GitLab 仓库回退到指定版本,您可以使用以下命令:git fetchg...

程序员开发必会之git常用命令,git配置、拉取、提交、分支管理

整理日常开发过程中经常使用的git命令![送心]git配置SSH刚进入项目开发中,我们首先需要配置git的config、配置SSH方式拉取代码,以后就免输入账号密码了!# 按顺序执行 git config --global user.name "自己的账号" git config -...

使用cgroup限制进程资源

这里使用containerd项目中的cgroup包来实现进程资源限制。先写一个耗费一个CPU并且一秒增加10m内存的测试进程package mainimport ( "fmt" "math/rand" "time")func main() { go f...

HTML5学习笔记三:HTML5语法规则

1.标签要小写2.属性值可加可不加””或”3.可以省略某些标签 html body head tbody4.可以省略某些结束标签 tr td li例:显示效果:5.单标签不用加结束标签img input6.废除的标签font center big7.新添加的标签将在下一HTML5学习笔记中重点阐述。...