springboot解析自定义yml文件
背景
公司产品微服务架构下有十几个模块,几乎大部分模块都要连接redis。每次在客户那里部署应用,都要改十几遍配置,太痛苦了。当然可以用nacos配置中心的功能,配置公共参数。不过我是喜欢在应用级别上解决问题,因为并不是每个项目都会使用nacos,做个知识储备还是不错的。
公共配置文件位置

启动本地redis(windows版)

当前redis 没有数据

初始化redis
这里的初始化和正常把redis配置信息放到application.yml里的初始化是一样的。
package cn.com.soulfox.common.config;import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;/*** * @create 2024/4/11 10:48*/
@Configuration
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class)
@Slf4j
public class RedisTemplateConfig {@Bean@ConditionalOnMissingBean(name = "redisTemplate")public RedisTemplate<String, Object> getRedisTemplate(RedisConnectionFactory factory){log.info("开始初始化 RedisTemplate ------------------");RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();// key的序列化类型redisTemplate.setKeySerializer(new StringRedisSerializer());redisTemplate.setHashKeySerializer(new StringRedisSerializer());redisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer());redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());redisTemplate.setConnectionFactory(factory);log.info("初始化 RedisTemplate 结束------------------");return redisTemplate;}
}
解析自定义sf-redis.yml
package cn.com.soulfox.business.config;import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.FileSystemResource;
import org.springframework.stereotype.Component;/*** * @create 2024/6/26 16:41*/
@Configuration
public class CommonConfig {@Bean("common-config")public static PropertySourcesPlaceholderConfigurer properties() {PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();YamlPropertiesFactoryBean redis = new YamlPropertiesFactoryBean();//文件路径写死的,真正做项目时,文件路径可以配置到application.yml文件FileSystemResource redisResource = new FileSystemResource("../common-config/sf-redis.yml");redis.setResources(redisResource);configurer.setPropertiesArray(redis.getObject());//如果有多个配置文件,也是可以处理的。setPropertiesArray(Properties... propertiesArray)方法的参数是个数组,//如下还可以同时处理文件sf-ports.yml,此时configurer.setPropertiesArray(redis.getObject());代码要注释掉//YamlPropertiesFactoryBean ports = new YamlPropertiesFactoryBean();
// FileSystemResource portsResource = new FileSystemResource("../common-config/sf-ports.yml");
// ports.setResources(portsResource);//同时添加sf-redis.yml和sf-ports.yml的配置信息
// configurer.setPropertiesArray(redis.getObject(), ports.getObject());return configurer;}
}
应用启动类
注意一下,因为我已经搭建了完整的微服务,包括nacos,mybatis,feign等,所有启动类上注解比较多。如果只是单纯测试一下,引入springboot基础框架和redis依赖,写一个基础启动类就可以了。
package cn.com.soulfox.business;import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.PathResource;
import org.springframework.core.io.Resource;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import tk.mybatis.spring.annotation.MapperScan;import java.io.File;@SpringBootApplication
@EnableDiscoveryClient//nacos注册中心
@EnableFeignClients(basePackages = {"cn.com.soulfox.common.feign.client"})//feign扫描
@MapperScan(basePackages={"cn.com.soulfox.*.mvc.mapper"})//mybatis mapper扫描
@EnableTransactionManagement//开启数据库事务
@ComponentScan("cn.com.soulfox")
public class BusinessApplicationRun {public static void main(String[] args) {SpringApplication.run(BusinessApplicationRun.class, args);}}
启动一下应用看看redis是否初始化成功

测试一下是否可以正常使用
- 单元测试类
package cn.com.soulfox.common.config;import cn.com.soulfox.business.BusinessApplicationRun;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;/*** * @create 2024/6/26 16:52*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = BusinessApplicationRun.class,webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class CommonConfigTest {@Autowiredprivate RedisTemplate<String, Object> redisTemplate;//文件sf-redis.yml里属性的使用和applications.yml一样@Value("${spring.redis.host}")private String redisHost;@Testpublic void test(){System.out.println("从文件取参数测试+++++++++++");System.out.println("redisHost: " + redisHost);}
}
- 测试sf-redis.yml属性使用
使用方法和配置在application.yml文件是一样,都是通过@Value注解获取
测试结果

- 测试redis是否可以正常使用
测试写入数据,增加以下测试方法
@Testpublic void testRedisSetValue(){this.redisTemplate.opsForValue().set("test", "test123");}
测试结果

测试读取数据,增加以下测试方法
@Testpublic void testRedisGetValue(){Object testValue = this.redisTemplate.opsForValue().get("test");System.out.println(testValue);}
测试结果

总结一下。。。
现在的微服务,大多使用nacos作为注册中心,同事nacos也能作为配置中心使用。公共配置一般放在nacos中,以上方法没有什么用处。但总有项目可能不会使用nacos,比如使用eureka,这时候以上方法就有用武之地。这个方法可以作为知识储备,了解一下总是有好处的 :–)
还有一点需要注意的,就是yml文件是在程序启动后解析的,所以文件里的配置信息,在application.yml里是不能通过${xxx.xxx}使用的。
相关文章:
springboot解析自定义yml文件
背景 公司产品微服务架构下有十几个模块,几乎大部分模块都要连接redis。每次在客户那里部署应用,都要改十几遍配置,太痛苦了。当然可以用nacos配置中心的功能,配置公共参数。不过我是喜欢在应用级别上解决问题,因为并不…...
【C/C++】静态函数调用类中成员函数方法 -- 最快捷之一
背景 注册回调函数中,回调函数是一个静态函数。需要调用类对象中的一个成员函数进行后续通知逻辑。 方案 定义全局指针,用于指向类对象this指针 static void *s_this_obj;类构造函数中,将全局指针指向所需类的this指针 s_this_obj this…...
佣金的定义和类型
1. 佣金的定义 基本定义:佣金是指在商业交易中,代理人或中介机构为促成交易所获得的报酬。它通常是按交易金额的一定比例计算和支付的。支付方式:佣金可以是固定金额,也可以是交易金额的百分比。 2. 佣金的类型 销售佣金&#…...
python数据分析实训任务二(‘风力风向’)
import numpy as np import matplotlib.pyplot as plt # 数据 labelsnp.array([东风, 东北风, 北风, 西北风, 西风, 西南风, 南风, 东南风]) statsnp.array([2.1, 2, 0, 3, 1.5, 3, 6, 4]) # 将角度转换为弧度 anglesnp.linspace(0, 2*np.pi, len(labels), endpointFalse).toli…...
Java技术栈总结:数据库MySQL篇
一、慢查询 1、常见情形 聚合查询 多表查询 表数据量过大查询 深度分页查询 2、定位慢查询 方案一、开源工具 调试工具:Arthas运维工具:Prometheus、Skywalking 方案二、MySQL自带慢日志 在MySQL配置文件 /etc/my.conf 中配置: # …...
vue-cli 项目打包优化-基础篇
1、项目打包完运行空白 引用资源路径问题,打包完的【index.html】文件引用其他文件的引用地址不对 参考配置:https://cli.vuejs.org/zh/config 修改vue.config.js ,根据与 后端 或 运维 沟通修改 module.export {// 默认 publicPath: //…...
24/06/26(1.1129)动态内存
strtok 字符串分割函数 #include<stdio.h> int main(){ char str[] "this,a sample string."; char* sep ","; char* pch strtok(str, sep); printf("%s\n", pch); while (pch ! NULL){ printf("%s\…...
基于 elementUI / elementUI plus,实现 主要色(主题色)的一件换色(换肤)
一、效果图 二、方法 改变elementUI 的主要色 --el-color-primary 为自己选择的颜色,核心代码如下: // 处理主题样式 export function handleThemeStyle(theme) {document.documentElement.style.setProperty(--el-color-primary, theme) } 三、全部代…...
js 计算某个日期加月份最后月份不会增加或者跳变
/** * * param {*} dateString 原来日期 2023-12-31 * param {*} months 加月份 2 * returns 2024-02-29 */ export function getDateByMonth(dateString, months0) { console.log(1); let oldMonths dateString.substring(0,7); let day dateString.substring(8); let …...
Git简介与详细教程
一、简介 什么是Git? Git是一款分布式版本控制系统,由Linux之父Linus Torvalds于2005年开发。它旨在快速、高效地处理从小型到大型项目的所有内容。Git与传统的版本控制系统相比,具备显著的优势,主要体现在其分布式架构、强大的…...
创建OpenWRT虚拟机
环境:Ubuntu 2204,VM VirtualBox 7.0.18 安装必备软件包: sudo apt update sudo apt install subversion automake make cmake uuid-dev gcc vim build-essential clang flex bison g gawk gcc-multilib g-multilib gettext git libncurses…...
智慧安防新篇章:如何科学设定可燃气体报警器校准检测周期
随着科技的快速发展,智慧安防系统已成为现代社会不可或缺的一部分。在各类安全监测设备中,可燃气体报警器因其对潜在危险的及时预警功能而备受关注。 接下来,佰德将围绕可燃气体报警器的校准检测周期进行深入探讨,以确保其在智慧…...
如何优化Spring Boot应用的启动时间
如何优化Spring Boot应用的启动时间 大家好,我是免费搭建查券返利机器人省钱赚佣金就用微赚淘客系统3.0的小编,也是冬天不穿秋裤,天冷也要风度的程序猿!今天我们将讨论如何优化Spring Boot应用的启动时间,提升应用的性…...
(Effective C) 2.3 作用域
(Effective C) 2.3 作用域 文章目录 (Effective C) 2.3 作用域前言🔢4大作用域1️⃣文件作用域2️⃣块作用域3️⃣函数原型作用域4️⃣函数作用域 ⭐作用域性质📖实例CodeEND关注我 前言 作用域应用于标识符的某个特定声明。 标识符包含对象࿰…...
Python 基础 (标准库):堆 heap
1. 官方文档 heapq --- 堆队列算法 — Python 3.12.4 文档 2. 相关概念 堆 heap 是一种具体的数据结构(concrete data structures);优先级队列 priority queue 是一种抽象的数据结构(abstract data structures)&…...
动手学深度学习(Pytorch版)代码实践 -卷积神经网络-30Kaggle竞赛:图片分类
30Kaggle竞赛:图片分类 比赛链接: https://www.kaggle.com/c/classify-leaves 导入包 import torch import torchvision from torch.utils.data import Dataset, DataLoader from torchvision import transforms import numpy as np import pandas as…...
【LeetCode】每日一题:数组中的第K大的元素
给定整数数组 nums 和整数 k,请返回数组中第 k 个最大的元素。 请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。 你必须设计并实现时间复杂度为 O(n) 的算法解决此问题。 解题思路 第一种是快排,快…...
Keil5.38ARM,旧编译器(V5)安装
站内文章KEIL5MDK最新版(3.37)安装以及旧编译器(V5)安装_keil5 mdk-CSDN博客...
【perl】脚本编程的一些坑案例
引言 记录自己跳进的【perl】编程小坑,以己为鉴。 1、eq $str1 "12345\n"; $str2 "12345"; if ($str1 eq $str2) { print "OK" } 上述代码不会打印 OK。特别在读文件 ,匹配字符串时容易出BUG。 案例说明: 有…...
MIX OTP——使用 GenServer 进行客户端-服务器通信
在上一章中,我们使用代理来表示存储容器。在 mix 的介绍中,我们指定要命名每个存储容器,以便我们可以执行以下操作: 在上面的会话中,我们与“购物”存储容器进行了交互。 由于代理是进程,因此每个存储容器…...
web vue 项目 Docker化部署
Web 项目 Docker 化部署详细教程 目录 Web 项目 Docker 化部署概述Dockerfile 详解 构建阶段生产阶段 构建和运行 Docker 镜像 1. Web 项目 Docker 化部署概述 Docker 化部署的主要步骤分为以下几个阶段: 构建阶段(Build Stage):…...
树莓派超全系列教程文档--(61)树莓派摄像头高级使用方法
树莓派摄像头高级使用方法 配置通过调谐文件来调整相机行为 使用多个摄像头安装 libcam 和 rpicam-apps依赖关系开发包 文章来源: http://raspberry.dns8844.cn/documentation 原文网址 配置 大多数用例自动工作,无需更改相机配置。但是,一…...
Nuxt.js 中的路由配置详解
Nuxt.js 通过其内置的路由系统简化了应用的路由配置,使得开发者可以轻松地管理页面导航和 URL 结构。路由配置主要涉及页面组件的组织、动态路由的设置以及路由元信息的配置。 自动路由生成 Nuxt.js 会根据 pages 目录下的文件结构自动生成路由配置。每个文件都会对…...
linux 下常用变更-8
1、删除普通用户 查询用户初始UID和GIDls -l /home/ ###家目录中查看UID cat /etc/group ###此文件查看GID删除用户1.编辑文件 /etc/passwd 找到对应的行,YW343:x:0:0::/home/YW343:/bin/bash 2.将标红的位置修改为用户对应初始UID和GID: YW3…...
【碎碎念】宝可梦 Mesh GO : 基于MESH网络的口袋妖怪 宝可梦GO游戏自组网系统
目录 游戏说明《宝可梦 Mesh GO》 —— 局域宝可梦探索Pokmon GO 类游戏核心理念应用场景Mesh 特性 宝可梦玩法融合设计游戏构想要素1. 地图探索(基于物理空间 广播范围)2. 野生宝可梦生成与广播3. 对战系统4. 道具与通信5. 延伸玩法 安全性设计 技术选…...
Maven 概述、安装、配置、仓库、私服详解
目录 1、Maven 概述 1.1 Maven 的定义 1.2 Maven 解决的问题 1.3 Maven 的核心特性与优势 2、Maven 安装 2.1 下载 Maven 2.2 安装配置 Maven 2.3 测试安装 2.4 修改 Maven 本地仓库的默认路径 3、Maven 配置 3.1 配置本地仓库 3.2 配置 JDK 3.3 IDEA 配置本地 Ma…...
2023赣州旅游投资集团
单选题 1.“不登高山,不知天之高也;不临深溪,不知地之厚也。”这句话说明_____。 A、人的意识具有创造性 B、人的认识是独立于实践之外的 C、实践在认识过程中具有决定作用 D、人的一切知识都是从直接经验中获得的 参考答案: C 本题解…...
【Nginx】使用 Nginx+Lua 实现基于 IP 的访问频率限制
使用 NginxLua 实现基于 IP 的访问频率限制 在高并发场景下,限制某个 IP 的访问频率是非常重要的,可以有效防止恶意攻击或错误配置导致的服务宕机。以下是一个详细的实现方案,使用 Nginx 和 Lua 脚本结合 Redis 来实现基于 IP 的访问频率限制…...
省略号和可变参数模板
本文主要介绍如何展开可变参数的参数包 1.C语言的va_list展开可变参数 #include <iostream> #include <cstdarg>void printNumbers(int count, ...) {// 声明va_list类型的变量va_list args;// 使用va_start将可变参数写入变量argsva_start(args, count);for (in…...
PostgreSQL——环境搭建
一、Linux # 安装 PostgreSQL 15 仓库 sudo dnf install -y https://download.postgresql.org/pub/repos/yum/reporpms/EL-$(rpm -E %{rhel})-x86_64/pgdg-redhat-repo-latest.noarch.rpm# 安装之前先确认是否已经存在PostgreSQL rpm -qa | grep postgres# 如果存在࿰…...
