风的旅行

两个系统相互交互,一个抛接口,一个接数据

一、服务器向外抛数据:

1.向外发数据:

我这个是在代码里做了一个定时发送,(我这个是2分钟发一次)

//同步手机和微信数据信息
    @Scheduled(cron = "0 0/2 * * * ?")
    public void SyncWechatData() throws Exception {
        //获取本机的InetAddress实例  
        InetAddress address = InetAddress.getLocalHost();
        //获取IP
        String local = address.getHostAddress();
        String server = FinalData.server;
        if(StringUtil.isNotEmpty(server)){
            if(server.equals(local)){
                
                //这里是写方法的
                Map<String, Object> json = WechatPhoneService.DataTransmit();
                WechatAddressService.SendPostInJosn(json);
                
                System.out.println("同步手机和微信数据信息结束:" + sdf.format(new Date()));
                
            }
        }
    }

2.释放一个接口(在spring-mvc.xml文件中)

<value>PhoneController/wchatJosn.do</value>

3.在数据库中取数据,放在map集合中

 1 /**
 2      * 同步手机和微信数据信息到办公平台(封装)
 3      */
 4     public Map<String, Object> DataTransmit(){
 5         List<PhoneEntity> phones = systemService.findByQueryString(" from PhoneEntity where transfer = '0'");
 6         List<InfoEntity> wechatInfos = systemService.findByQueryString(" from InfoEntity where transfer = '0'");
 7         List<PhoneWxEntity> phoneWxs = systemService.findByQueryString(" from PhoneWxEntity where transfer = '0'");
 8         Map<String, Object> map = new HashMap<String, Object>();
 9         //手机表id串
10         String phoneids = "";
11         int i =1;
12         if (phones.size() > 0) {
13             List<PhoneEntity> phones1 = new ArrayList<tPhoneEntity>();
14             //只取1000条数据
15             for (PhoneEntity phone : phones) {
16                 //把取到的数据放在list集合中
17                 phones1.add(phone);
18                 if (i > 1000) {
19                     break;
20                 }
21                 i++;
22             }
23             map.put("phone", phones1);
24             for (PhoneEntity phone : phones) {
25                 if (StringUtils.isNotEmpty(phoneids)) {
26                     phoneids = phoneids + ",'" + phone.getId() + "'";
27                 }else {
28                     phoneids = "'" + phone.getId() + "'";
29                 }
30             }
31         }
32         //微信表id串
33         String infoids = "";
34         if (wechatInfos.size() > 0) {
35             i = 1;
36             List<InfoEntity> wechatInfos1 = new ArrayList<InfoEntity>();
37             //只取1000条数据
38             for (InfoEntity wechatInfo : wechatInfos) {
39                 //把取到的数据放在list集合中
40                 wechatInfos1.add(wechatInfo);
41                 if (i > 1000) {
42                     break;
43                 }
44                 i++;
45             }
46             map.put("wechatInfo", wechatInfos1);
47             for (InfoEntity wechatInfo : wechatInfos) {
48                 if (StringUtils.isNotEmpty(infoids)) {
49                     infoids = infoids + ",'" + wechatInfo.getId() + "'";
50                 }else {
51                     infoids = "'" + wechatInfo.getId() + "'";
52                 }
53             }
54         }
55         //手机微信关系表id串
56         String phoneWxids = "";
57         if (phoneWxs.size() > 0) {
58             i = 1;
59             List<PhoneWxEntity> phoneWxs1 = new ArrayList<PhoneWxEntity>();
60             //只取1000条数据
61             for (PhoneWxEntity phoneWx : phoneWxs) {
62                 //把取到的数据放在list集合中
63                 phoneWxs1.add(phoneWx);
64                 if (i > 1000) {
65                     break;
66                 }
67                 i++;
68             }
69             map.put("phoneWx", phoneWxs1);
70             for (PhoneWxEntity phoneWx : phoneWxs) {
71                 if (StringUtils.isNotEmpty(phoneWxids)) {
72                     phoneWxids = phoneWxids + ",'" + phoneWx.getId() + "'";
73                 } else {
74                     phoneWxids = "'" + phoneWx.getId() + "'";
75                 }
76             }
77         }
78         JSONArray arry=JSONArray.fromObject(map);
79         String str = arry.toString();
80         Map<String, Object> maps = new HashMap<String, Object>();
81         maps.put("json", str);
82         maps.put("phoneids", phoneids);
83         maps.put("infoids", infoids);
84         maps.put("phoneWxids", phoneWxids);
85         return maps;
86     }

