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();
        }
    }

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