数据库中的数据,按批次发送给接口

//工具类方法封装

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;

import com.hjsj.domain.Commodity;
import com.hjsj.domain.Upfile;

public class HttpFa2 {

/**
 * post请求
 *
 * @param url
 * @param json
 * @return
 */

public static JSONObject doPost(String method, JSONObject date,HttpServletRequest request) {
    HttpClient client = HttpClients.createDefault();
    // 将接口地址和接口方法拼接起来
    String url = "http://shopweb2.hanshows.com:58080/shopweb-17-test/" + method;
    HttpPost post = new HttpPost(url);
    JSONObject response = null;
    try {
        StringEntity s = new StringEntity(date.toString());
        s.setContentEncoding("UTF-8");
        s.setContentType("application/json");
        post.setEntity(s);
        post.addHeader("content-type", "text/xml");
        // 调用Fa接口
        HttpResponse res = client.execute(post);
        //String response1 = EntityUtils.toString(res.getEntity());
        //System.out.println("************");
        //System.out.println(response1);
        if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            //HttpEntity entity = res.getEntity();
            //String result = EntityUtils.toString(res.getEntity());// 返回json格式:
            response = JSONObject.fromObject(res.getEntity());
            //System.out.println(response);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return response;
    }
//批次商品不大于1000
public static JSONObject encapsulaCommodity(List<Commodity> commodities,Upfile upfile) {

    ArrayList<JSONObject> array = new ArrayList<JSONObject>();
    JSONObject obj = new JSONObject();
    JSONObject obj1 = null;
    for(Iterator<Commodity> iterators = commodities.iterator();iterators.hasNext();){
        obj1= new JSONObject();
        Commodity commodity = (Commodity) iterators.next();//获取当前遍历的元素,指定为Example对象
        obj1.element("sku", commodity.getSku());
        obj1.element("customerStoreCode", upfile.getSiteCode());
        obj1.element("itemName", commodity.getItemName());
        obj1.element("price1", commodity.getPrice1());
        array.add(obj1);
    }
    obj.element("customerStoreCode", upfile.getSiteCode());
    obj.element("storeCode", upfile.getSiteCode());
    obj.element("batchNo", upfile.getFileNo()+"-1");
    obj.element("batchSize", commodities.size());
    obj.element("items", array);
    
    //System.out.println("data="+obj.toString());
    // 发送 POST 请求 调用接口 参数1 接口名(项目后 不带/) 参数二 json对象 参数三 request
    //JSONObject sr = HttpFa2.doPost("integration", obj, request);
    return obj;
}
//批次商品大于1000
public static List<JSONObject> encapsulaCommoditys(List<Commodity> commodities,Upfile upfile) {

    ArrayList<JSONObject> array = new ArrayList<JSONObject>();
    ArrayList<JSONObject> array1 = new ArrayList<JSONObject>();
    
    JSONObject obj = new JSONObject();
    JSONObject objs = new JSONObject();
    JSONObject obj1 = null;
    JSONObject obj2 = null;
    
    List<Commodity> commodities2 = commodities.subList(0, 1000);
    List<Commodity> commodities3 = commodities.subList(1000, commodities.size());
    //批次处理第一条
    for(Iterator<Commodity> iterators = commodities2.iterator();iterators.hasNext();){
        obj1= new JSONObject();
        Commodity commodity = (Commodity) iterators.next();//获取当前遍历的元素,指定为Example对象
        obj1.element("sku", commodity.getSku());
        obj1.element("customerStoreCode", upfile.getSiteCode());
        obj1.element("itemName", commodity.getItemName());
        obj1.element("price1", commodity.getPrice1());
        array.add(obj1);
    }
    obj.element("customerStoreCode", upfile.getSiteCode());
      obj.element("storeCode", upfile.getSiteCode());
      obj.element("batchNo", upfile.getFileNo()+"-1");
      obj.element("batchSize", commodities2.size());
      obj.element("items", array);
    //批次处理第二条
        for(Iterator<Commodity> iterators = commodities3.iterator();iterators.hasNext();){
            obj2= new JSONObject();
            Commodity commodity = (Commodity) iterators.next();//获取当前遍历的元素,指定为Example对象
            obj2.element("sku", commodity.getSku());
            obj2.element("customerStoreCode", upfile.getSiteCode());
            obj2.element("itemName", commodity.getItemName());
            obj2.element("price1", commodity.getPrice1());
            array1.add(obj2);
        }
        objs.element("customerStoreCode", upfile.getSiteCode());
        objs.element("storeCode", upfile.getSiteCode());
        objs.element("batchNo", upfile.getFileNo()+"-2");
        objs.element("batchSize", commodities3.size());
        objs.element("items", array1);

        List<JSONObject> objects = new ArrayList<JSONObject>();
        objects.add(obj);objects.add(objs);
    return objects;
}

}

//Controller业务


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;
import net.sf.json.util.CycleDetectionStrategy;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import org.json.JSONObject;

import com.hjsj.common.JsonCrudModel;
import com.hjsj.domain.Commodity;
import com.hjsj.domain.Synchro_record;
import com.hjsj.domain.Upfile;
import com.hjsj.domain.User;
import com.hjsj.utils.HttpClientUtil;
import com.hjsj.utils.HttpFa2;
import com.hjsj.utils.PasswordUtils;
import com.sun.org.apache.bcel.internal.generic.NEW;
@Controller("SynchronizationController")
@RequestMapping(SynchronizationController.Location)
public class SynchronizationController extends BaseController{
    public static final String Location = "/web_file";
    