4.把返回的map集合中json串取出来发送到另一个服务器上,map集合中剩下的拼接好的id串等返回一个ok值后,在相应的表中把发送过的数据改为已发送状态(这里边要注意:当数据可中的数据添加、修改时要把状态改为为发送状态)

/**
     * 把传过来的数据用接口发送出去,把拼接的id等返回ok后把发送的数据标记为已发送状态
     */
    @Override
    public void SendPostInJosn(Map<String, Object> map){
        String url1 = "域名/服务器名称/控制层/方法名.do";
        String json = map.get("json").toString();//json串
        String phoneids = map.get("phoneids").toString();//电话表id串
        String infoids = map.get("infoids").toString();//微信表id串
        String phoneWxids = map.get("phoneWxids").toString();//手机微信关系表id串
        String result="";
        PrintWriter out = null;  
        BufferedReader in = null; 
        URL url=null;
         try {
             url = new URL(url1);
             URLConnection connect = url.openConnection();
             connect.setRequestProperty("content-type","application/x-www-form-urlencoded;charset=utf-8");
             connect.setRequestProperty("method","POST");
             byte[] bytes= json.getBytes("utf-8") ;
             connect.setDoOutput(true);  
             connect.setDoInput(true);  
             
             out = new PrintWriter(connect.getOutputStream());  
             // 发送请求参数  
             out.print("datas="+json);
             out.flush();  
             //数据交互返回值200/400/500...
             CloseableHttpClient httpClient = HttpClients.createDefault();
             HttpPost post = new HttpPost(url1);
             CloseableHttpResponse response = null;
             StringEntity entitys = new StringEntity(json);
             post.setEntity(entitys);
             response = httpClient.execute(post);
             System.out.println(response.getStatusLine().getStatusCode());
             // 定义BufferedReader输入流来读取URL的响应  
             if (response != null && response.getStatusLine().getStatusCode() == 200) {
                 in = new BufferedReader(new InputStreamReader(connect.getInputStream()));
                 String line = "";  
                 while ((line = in.readLine()) != null) {  
                     result +=  line;  
                     if ("ok".equals(result)) {
                          PhoneService.updateTransferData(phoneids,infoids,phoneWxids);
                    }
                 }   
            }else {
                System.out.println("数据交互出错,请检查办公平台服务是否开启?出错原因报:"+response.getStatusLine().getStatusCode());
            }
         } catch (Exception e) {
             System.out.println("数据交互出错,请检查办公平台服务是否开启???");
             e.printStackTrace();
         }
    }

5.把拼接好的id串在数据库中检索出对应的数据再把数据改为已发送状态

/**
     * 把电话表、微信表、手机与微信关系表中的是否传送字段改为“1”;(否:0;是:1)
     */
    @Override
    public void updateTransferData(String phoneids, String infoids, String phoneWxids) {
        //修改电话表中的字段是否传送
        if (StringUtils.isNotEmpty(phoneids)) {
            String sql1 = "update phone set transfer = '1' where id in ("+phoneids+")";
            systemService.updateBySqlString(sql1);
        }
        //修改微信表中的字段是否传送
        if (StringUtils.isNotEmpty(infoids)) {
            String sql2 = "update info set transfer = '1' where id in ("+infoids+")";
            systemService.updateBySqlString(sql2);
        }
        //修改手机与微信关系表中的字段是否传送
        if (StringUtils.isNotEmpty(phoneWxids)) {
            String sql3 = "update phone_wx set transfer = '1' where id in ("+phoneWxids+")";
            systemService.updateBySqlString(sql3);
        }
    }

