1 mybaits for循环插入数据
RestTemplate 请求第三方网站数据 定时插入到数据库_tenc1239的博客-CSDN博客Java Web 编程 之 RestTemplate 实战全集 & SpringBoot & Spring 框架集成共计5条视频,包括:1 SpringBoot 集成 RestTemplate、2 SpringBoot HTTP 状态码解析、3 SpringBoot RestTemplate执行Http Get请求等,UP主更多精彩视频,请关注UP账号。Java Web 编程 之 RestTemplate 实战全集 & SpringBoot & Spring 框架集成_哔哩哔哩_bilibili。https://blog.csdn.net/tenc1239/article/details/130467138?spm=1001.2014.3001.5501
2 for 循环改 batchInsert 批量插入
2.1 改mapper
@RestController
@Component // 代表这个类确保会被springboot扫描到
@Transactional
public class AutoController {
private RestTemplate restTemplate = new RestTemplate() ;@Mapper
public interface DtoMapper extends BaseMapper<RestDto> {
@InsertProvider(type = Provider.class, method = "batchInsert")
int batchInsert(List<RestDto> data);
class Provider {
/* 批量插入 */
public String batchInsert(Map map) {
List<RestDto> data = (List<RestDto>) map.get("list");
StringBuilder sb = new StringBuilder(); // --> 不写 id
// INTO order_btc_usdt --> 插入数据库的表名
// 第一个是inst_id 第二个是 instId
sb.append("INSERT INTO order_btc_usdt (" +
"inst_id," +
"side," +
"sz," +
"px," +
"trade_id," +
"ts" +
") VALUES ");
MessageFormat mf = new MessageFormat(
"(" +
"#'{'list[{0}].instId}, " +
"#'{'list[{0}].side}, " +
"#'{'list[{0}].sz}, " +
"#'{'list[{0}].px}, " +
"#'{'list[{0}].tradeId}, " +
"#'{'list[{0}].ts}" +
")"
);
for (int i = 0; i < data.size(); i++) {
sb.append(mf.format(new Object[] {i}));
if (i < data.size() - 1)
sb.append(",");
}
return sb.toString();
}
}
}
}
2.2 改controller -> 不用service及impl 直接用mapper干
@Resource
DtoMapper dtoMapper ;
@Scheduled(fixedDelay = 3000) // 定时3000ms
public void autoData() {
String url = ""; // 掉数据的api
Map<String, Long> paramMap = new HashMap<>(); // 入参 可写 可不写 这里没有入参
// Map<String, Object> result = restTemplate.getForObject(url, Map.class, paramMap);// RestDto.class 根据 这个 序列化
ResponseEntity<HashMap> result = restTemplate.getForEntity(url, HashMap.class, paramMap);// RestDto.class 根据 这个 序列化
if(result.getStatusCode()== HttpStatus.OK) {
JSONArray jsonArray = JSONUtil.parseArray(result.getBody().get("data")); // list [{},{},{}] --> list里面是字典
List<RestDto> dtoList = jsonArray.toList(RestDto.class); // list [RestDto,RestDto,RestDto] --> list里面是实体类
dtoMapper.batchInsert(dtoList);
}
}