使用Spring定时器定时推送数据

背景

公司项目需要写一个定时任务,放在用户本地的系统里,定时访问用户的数据库,把需要推送的数据通过访问上一篇文章的POST接口推送到中央数据库。

定时器编写

1.在配置文件里添加相关配置

​
<!-- 定时器开关 -->
<task:annotation-driven />
    
<!-- 自动扫描的包名 -->
<bean id="myTaskXml" class="定时方法所在的类的完整类名"></bean>
<task:scheduled-tasks>
	<task:scheduled ref="myTaskXml" method="appInfoAdd" cron="*/5 * * * * ?"/>
</task:scheduled-tasks>

​

上面的代码设置的是每5秒执行一次appInfoAdd方法,cron字段表示的是时间的设置,分为:秒,分,时,日,月,周,年。时间的设置可以参考这里

2.定时方法的编写

Logger log = Logger.getLogger(TimerTask.class);;
public void apiInfoAdd(){
    InputStream in = TimerTask.class.getClassLoader().getResourceAsStream("/system.properties");
    Properties prop = new Properties();
    try {
		prop.load(in);
	} catch (IOException e) {
		e.printStackTrace();
	}
    String key = prop.getProperty("DLKEY");
    log.info("key--" + key);
    //锁数据操作
    List<GbEsealInfo> list = this.esealService.loadBySendFlag("0");   	
    if (list == null) {
    	log.info("没有需要推送的锁数据");
    }else{
    	JsonObject json = new JsonObject();
        JsonArray ja = new JsonArray();
        json.add("esealList", ja);
        for(int i = 0; i < list.size(); i++) {
        	GbEntInfo ent = this.entService.loadByPk(list.get(i).getEntId());
            JsonObject esealJson = getEsealJson(list.get(i), ent);        	
            ja.add(esealJson);	
        }
        String data = json.toString();
        log.info("锁数据--" + data);
        HttpDeal hd = new HttpDeal();
        Map<String,String> map = new HashMap<String, String>();
        map.put("key",key);
        map.put("data", data);
        hd.post(prop.getProperty("ESEALURL"), map);
        log.info(hd.responseMsg);
        JsonObject returnData = new JsonParser().parse(hd.responseMsg).getAsJsonObject();
        if (("\"10000\"").equals(returnData.get("code").toString())){
          	log.info("锁数据推送成功");
            for(int i = 0; i < list.size(); i++){
              	list.get(i).setSendFlag("1");
              	int res = this.esealService.updateSelectiveByPk(list.get(i));
              	if(res == 0){
              	    log.info("第" + (i+1) + "条锁数据的sendflag字段的状态值修改失败");
              	    continue;
              	}
            }
        }
   }

这个过程包括读取配置文件里的key,从数据库读取数据(根据数据的字段判断是否需要推送),使用GSON把数据拼装成上一篇文章里的data的形式data={"esealList":[{},{},{}]},使用HttpClient执行带参数的POST方法,访问POST接口,根据返回信息判断状态。

3.HttpClient里的带参POST方法

public class HttpDeal {
    public String responseMsg;
	
	public String post(String url,Map<String, String> params){
		//实例化httpClient
		CloseableHttpClient httpclient = HttpClients.createDefault();
		//实例化post方法
		HttpPost httpPost = new HttpPost(url); 
		//处理参数
		List<NameValuePair> nvps = new ArrayList <NameValuePair>();  
        Set<String> keySet = params.keySet();  
	    for(String key : keySet) {  
	        nvps.add(new BasicNameValuePair(key, params.get(key)));  
	    }  
		//结果
		CloseableHttpResponse response = null;
		String content="";
		try {
			//提交的参数
			UrlEncodedFormEntity uefEntity  = new UrlEncodedFormEntity(nvps, "UTF-8");
			//将参数给post方法
			httpPost.setEntity(uefEntity);
			//执行post方法
			response = httpclient.execute(httpPost);
			if(response.getStatusLine().getStatusCode()==200){
				content = EntityUtils.toString(response.getEntity(),"utf-8");
				responseMsg = content;
				//System.out.println(content);
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} 
		return content;
	}
	public static void main(String[] args) {
		HttpDeal hd = new HttpDeal();
        Map<String,String> map = new HashMap();
        map.put("key","5c07db6e22c780e76824c88b2e65e9d9");
        map.put("data", "{'esealList':[{'esealId':'1','entName':'q','entName':企业,'id':'qqww','id':'123', 'customsCode':'qq','fax':'021-39297127'}]}");
        hd.post("http://localhost:8080/EportGnssWebDL/api/CopInfoAPI/esealInfoAdd.json",map);
	}
}

4.辅助类

    /**
     * 辅助类:锁接口需要的字段
     * @param eseal
     * @param ent
     * @return
     */
    private JsonObject getEsealJson(GbEsealInfo eseal, GbEntInfo ent){	
    	JsonObject j = new JsonObject(); 	
    	j.addProperty("esealId", eseal.getEsealId());
    	j.addProperty("vehicleNo", eseal.getVehicleNo());
    	j.addProperty("customsCode", eseal.getCustomsCode());
    	j.addProperty("simNo", eseal.getSimNo());
    	j.addProperty("entName", ent.getEntName());
    	j.addProperty("customsName", eseal.getCustomsName());
    	j.addProperty("leadingOfficial", ent.getLeadingOfficial());
    	j.addProperty("contact", ent.getContact());
    	j.addProperty("address", ent.getAddress());
    	j.addProperty("mail", ent.getMail());
    	j.addProperty("phone", ent.getPhone());
    	j.addProperty("fax", ent.getFax());
    	return j;
    }

猜你喜欢

转载自blog.csdn.net/zhulurensheng/article/details/81564949
今日推荐