二、服务器接收数据

1.接受接口所传过来的数据(个人认为这个接收方法就像是在一个实体中的方法调用)

 1 /**
 2      * 接收方法传过来的json串
 3      * @param request
 4      * @param response
 5      * @throws Exception 
 6      */
 7     @RequestMapping(value = "/wchatJosn")
 8     public void wchatJosn(HttpServletRequest request, HttpServletResponse response) throws Exception{
 9         String result = "";
10         boolean isPost = request.getMethod().toLowerCase().equals("post");
11         String json = request.getParameter("datas");
12         
13         PrintWriter wirte = null;
14         wirte = response.getWriter();
15         response.setCharacterEncoding("UTF-8");
16         response.setContentType("text/html;charset=UTF-8");
17         if (isPost) {
18             //应答接口,包括注册、接收数据等 使用post协议
19             result = PhoneService.wchatJosnAddress(json);
20             wirte.print(result);
21         }else{
22             wirte.print("");
23         }
24         wirte.flush();            
25         wirte.close();
26     }

2.把json串解析  然后根据不同的表数据再把不同的数据放在自己对应的数据库中(这个是一个批处理的数据存储和修改的方法)

  1 /**
  2       * 把传过来的数据放到数据库中
  3       * 正确时返回“ok”
  4       * @throws ClassNotFoundException 
  5       */
  6     @Override
  7     public String wchatJosnAddress(String json) throws Exception {
  8         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  9         String str = "";
 10         int i = 0;
 11         //手机表
 12         String phones = "";
 13         //微信表
 14         String wechatInfos = "";
 15         //手机微信表关系表
 16         String phoneWxs = "";
 17         if (StringUtils.isNotEmpty(json)) {
 18             json = json.substring(1,json.length()-1);
 19         }
 20         JSONObject objects=JSONObject.fromObject(json);
 21         JSONArray array1 = null;
 22         JSONArray array2 = null;
 23         JSONArray array3 = null;
 24         if (null != objects) {
         //判断json传过来的数据中是否在map中有这个键值对
25 if (StringUtils.isNotEmpty(objects.optString("phone"))) { 26 array1 = objects.getJSONArray("phone"); 27 phones = array1.toString(); 28 } 29 if (StringUtils.isNotEmpty(objects.optString("wechatInfo"))) { 30 array2 = objects.getJSONArray("wechatInfo"); 31 wechatInfos = array2.toString(); 32 } 33 if (StringUtils.isNotEmpty(objects.optString("phoneWx"))) { 34 array3 = objects.getJSONArray("phoneWx"); 35 phoneWxs = array3.toString(); 36 } 37 } 38 //数据库配置 这个是我之前自己封装好的在页面中直接修改服务器id 39 String[] add = DatabaseaddressController.getDatabasePassworld().split(","); 40 Connection conn; 41 Class.forName("com.mysql.jdbc.Driver"); 42 String pwd = ""; 43 if (add.length<=2) { 44 pwd = ""; 45 }else{ 46 pwd = add[2]; 47 } 48 49 conn = DriverManager.getConnection(add[0], add[1], pwd); 50 conn.setAutoCommit(false); 51 // 保存当前自动提交模式 52 boolean autoCommit = conn.getAutoCommit(); 53 // 关闭自动提交 54 conn.setAutoCommit(false); 55 Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); 56 //声明变量手机唯一标识拼接字符串用于sql语句 57 String imeis = ""; 58 Map<String, PhoneEntity> maps = new HashMap<String, WechatPhoneEntity>(); 59 if (StringUtil.isNotEmpty(phones)) { 60 JSONArray arrays = JSONArray.fromObject(phones); 61 System.out.println("手机数据存储开始执行操作!!!!"); 62 for (Object array : arrays) { 63 JSONObject object=JSONObject.fromObject(array); 64 PhoneEntity phone = (PhoneEntity)JSONObject.toBean(object,PhoneEntity.class); 65 String imei = phone.getImei(); 66 if (StringUtils.isNumeric(imeis)) { 67 imeis = imeis + ",'" + imei + "'"; 68 }else { 69 imeis = "'" + imei + "'"; 70 } 71 //把手机表用手机唯一标识作为键放在map集合中 72 maps.put(imei, phone); 73 } 74 } 75 76 //把微信表数据存储在数据库 (这个方法就不写了 其实就是一个数据存储到数据库中的方法 和下边这个一样) 77 // boolean tu = getWechatInfos(wechatInfos); 78 if (tu) { 79 //把微信表数据存储在数据库 80 // boolean tus = getWechatInfoWxs(phoneWxs); 81 if (tus) { 82 if (StringUtil.isNotEmpty(phones)) { 83 String hql = " from PhoneEntity where imei in("+imeis+")"; 84 List<PhoneEntity> Phones1 = systemService.findByQueryString(hql); 85 if (Phones1.size() >0) { 86 for (PhoneEntity Phone : Phones1) { 87 String imei1 = Phone.getImei(); 88 //在maps集合中把手机实体表数据取出 89 PhoneEntity phone2 = maps.get(Phone.getImei()); 90 if (null != phone2) { 91 stmt.addBatch("update phone set create_date = '"+sdf.format(phone2.getCreateDate())+"',imei = '"+phone2.getImei()+"'" 92 + ",type = '"+phone2.getType()+"',status = '"+phone2.getStatus()+"',is_root = '"+phone2.getIsRoot()+"'" 93 + ",soft_version = '"+phone2.getSoftVersion()+"',is_info_plugin = '"+phone2.getIsInfoPlugin()+"',phone_os = '"+phone2.getPhoneOs()+"'" 94 + ",brand = '"+phone2.getBrand()+"',only_num = '"+phone2.getOnlyNum()+"' where id = '"+Phone.getId()+"'"); 95 96 if (i % 1000 == 0 || i == Phones1.size()) { 97 try { 98 stmt.executeBatch(); 99 stmt.clearBatch(); 100 conn.commit(); 101 } catch (Exception e) { 102 conn.close(); 103 e.printStackTrace(); 104 } 105 } 106 i = i + 1; 107 } 108 //删除掉maps集合中已经把数据放在数据库手机表中的数据 109 maps.remove(imei1); 110 } 111 } 112 if (maps.size() > 0) { 113 i = 1; 114 //把maps集合循环遍历 115 for (String key : maps.keySet()) { 116 Entity phone = maps.get(key); 117 if (null != phone) { 118 stmt.addBatch("insert into phone set id = '"+phone.getId()+"',create_date = '"+sdf.format(phone.getCreateDate())+"',imei = '"+phone.getImei()+"'" 119 + ",person_id = null,person_name = null,dept_id = null" 120 + ",dept_name = null,type = '"+phone.getType()+"',status = '"+phone.getStatus()+"',is_root = '"+phone.getIsRoot()+"'" 121 + ",soft_version = '"+phone.getSoftVersion()+"',is_info_plugin = '"+phone.getIsInfoPlugin()+"',phone_os = '"+phone.getPhoneOs()+"'" 122 + ",brand = '"+phone.getBrand()+"',only_num = '"+phone.getOnlyNum()+"'"); 123 if (i % 1000 == 0 || i == maps.size()) { 124 try { 125 stmt.executeBatch(); 126 stmt.clearBatch(); 127 conn.commit(); 128 } catch (Exception e) { 129 conn.close(); 130 e.printStackTrace(); 131 } 132 } 133 } 134 i = i + 1; 135 } 136 } 137 conn.close(); 138 //成功返回ok 139 str = "ok"; 140 }else { 141 str = "ok"; 142 } 143 }else { 144 System.out.println("数据存储结束执行失败???"); 145 } 146 }else { 147 System.out.println("数据存储结束执行失败???"); 148 } 149 System.out.println("数据存储结束执行操作!!!!"); 150 return str; 151 }

 

posted on 2018-12-17 15:59  风的旅行  阅读(943)  评论(0编辑  收藏  举报

导航