首页 > 数据库 >使用springboot cache + redis缓存时使用gzip压缩以提升性能

使用springboot cache + redis缓存时使用gzip压缩以提升性能

时间:2023-02-17 17:22:05浏览次数:40  
标签:return springboot cache redis gzip new byte public

背景

在高并发的场景中,我们通常会使用缓存提升性能。在使用springboot cache时,我们通常会使用基于JSON的序列化与反序列化。

JSON具有可读性强,结构简单的特点,使用灵活。

但是JSON体积大,占用redis内存,同时增加网络开销,使用gzip压缩可以将体积缩减到原来的十分之以下,取得媲美Protobuf的编码效率

使用springboot cache + redis并使用Gzip压缩

引入依赖

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

Gzip压缩工具类

public class GzipUtil {
    public static byte[] compress(byte[] data) throws IOException {
        if (data == null || data.length == 0) {
            return new byte[0];
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        GZIPOutputStream gzOut = new GZIPOutputStream(out);
        gzOut.write(data);
        gzOut.close();
        return out.toByteArray();
    }
    
    public static byte[] decompress(byte[] gzip) throws IOException {
        if (gzip == null || gzip.length == 0) {
            return new byte[0];
        }
        ByteArrayInputStream in = new ByteArrayInputStream(gzip);
        GZIPInputStream gzIn = new GZIPInputStream(in);
        return gzIn.readAllBytes();
    }
    
}

继承GenericJackson2JsonRedisSerializer 并实现Gzip压缩

    public class JacksonGzipSerializer extends GenericJackson2JsonRedisSerializer {
        @Override
        public byte[] serialize(@Nullable Object source) throws SerializationException {
            byte[] raw = super.serialize(source);
            try {
                return GzipUtil.compress(raw);
            } catch (IOException ioe) {
                throw new SerializationException("Exception", ioe);
            }
        }

        @Override
        public Object deserialize(@Nullable byte[] source) throws SerializationException {
            try {
                byte[] raw = GzipUtil.decompress(source);
                return deserialize(raw, Object.class);
            } catch (IOException ioe) {
                throw new SerializationException("Exception", ioe);
            }
        }
    }

配置Config,使用上述自定义的序列化及反序列化机制

@Configuration
public class CacheConfig implements CachingConfigurer {

    @Resource
    private RedisConnectionFactory redisConnectionFactory;
    
    @Override
    @Bean
    public CacheManager cacheManager() {
        return new RedisCacheManager(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory), redisCacheConfiguration());
    }

    public RedisCacheConfiguration redisCacheConfiguration() {
        return RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofMinutes(5))
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(RedisSerializer.string()))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new JacksonGzipSerializer()));

    }
}

使用@EnableCaching开启缓存

@SpringBootApplication
@EnableCaching
public class RedisCacheApplication {
    public static void main(String[] args) {
        SpringApplication.run(RedisCacheApplication.class, args);
    }
}

最后别忘了配置redis(具体格式和springboot版本有关)

spring.redis.database=0
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=

效果

没用使用gzip的大小101KB

使用gzip压缩后的大小 14KB

标签:return,springboot,cache,redis,gzip,new,byte,public
From: https://www.cnblogs.com/bianheng/p/17130852.html

相关文章

  • PHP Cache_Lite 下载及使用
    https://github.com/pear/Cache_Litecomposerrequirepear/cache_litecomposer如果提示root不安全可以切换为www用户su-www-s/bin/bashcomposer加载原理,有空再研究......
  • redis的key过期策略+内存淘汰策略
    redis的key过期策略是怎么样的redis的过期策略主要是定期删除和懒删除来实现的定期删除redis定时每间隔大约100ms进行随机抽选择1批key,对过期的key进行删除,并且根......
  • 第一周复习笔记(MySQL、Redis、JVM、JUC)
    MySQL1.引擎1.1Innodb和MyIsAM的区别1.2Innodb的逻辑存储结构2.索引2.1索引的分类2.2索引优化2.3索引失效的场景3.事务3.1事务的隔离级别3.2ACID原则......
  • springboot加入cloud,并注册到nacos
    pom.xml下新增 <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-context</artifactId> <version>2.2.5.RELEASE</version> ......
  • 超好用的 Redis GUI 工具,你值得拥有
    超好用的RedisGUI工具,你值得拥有提供原生的性能,并且比使用Electron等Web技术开发的同等应用程序消耗的资源少得多。下载地址:http://www.redisant.cn/功能介绍实......
  • SpringBoot 整合 RabbitMQ
    SpringBoot整合RabbitMQ生产者application.yml#配置RabbitMQ的基本信息spring:rabbitmq:#iphost:192.168.36.100#usernameuse......
  • SpringBoot
    SpringBoot2核心技术与响应式编程SpringBoot2核心技术SpringBoot2基础入门Spring能做什么?Spring的生态覆盖了:web开发数据访问安全控制分布式消息服务移动......
  • Redis 介绍
        ......
  • SpringBoot配置与打包基础
    本篇主要记录SpringBoot使用的基础配置SpringBootMaven配置SpringBootmaven依赖关系我们创建springboot项目后,会发现项目的pom文件都会继承自spring-boot-starter-p......
  • Feign远程调用结合fallback(Springboot包扫描)
    Feign远程调用结合fallback(Springboot包扫描)微服务项目中,各微服务模块间互相调用,通常使用HTTP协议调用,为了优雅和快速调用服务,通常使用HTTP客户端,如Feign为各服务编写......