需求:在一个springBoot项目中,需要定时调用外部接口,并将接口返回数据写入到内部数据表中
解决:1、定时任务;2、调用接口;3、保存数据
(一)定时任务
package com.success.datashow.utils;
import com.success.datashow.service.impl.GuangxiInPortShipServiceImpl;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.io.IOException;
/**
* @Description:定时任务公共类
*/
@Component
@PropertySource("classpath:schedule.props")
@EnableScheduling //通过@EnableScheduling注解开启对计划任务的支持
public class AllTask implements ApplicationContextAware {
@Autowired
private GuangxiInPortShipServiceImpl guangxiInPortShipServiceImpl;
private static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context=applicationContext;
}
public static ApplicationContext getApplicationContext(){return context;}
public static Object getBean(String name){return getApplicationContext().getBean(name);}
/**
* 查询数量,并进行本地保存
* 每小时一次
* @throws IOException
*/
@Scheduled(cron="${jobs.getinportshipnum}") //每小时执行一次
public void getInPortShipNum() throws IOException {
try {
Thread.sleep(2000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
GuangxiInPortShipServiceImpl guangxiInPortShipService = (GuangxiInPortShipServiceImpl)this.getBean("guangxiInPortShipServiceImpl");
//查询数量,并进行本地保存
guangxiInPortShipService.inPortShipSave();
}
}
(二)接口调用
package com.success.datashow.service.impl;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.success.datashow.dao.GuangxiInPortShipDao;
import com.success.datashow.utils.PropertiesUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;
import static sun.net.www.protocol.http.HttpURLConnection.userAgent;
@Slf4j
@Service
@DS("000001")
public class GuangxiInPortShipServiceImpl implements ApplicationContextAware {
private GuangxiInPortShipDao guangxiInPortShipDao;
private static ApplicationContext context;
/*PropertiesUtil util = new PropertiesUtil("sysconfig.properties");
String onPortDataurl = util.readProperty("onPortDataurl");*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context=applicationContext;
}
public static ApplicationContext getApplicationContext(){return context;}
public static Object getBean(String name){return getApplicationContext().getBean(name);}
/*
**
* @Description:获取在港船舶数量并保存到本地
* @Param:
* @return:
* @Author: lijun
* @Date: 2021-07-21 15:32
*/
public void inPortShipSave() throws IOException {
GuangxiInPortShipDao guangxiInPortShipDao = (GuangxiInPortShipDao)this.getBean("guangxiInPortShipDao");
HttpURLConnection conn = null;
BufferedReader reader = null;
String rs = null;
String method = "GET";
Map<String, Object> map = new HashMap<>();
try {
StringBuffer sb = new StringBuffer();
String onPortDataurl = "";
if (method == null || method.equals("GET")) {
//onPortDataurl = onPortDataurl + "?fuseFlags=2";
onPortDataurl = "http://198.21.18.20:8080/****/count?fuseFlags=2";
}
URL url = new URL(onPortDataurl);
conn = (HttpURLConnection) url.openConnection();
if (method == null || method.equals("GET")) {
conn.setRequestMethod("GET");
} else {
conn.setRequestMethod("POST");
conn.setDoOutput(true);
}
conn.setRequestProperty("User-agent", userAgent);
conn.setUseCaches(false);
conn.setConnectTimeout(2000);
conn.setReadTimeout(4000);
conn.setInstanceFollowRedirects(false);
conn.connect();
InputStream is = conn.getInputStream();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String strRead = null;
while ((strRead = reader.readLine()) != null) {
sb.append(strRead);
}
rs = sb.toString();
JSONObject jsonObject = new JSONObject();
//获取的字符串转为json对象
jsonObject = JSONObject.parseObject(rs);
int count = 0;
if("200".equals(jsonObject.get("code").toString())){
count = Integer.parseInt(JSONObject.parseObject(jsonObject.get("data").toString()).get("count").toString());
//count = Integer.parseInt(jsonObject.get("data").toString());
System.out.println("jsonObject:"+jsonObject);
System.out.println("count:"+count);
map.put("inport_ship_num",count);
map.put("import_time",new Date());
}
guangxiInPortShipDao.insertOnPortShip(map);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
reader.close();
}
if (conn != null) {
conn.disconnect();
}
}
}
}
(三)保存数据
package com.success.datashow.dao;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Map;
@Repository
@Mapper
public interface GuangxiInPortShipDao {
// 插入数据
@Insert("insert into C_DAP_INPORT_SHIP(inport_ship_num,import_time) "
+ "values (#{map.inport_ship_num},#{map.import_time})")
void insertOnPortShip(@Param("map") Map<String, Object> map);
}