springboot自定義緩存加載數據庫中的基本信息

Background

在開發中可能會有這樣的情景。需要在容器啓動的時候執行一些內容。比如讀取配置文件,數據庫連接之類的。SpringBoot給我們提供了兩個接口來幫助我們實現這種需求。這兩個接口分別爲CommandLineRunnerApplicationRunner。他們的執行時機爲容器啓動完成的時候。
這兩個接口中有一個run方法,我們只需要實現這個方法即可。這兩個接口的不同之處在於:ApplicationRunner中run方法的參數爲ApplicationArguments,而CommandLineRunner接口中run方法的參數爲String數組。

ApplicationRunner

在容器啓動時把數據庫中的基本信息加載到內存中

package com.cloudansys.monitor.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
public class CacheHandler implements ApplicationRunner {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    // 每個 targetId 對應的參數的codes
    private Map<Integer, List<Integer>> paramCodes = new ConcurrentHashMap<>();

    // 每個 targetId 對應的參數的names
    private Map<Integer, List<String>> paramNames = new ConcurrentHashMap<>();

    // 每個 targetId 的 targetCode
    private Map<Integer, String> targetsCode = new ConcurrentHashMap<>();

    public List<String> getParamCodes(Integer targetId) {
        List<Integer> codes = this.paramCodes.get(targetId);
        List<String> list = new ArrayList<>();
        for (Integer code : codes) {
            list.add(String.valueOf(code));
        }

        return list;
    }

    public List<String> getParamNames(Integer targetId) {
        return this.paramNames.get(targetId);
    }

    public String getTargetCode(Integer targetId) {
        return this.targetsCode.get(targetId);
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {

        final String SQL_1 = "SELECT id FROM %s ;";
        final String SQL_2 = "SELECT type FROM %s WHERE id = ? ;";
        final String SQL_3 = "SELECT code FROM %s WHERE target_type = ? ;";
        final String SQL_4 = "SELECT name FROM %s WHERE target_type = ? ;";
        final String SQL_5 = "SELECT code as targetCode FROM %s WHERE id = ?;";

        final String sql_1 = String.format(SQL_1, Constants.DB.TARGET_INFO);
        final String sql_2 = String.format(SQL_2, Constants.DB.TARGET_INFO);
        final String sql_3 = String.format(SQL_3, Constants.DB.QUOTA_INFO);
        final String sql_4 = String.format(SQL_4, Constants.DB.QUOTA_INFO);
        final String sql_5 = String.format(SQL_5, Constants.DB.TARGET_INFO);

//        log.debug("sql_1: {}", sql_1);
//        log.debug("sql_2: {}", sql_2);
//        log.debug("sql_3: {}", sql_3);
//        log.debug("sql_4: {}", sql_4);
//        log.debug("sql_5: {}", sql_5);

        // 獲取所有的測點 id
        final List<Integer> ids = this.jdbcTemplate.queryForList(sql_1, Integer.class);

        // 遍歷 ids 獲取每個測點 id 對應的 測點編號 targetCode、參數名 paramNames、參數編號 codeNames
        for (Integer id : ids) {

            // 獲取測點 id 對應的類型,且每個測點 id 只有一個類型
            final List<String> types = this.jdbcTemplate.queryForList(sql_2, String.class, id);
            Integer type = Integer.valueOf(types.get(0));

            // 獲取測點 id 對應的測點編號,並把所有 id 和 targetCode 的對應關係放到 targetsCode Map 中
            String targetCode = this.jdbcTemplate.queryForList(sql_5, String.class, id).get(0);
            this.targetsCode.put(id, targetCode);

            // 獲取測點 id 對應類型中包含的參數編號,並根據參數編號獲取參數名
            final List<Integer> paramCodes = this.jdbcTemplate.queryForList(sql_3, Integer.class, type);
            final List<String> paramNames = this.jdbcTemplate.queryForList(sql_4, String.class, type);
            this.paramCodes.put(id, paramCodes);
            this.paramNames.put(id, paramNames);
        }
    }
}

CommandLineRunner

這是個定時任務,且在容器啓動時加載,定時向mqtt發送消息

package com.cloudansys.processor;

import com.cloudansys.config.MqttGateway;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
@EnableScheduling
public class ProcessorEMQ implements Processor, CommandLineRunner {

    private ObjectMapper objectMapper;

    @Autowired
    private MqttGateway gateway;

    private static final String SEND_TOPIC = "warn_blast";

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public ProcessorEMQ(){
        this.objectMapper = new ObjectMapper();
    }

    @Override
    public void run(String... args) {
        exec();
    }

    //    {秒} {分} {時} {日} {月} {星期} {年份(可爲空)}
//    @Scheduled(cron = "10 * * * * ?", zone = "GMT+8")
    @Scheduled(cron = "*/10 * * * * ?")
    private void exec() {
        String sql = "SELECT node_id, time_o, `value` FROM simulation_data_blast WHERE id = ?;";
        log.debug("sql :{} ", sql);

        int num = (int) (Math.random() * 1000);
        log.info("num: {}", num);

        Object args[] = {num};
        List<Map<String, Object>> maps = this.jdbcTemplate.queryForList(sql, args);
        maps.forEach(System.out::println);
        try {
            String payload = this.objectMapper.writeValueAsString(maps);
            log.info("payload: {}", payload);

            this.gateway.sendToMqtt(SEND_TOPIC, payload);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章