        @RequestMapping(value="/synchro",method=RequestMethod.POST)
        public @ResponseBody JsonCrudModel<String> synchro(@RequestBody String data,HttpServletRequest request,HttpServletResponse response) throws Exception{    
            final JsonCrudModel<String> result = new JsonCrudModel<String>();
            
            System.out.println("来了");
            try {
                JSONObject jObj = new JSONObject(data);  
                //System.out.println(jObj);
                String fileId = jObj.getString("fileId");
                Upfile upfile = upfileService.getUpFileId(Integer.parseInt(fileId));
                if(upfile!=null && upfile.getFileState().equals("1")){
                    List<Commodity> commodities = commodityService.getAllCommodityNo(upfile.getFileNo());
                    
                    if(commodities.size()<1000){
                    //同步数据小于1000
                        net.sf.json.JSONObject object = HttpFa2.encapsulaCommodity(commodities, upfile);
                        net.sf.json.JSONObject object2 = HttpFa2.doPost("integration", object, request);
                        String resultCode = object2.getString("resultCode");
                        if(resultCode.equals("0")){
                            //插入数据库操作
                            //插入数据库
                            Synchro_record record = new Synchro_record();
                            record.setFileNo(upfile.getFileNo());
                            record.setBatchSize(commodities.size());
                            record.setBatchNo(upfile.getFileNo()+"-1");
                            record.setState("0");
                            int relt = synchro_recordService.addRecord(record);
                                if(relt>0){
                                }else{
                                    result.setCode(JsonCrudModel.Status_Business);
                                    result.setMachine("数据库同步失败,请重试或联系管理员");
                                    return result;
                                }
                        }else if(resultCode.equals("1")){
                            result.setCode(JsonCrudModel.Status_Business);
                            result.setMachine("未创建对应的商店");
                            return result;
                        }else{
                            //同步失败
                            result.setCode(JsonCrudModel.Status_Business);
                            result.setMachine("同步失败,请重试或联系管理员");
                            return result;
                        }
                    }else{
                    //同步数据大于1000
                    List<net.sf.json.JSONObject> object = HttpFa2.encapsulaCommoditys(commodities, upfile);
                    List<Integer> size = new ArrayList<Integer>();size.add(1000);size.add((commodities.size()-1000));
                    int j=0;
                    for(int i = 0 ; i < object.size() ; i++){
                        j=j+1;
                        net.sf.json.JSONObject object2 = HttpFa2.doPost("integration", object.get(i), request);
                        String resultCode = object2.getString("resultCode");
                        if(resultCode.equals("0")){
                            //插入数据库
                            Synchro_record record = new Synchro_record();
                            record.setFileNo(upfile.getFileNo());
                            record.setBatchSize(size.get(i));
                            record.setBatchNo(upfile.getFileNo()+"-"+j);
                            record.setState("0");
                            int relt = synchro_recordService.addRecord(record);
                                if(relt>0){
                                }else{
                                    result.setCode(JsonCrudModel.Status_Business);
                                    result.setMachine("数据库同步失败,请重试或联系管理员");
                                    return result;
                                }
                            }else if(resultCode.equals("1")){
                                result.setCode(JsonCrudModel.Status_Business);
                                result.setMachine("未创建对应的商店");
                                return result;
                            }else{
                                //同步失败
                                result.setCode(JsonCrudModel.Status_Business);
                                result.setMachine("同步失败,请重试或联系管理员");
                                return result;
                            }
                        }
                    }
                }else if (upfile!=null && upfile.getFileState().equals("2")) {
                    result.setCode(JsonCrudModel.Status_Business);
                    result.setMachine("该数据已同步");
                    return result;
                }
                
                result.setCode(JsonCrudModel.Status_Success);
            } catch (Exception e) {
                result.setMachine("程序异常");
                log.error("FileController method synchro bug", e);
                e.printStackTrace();
            }
            return result;
        }

}

请尊重原创,借鉴原博主--->https://blog.csdn.net/qq346859029/article/details/52485506

猜你喜欢

转载自blog.csdn.net/weixin_42102798/article/details/80661083