【PostgreSQL保存】java.io.IOException: Tried to send an out-of-range integer as a 2-byte value 问题分析+解决方法
生活随笔
收集整理的這篇文章主要介紹了
【PostgreSQL保存】java.io.IOException: Tried to send an out-of-range integer as a 2-byte value 问题分析+解决方法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.問題分析
項目里有一個從MySQL導入PostgreSQL然后利用GIS相關插件計算空間數據的定時任務,上線某地市沒有任何問題,后期上線到一個大城市,定時任務報錯 java.io.IOException: Tried to send an out-of-range integer as a 2-byte value: xxxxx,這里貼一下源碼:
public void sendInteger2(int val) throws IOException {if (val >= -32768 && val <= 32767) {this.int2Buf[0] = (byte)(val >>> 8);this.int2Buf[1] = (byte)val;this.pgOutput.write(this.int2Buf);} else {throw new IOException("Tried to send an out-of-range integer as a 2-byte value: " + val);}}大白話解釋是:試圖以2字節值的形式發送一個超出范圍的整數 xxxxx,第一時間我沒有反應過來,查詢了MySQL數據庫的記錄數,也就1w+條,怎么也超不過32767啊,后來才知道32767是PostgreSQL對于SQL語句的參數數量限制,當時往PostgreSQL入庫的SQL類似這種:
<insert id="batchInsertXXX" parameterType="xxx.common.persistence.model.xxxGis">insert into xxx_gis (id, name, index, geom) values<foreach collection="list" index="index" item="item" separator=",">( #{item.id}, #{item.name}, #{item.index}, ST_GeomFromText(#{item.geom}) )</foreach> </insert>然后一算1w+*4可不超過32767嘛!
2.解決方法代碼
我查詢了一下網絡,遇到這個問題的小伙伴還是不少的,大家的方法就是分批導入,代碼如下。
public void insertBatch(List<Object> list){int numberBatch = 32767; // PostgreSQL每一次插入最大參數量double number = list.size() * 4.0 / numberBatch; // 4.0是每條插入語句的參數個數int n = ((Double)Math.ceil(number)).intValue(); for(int i = 0; i < n; i++){int end = numberBatch * (i + 1);if(end > list.size()){ end = list.size(); }List<Object> insertList = list.subList(numberBatch * i , end);// 這里調用批量插入程程序將insertList保存}}這個是臨時解決方案,里邊把每條插入語句的參數個數值固定了,可以將這個方法封裝,然后把參數個數參數化。
總結
以上是生活随笔為你收集整理的【PostgreSQL保存】java.io.IOException: Tried to send an out-of-range integer as a 2-byte value 问题分析+解决方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Layui上传文件时choose事件只触
- 下一篇: Neo4j【付诸实践 01】Spring