在XMLHttpRequest请求中使用ArrayBuffer方式,和后端服务器进行二进制的传输交互。
在项目中发现随着用户增长,部分前端功能,请求的数据量越来越大,传统的josn的方式,在下载、序列化时非常慢,因此尝试使用二进制+压缩的方式提升性能。
服务端Java代码:
实体类: public class ByteTest implements Serializable{ private static final long serialVersionUID = 4073873126215417736L; private long id; private String name; private String desc; private double lon; private double lat; public ByteTest(long id, String name, String desc, double lon, double lat) { this.id = id; this.name = name; this.desc = desc; this.lon = lon; this.lat = lat; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public double getLon() { return lon; } public void setLon(double lon) { this.lon = lon; } public double getLat() { return lat; } public void setLat(double lat) { this.lat = lat; } } 控制层: @RestController @RequestMapping("/test") public class TestController { @GetMapping("/testByte") public byte[] testByte() throws Exception{ ByteTest model = new ByteTest(1001,"保安室","abc",133.123456789,22.123456789); byte[] content=JSON.toJSONString(model).getBytes("utf-8"); // return content; byte[] result = new byte[]{}; try { ByteArrayOutputStream bos = new ByteArrayOutputStream(content.length); GZIPOutputStream gzipOS = new GZIPOutputStream(bos); gzipOS.write(content); gzipOS.close(); result = bos.toByteArray(); } catch (IOException e) { e.printStackTrace(); } return result; } }
客户端JS代码:
<script src="js/pako.min.js"></script> <!--引用解压用的pako.mini.js --> <script type="text/javascript"> var oReq = new XMLHttpRequest(); oReq.onload = function(e) { var responseArray = new Uint8Array(this.response); var responseString = new TextDecoder().decode(pako.ungzip(responseArray)); } oReq.open("GET", "http://dev.xx.com:8080/test/testByte", true); oReq.responseType = "arraybuffer"; oReq.send(); </script>