啟動項目后, 加載數據庫公共配置數據到redis中
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;/*** 啟動項目后, 加載數據庫公共配置數據到redis中* */
@Component
public class PubConfigUtil {private static String pre = "pub_config"; // 存儲到redis中的前綴private static String operation = ":"; // redis冒號分組@Resourceprivate JdbcTemplate jdbcTemplate; // springboot集成mybatis-spring-boot-starter后本身封裝的工具類@Resourceprivate RedisTemplate redisTemplate;@PostConstruct // 是java注解,在方法上加該注解會在項目啟動的時候執行該方法,也可以理解為在spring容器初始化的時候執行該方法。public void reload() {String sql = "SELECT config_id,config_block,config_name,config_value,config_desc FROM ad_basic_config WHERE data_status = '1'"; // 數據庫配置表,根據你自己的配置表定義查詢語句List<Map<String, Object>> mapsList = jdbcTemplate.queryForList(sql);if (!CollectionUtils.isEmpty(mapsList)) { // 存在值StringBuilder sbl = new StringBuilder();for (Map<String, Object> map : mapsList) {sbl.setLength(0);String config_block = map.get("config_block").toString(); // 數據庫配置表中的字段名稱| 模塊: aliyunString config_name = map.get("config_name").toString(); // 數據庫配置表中的字段名稱| 配置名: SMS_TEMPLATECODE_LOGGIN (阿里云下短信模板號 - 登錄)String config_value = map.get("config_value").toString(); // 數據庫配置表中的字段名稱| 配置具體值: xxxxx (阿里云下短信模板號)String key = sbl.append(pre).append(operation).append(config_block).append(operation).append(config_name).toString();redisTemplate.opsForValue().set(key, config_value);}}}/* // 獲取啟動后加載的配置數據 - 放到自己項目的redis工具類中public Integer getInt(String configBlock,String configName, Integer defaultVal) {String string = getString(configBlock,configName, null);Integer value = defaultVal;try {value = Integer.valueOf(string);} catch (Exception e) {e.printStackTrace();}return value;}public Long getLong(String configBlock,String configName, Long defaultVal) {String string = getString(configBlock,configName, null);Long value = defaultVal;try {value = Long.valueOf(string);} catch (Exception e) {e.printStackTrace();}return value;}public Double getDouble(String configBlock,String configName, Double defaultVal) {String string = getString(configBlock,configName, null);Double value = defaultVal;try {value = Double.valueOf(string);} catch (Exception e) {e.printStackTrace();}return value;}public Boolean getBoolean(String configBlock,String configName, Boolean defaultVal) {String string = getString(configBlock,configName, null);Boolean value = defaultVal;try {value = Boolean.valueOf(string);} catch (Exception e) {e.printStackTrace();}return value;}} */
可以根據項目情況進行修改