Tích hợp API bên thứ ba để lưu trữ và cập nhật dữ liệu vào cơ sở dữ liệu

Yêu cầu thực hiện:

Thực hiện truy vấn định kỳ từ API bên thứ ba để chèn mới và cập nhật dữ liệu trong cơ sở dữ liệu nội bộ

Bước 1: Chuẩn bị

  1. Chuẩn bị một API bên thứ ba để kiểm tra, bài viết sử dụng API miễn phí từ ShowAPI, cách lấy API này có nhiều hướng dẫn trên mạng, không nêu chi tiết ở đây.

  2. Sử dụng công cụ kiểm tra API (ở đây dùng Apipost) để xác minh tính khả dụng và cấu trúc phản hồi của API.

  3. Tạo bảng tương ứng trong MySQL để lưu trữ dữ liệu theo cấu trúc phản hồi từ API; quy trình tạo bảng không được đề cập chi tiết.

Thực hiện mã nguồn

  1. Lớp Controller
package com.ndtl.yyky.common.yong;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@EnableScheduling
@Controller
public class ApiDataProcessor {
    @Autowired
    private DataHandler dataHandler;
    
    @RequestMapping("/")
    @ResponseBody
    @Scheduled(cron = "0 0 2 * * ?")
    public String fetchAndStoreData() {
        String apiUrl = "https://route.showapi.com/126-2?showapi_appid=XXXXX&showapi_sign=XXXXXXX";
        dataHandler.processApiData(apiUrl);
        return "Data processing completed";
    }
}
  1. Lớp Service
@Service
public class DataHandler {
    @Autowired
    private DataRepository dataRepository;

    @Transactional
    public void processApiData(String endpoint) {
        BufferedReader reader = null;
        StringBuilder response = new StringBuilder();
        
        try {
            URL url = new URL(endpoint);
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Charset", "utf-8");
            connection.connect();
            
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            
            JSONObject responseJson = JSON.parseObject(response.toString());
            String status = responseJson.getString("showapi_res_code");
            
            if ("200".equals(status)) {
                JSONObject body = responseJson.getJSONObject("showapi_res_body");
                JSONObject pageData = body.getJSONObject("pagebean");
                JSONArray items = pageData.getJSONArray("contentlist");
                
                for (int i = 0; i < items.size(); i++) {
                    JSONObject item = items.getJSONObject(i);
                    DataRecord record = new DataRecord();
                    
                    String name = item.getString("realName");
                    if (dataRepository.findExistingRecord(name) == null) {
                        record.setAvatar(item.getString("avatarUrl"));
                        record.setIdCard(item.getString("cardUrl"));
                        record.setLocation(item.getString("city"));
                        record.setFullName(name);
                        record.setCategory(item.getString("type"));
                        dataRepository.saveRecord(record);
                    } else {
                        dataRepository.updateRecord(name, 
                                                    item.getString("avatarUrl"), 
                                                    item.getString("cardUrl"), 
                                                    item.getString("city"), 
                                                    item.getString("type"));
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try { if (reader != null) reader.close(); } 
            catch (IOException e) { e.printStackTrace(); }
        }
    }
}
  1. Kết quả hiển thị trong bảng cơ sở dữ liệu:

Thẻ: Spring mysql JSON REST API Scheduled Tasks

Đăng vào ngày 31 tháng 5 lúc 18:47