springboot对压缩请求的处理方法是什么
springboot对压缩请求的处理
最近对接银联需求,为了节省带宽,需要对报文进行压缩处理。但是使用springboot自带的压缩设置不起作用:
server.compression.enabled=true server.compression.mime-types=application/javascript,text/css,application/json,application/xml,text/html,text/xml,text/plain server.compression.compressionMinSize=10
server.compression.enabled:表示是否开启压缩,默认开启,true:开启,false:不开启
server.compression.mime-types:压缩的内容的类型,有xml,json,html等格式
server.compression.compressionMinSize:开启压缩数据最小长度,单位为字节,默认是2048字节
源码如下:
public class Compression { private boolean enabled = false; private String[] mimeTypes = new String[]{"text/html", "text/xml", "text/plain", "text/css", "text/javascript", "application/javascript", "application/json", "application/xml"}; private String[] excludedUserAgents = null; private int minResponseSize = 2048; }
一、Tomcat设置压缩原理
tomcat压缩是对响应报文进行压缩,当请求头中存在accept-encoding时,如果Tomcat设置了压缩,则会在响应时对数据进行压缩。
tomcat压缩源码是在Http11Processor中设置的:
public class Http11Processor extends AbstractProcessor { private boolean useCompression() { // Check if browser support gzip encoding MessageBytes acceptEncodingMB = request.getMimeHeaders().getValue("accept-encoding"); if ((acceptEncodingMB == null)-->当请求头没有这个字段是不进行压缩 || (acceptEncodingMB.indexOf("gzip") == -1)) { return false; } // If force mode, always compress (test purposes only) if (compressionLevel == 2) { return true; } // Check for incompatible Browser if (noCompressionUserAgents != null) { MessageBytes userAgentValueMB = request.getMimeHeaders().getValue("user-agent"); if(userAgentValueMB != null) { String userAgentValue = userAgentValueMB.toString(); if (noCompressionUserAgents.matcher(userAgentValue).matches()) { return false; } } } return true; } }
二、银联报文压缩
作为发卡机构,银联报文请求报文是压缩的,且报文头中不存在accept-encoding字段,无法直接使用tomcat配置进行压缩解压。
需要单独处理这种请求
@RestController @RequestMapping("/user") public class UserController { private static final Logger logger = LoggerFactory.getLogger(UserController.class); /** * * application/xml格式报文 * */ @PostMapping(path = "/test", produces = MediaType.APPLICATION_XML_VALUE, consumes = MediaType.APPLICATION_XML_VALUE) public void getUserInfoById(HttpServletRequest request, HttpServletResponse response) throws IOException { String requestBody; String resultBody="hello,wolrd"; byte[] returnByte; if (StringUtils.isNoneEmpty(request.getHeader("Content-encoding"))) { logger.info("报文压缩,需要进行解压"); //业务处理 //返回报文也同样需要进行压缩处理 assemleResponse(request,response,resultBody); } } public static void assemleResponse(HttpServletRequest request, HttpServletResponse response,String resultBody) throws IOException { response.setHeader("Content-Type","application/xml;charset=UTF-8"); response.setHeader("Content-Encoding","gzip"); byte[] returnByte=GzipUtil.compress(resultBody); OutputStream outputStream=response.getOutputStream(); outputStream.write(returnByte); } }
public class GzipUtil { public static String uncompress(byte[] bytes){ if (bytes == null || bytes.length == 0) { return null; } String requestBody=null; ByteArrayInputStream byteArrayInputStream=new ByteArrayInputStream(bytes); GZIPInputStream gzipInputStream = null; try { gzipInputStream = new GZIPInputStream(byteArrayInputStream); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int temp; while ((temp = gzipInputStream.read(buffer)) != -1) { byteArrayOutputStream.write(buffer, 0, temp); } requestBody = new String(byteArrayOutputStream.toByteArray(), StandardCharsets.UTF_8); } catch (IOException e) { e.printStackTrace(); } return requestBody; } public static String uncompress(HttpServletRequest request){ String requestBody=null; int length = request.getContentLength(); try { BufferedInputStream bufferedInputStream = new BufferedInputStream(request.getInputStream()); GZIPInputStream gzipInputStream = new GZIPInputStream(bufferedInputStream); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int temp; while ((temp = gzipInputStream.read(buffer)) != -1) { byteArrayOutputStream.write(buffer, 0, temp); } requestBody = new String(byteArrayOutputStream.toByteArray(), StandardCharsets.UTF_8); } catch (IOException e) { e.printStackTrace(); } return requestBody; } public static byte[] compress(String src){ if (src == null || src.length() == 0) { return null; } ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream(); try { GZIPOutputStream gzipOutputStream=new GZIPOutputStream(byteArrayOutputStream); gzipOutputStream.write(src.getBytes(StandardCharsets.UTF_8)); gzipOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } byte[] bytes=byteArrayOutputStream.toByteArray(); return bytes; } }
补充:java springbooot使用gzip压缩字符串
import lombok.extern.slf4j.Slf4j; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; /** * effect:压缩/解压 字符串 */ @Slf4j public class CompressUtils { /** * effect 使用gzip压缩字符串 * @param str 要压缩的字符串 * @return */ public static String compress(String str) { if (str == null || str.length() == 0) { return str; } ByteArrayOutputStream out = new ByteArrayOutputStream(); GZIPOutputStream gzip = null; try { gzip = new GZIPOutputStream(out); gzip.write(str.getBytes()); } catch (IOException e) { log.error("",e); } finally { if (gzip != null) { try { gzip.close(); } catch (IOException e) { log.error("",e); } } } return new sun.misc.BASE64Encoder().encode(out.toByteArray()); // return str; } /** * effect 使用gzip解压缩 * * @param str 压缩字符串 * @return */ public static String uncompress(String str) { if (str == null) { return null; } ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayInputStream in = null; GZIPInputStream ginzip = null; byte[] compressed = null; String decompressed = null; try { compressed = new sun.misc.BASE64Decoder().decodeBuffer(str); in = new ByteArrayInputStream(compressed); ginzip = new GZIPInputStream(in); byte[] buffer = new byte[1024]; int offset = -1; while ((offset = ginzip.read(buffer)) != -1) { out.write(buffer, 0, offset); } decompressed = out.toString(); } catch (IOException e) { log.error("",e); } finally { if (ginzip != null) { try { ginzip.close(); } catch (IOException e) { } } if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } return decompressed; } }
以上是springboot对压缩请求的处理方法是什么的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

Jasypt介绍Jasypt是一个java库,它允许开发员以最少的努力为他/她的项目添加基本的加密功能,并且不需要对加密工作原理有深入的了解用于单向和双向加密的高安全性、基于标准的加密技术。加密密码,文本,数字,二进制文件...适合集成到基于Spring的应用程序中,开放API,用于任何JCE提供程序...添加如下依赖:com.github.ulisesbocchiojasypt-spring-boot-starter2.1.1Jasypt好处保护我们的系统安全,即使代码泄露,也可以保证数据源的

使用场景1、下单成功,30分钟未支付。支付超时,自动取消订单2、订单签收,签收后7天未进行评价。订单超时未评价,系统默认好评3、下单成功,商家5分钟未接单,订单取消4、配送超时,推送短信提醒……对于延时比较长的场景、实时性不高的场景,我们可以采用任务调度的方式定时轮询处理。如:xxl-job今天我们采

一、Redis实现分布式锁原理为什么需要分布式锁在聊分布式锁之前,有必要先解释一下,为什么需要分布式锁。与分布式锁相对就的是单机锁,我们在写多线程程序时,避免同时操作一个共享变量产生数据问题,通常会使用一把锁来互斥以保证共享变量的正确性,其使用范围是在同一个进程中。如果换做是多个进程,需要同时操作一个共享资源,如何互斥呢?现在的业务应用通常是微服务架构,这也意味着一个应用会部署多个进程,多个进程如果需要修改MySQL中的同一行记录,为了避免操作乱序导致脏数据,此时就需要引入分布式锁了。想要实现分

springboot读取文件,打成jar包后访问不到最新开发出现一种情况,springboot打成jar包后读取不到文件,原因是打包之后,文件的虚拟路径是无效的,只能通过流去读取。文件在resources下publicvoidtest(){Listnames=newArrayList();InputStreamReaderread=null;try{ClassPathResourceresource=newClassPathResource("name.txt");Input

在Springboot+Mybatis-plus不使用SQL语句进行多表添加操作我所遇到的问题准备工作在测试环境下模拟思维分解一下:创建出一个带有参数的BrandDTO对象模拟对后台传递参数我所遇到的问题我们都知道,在我们使用Mybatis-plus中进行多表操作是极其困难的,如果你不使用Mybatis-plus-join这一类的工具,你只能去配置对应的Mapper.xml文件,配置又臭又长的ResultMap,然后再去写对应的sql语句,这种方法虽然看上去很麻烦,但具有很高的灵活性,可以让我们

SpringBoot和SpringMVC都是Java开发中常用的框架,但它们之间有一些明显的差异。本文将探究这两个框架的特点和用途,并对它们的差异进行比较。首先,我们来了解一下SpringBoot。SpringBoot是由Pivotal团队开发的,它旨在简化基于Spring框架的应用程序的创建和部署。它提供了一种快速、轻量级的方式来构建独立的、可执行

1、自定义RedisTemplate1.1、RedisAPI默认序列化机制基于API的Redis缓存实现是使用RedisTemplate模板进行数据缓存操作的,这里打开RedisTemplate类,查看该类的源码信息publicclassRedisTemplateextendsRedisAccessorimplementsRedisOperations,BeanClassLoaderAware{//声明了key、value的各种序列化方式,初始值为空@NullableprivateRedisSe

本文来写个详细的例子来说下dubbo+nacos+Spring Boot开发实战。本文不会讲述太多的理论的知识,会写一个最简单的例子来说明dubbo如何与nacos整合,快速搭建开发环境。
