HttpUtils的使用、定时推送数据到不同服务的数据库

  实现定时推送数据到不同服务的数据库

首先需要准备一个HttpUtils类:

public class HttpUtils {


    public static String doPost(String URL,String jsonStr){
        OutputStreamWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        HttpURLConnection conn = null;
        try{
            URL url = new URL(URL);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            //发送POST请求必须设置为true
            conn.setDoOutput(true);
            conn.setDoInput(true);
            //设置连接超时时间和读取超时时间
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(10000);
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Accept", "application/json");
            //获取输出流
            out = new OutputStreamWriter(conn.getOutputStream());
            out.write(jsonStr);
            out.flush();
            out.close();
            //取得输入流,并使用Reader读取
            if (200 == conn.getResponseCode()){
                in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
                String line;
                while ((line = in.readLine()) != null){
                    result.append(line);
                    System.out.println(line);
                }
            }else{
                System.out.println("ResponseCode is an error code:" + conn.getResponseCode());
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try{
                if(out != null){
                    out.close();
                }
                if(in != null){
                    in.close();
                }
            }catch (IOException ioe){
                ioe.printStackTrace();
            }
        }
        return result.toString();
    }

    public static String doGet(String URL){
        HttpURLConnection conn = null;
        InputStream is = null;
        BufferedReader br = null;
        StringBuilder result = new StringBuilder();
        try{
            //创建远程url连接对象
            URL url = new URL(URL);
            //通过远程url连接对象打开一个连接,强转成HTTPURLConnection类
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            //设置连接超时时间和读取超时时间
            conn.setConnectTimeout(15000);
            conn.setReadTimeout(60000);
            conn.setRequestProperty("Accept", "application/json");
            //发送请求
            conn.connect();
            //通过conn取得输入流,并使用Reader读取
            if (200 == conn.getResponseCode()){
                is = conn.getInputStream();
                br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
                String line;
                while ((line = br.readLine()) != null){
                    result.append(line);
                    System.out.println(line);
                }
            }else{
                System.out.println("ResponseCode is an error code:" + conn.getResponseCode());
            }
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            try{
                if(br != null){
                    br.close();
                }
                if(is != null){
                    is.close();
                }
            }catch (IOException ioe){
                ioe.printStackTrace();
            }
            conn.disconnect();
        }
        return result.toString();
    }


    public static void main(String[] args) throws Exception {

        System.out.println("Testing 1 - Do Http GET request");
        doGet("http://localhost:8080/getTest?a=111&b=2222");
        System.out.println("\nTesting 2 - Do Http POST request");
        Map map = new HashMap();
        map.put("jineng","唱跳rap");
        doPost("http://localhost:8080/postTest?a=111", JSONObject.toJSONString(map));

//        System.out.println("=====================");
//        doPost("http://localhost:8080/postTest",JSONObject.toJSONString(new))
    }

}

 

然后需要在定时任务类MainTask中设置定时线程,利用Spring注解@Scheduled实现定时推送,方法中的url参数为依赖服务的对应Controller函数的映射路径

***注意:需要传递一个Json格式的字符串,注意转换,在接收时需要转换成所需Map或List***

/**
     * 每月将数据放入mysql中间表eng_person_info
     */
    @Scheduled(cron = "0 0 0 1 * ?")
    public void sendInfo() {
        Thread thread = new Thread(
                () -> {
                    List<EngPersonInfo> infoList = null;
                    try {
                        infoList = sendAttendanceService.getLastMonthInfo();
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    String s = JSONArray.toJSONString(infoList);
                    log.info("------------------------------------------------------------------------------------------");
                    log.info(s);
                    HttpUtils.doPost("http://localhost:8000/postInfo", s);
                }
        );
        thread.start();
    }

 

一个cron表达式有至少6个(也可能7个)有空格分隔的时间元素。

按顺序依次为

  • 秒(0~59)
  • 分钟(0~59)
  • 小时(0~23)
  • 天(月)(0~31,但是你需要考虑你月的天数)
  • 月(0~11)
  • 天(星期)(1~7 1=SUN 或 SUN,MON,TUE,WED,THU,FRI,SAT)
  • 年份(1970-2099)——@Scheduled是不支持的,spring quartz支持

其中每个元素可以是一个值(如6),一个连续区间(9-12),一个间隔时间(8-18/4)(/表示每隔4小时),一个列表(1,3,5),通配符。由于"月份中的日期"和"星期中的日期"这两个元素互斥的,必须要对其中一个设置?.

0 0 10,14,16 * * ? 每天上午10点,下午2点,4点

0 0/30 9-17 * * ? 朝九晚五工作时间内每半小时

0 0 12 ? * WED 表示每个星期三中午12点

"0 0 12 * * ?" 每天中午12点触发

"0 15 10 ? * *" 每天上午10:15触发

"0 15 10 * * ?" 每天上午10:15触发

"0 15 10 * * ? *" 每天上午10:15触发

"0 15 10 * * ? 2005" 2005年的每天上午10:15触发

"0 * 14 * * ?" 在每天下午2点到下午2:59期间的每1分钟触发

"0 0/5 14 * * ?" 在每天下午2点到下午2:55期间的每5分钟触发

"0 0/5 14,18 * * ?" 在每天下午2点到2:55期间和下午6点到6:55期间的每5分钟触发

"0 0-5 14 * * ?" 在每天下午2点到下午2:05期间的每1分钟触发

"0 10,44 14 ? 3 WED" 每年三月的星期三的下午2:10和2:44触发

"0 15 10 ? * MON-FRI" 周一至周五的上午10:15触发

"0 15 10 15 * ?" 每月15日上午10:15触发

"0 15 10 L * ?" 每月最后一日的上午10:15触发

"0 15 10 ? * 6L" 每月的最后一个星期五上午10:15触发

"0 15 10 ? * 6L 2002-2005" 2002年至2005年的每月的最后一个星期五上午10:15触发

"0 15 10 ? * 6#3" 每月的第三个星期五上午10:15触发

有些子表达式能包含一些范围或列表

例如:子表达式(天(星期))可以为 “MON-FRI”,“MON,WED,FRI”,“MON-WED,SAT”

“*”字符代表所有可能的值

因此,“*”在子表达式(月)里表示每个月的含义,“*”在子表达式(天(星期))表示星期的每一天

“/”字符用来指定数值的增量

例如:在子表达式(分钟)里的“0/15”表示从第0分钟开始,每15分钟

在子表达式(分钟)里的“3/20”表示从第3分钟开始,每20分钟(它和“3,23,43”)的含义一样

“?”字符仅被用于天(月)和天(星期)两个子表达式,表示不指定值

当2个子表达式其中之一被指定了值以后,为了避免冲突,需要将另一个子表达式的值设为“?”

“L” 字符仅被用于天(月)和天(星期)两个子表达式,它是单词“last”的缩写

但是它在两个子表达式里的含义是不同的。

在天(月)子表达式中,“L”表示一个月的最后一天

在天(星期)自表达式中,“L”表示一个星期的最后一天,也就是SAT

如果在“L”前有具体的内容,它就具有其他的含义了

例如:“6L”表示这个月的倒数第6天,“FRIL”表示这个月的最一个星期五

注意:在使用“L”参数时,不要指定列表或范围,因为这会导致问题

868cde2dbc0c4c2c859e399ee7adf1de

 

 

依赖服务中的Controller层负责接受推送过来的数据,Mapping路径需要对应上面的代码

 

@PostMapping("/postRecord")
    public void postTest(@RequestBody String record) {
        System.out.println(record);
        List<EngPersonRecord> engPersonRecordList = JSONArray.parseArray(record, EngPersonRecord.class);
        System.out.println(engPersonRecordList);
        for (EngPersonRecord engPersonRecord : engPersonRecordList) {
            engPersonRecordMapper.insertOne(engPersonRecord);
        }

    }

 

 

 

 

posted @ 2021-07-08 14:41  onecyl  阅读(362)  评论(0编辑  收藏  举报