当前位置: 首页 > news >正文

springboot解析自定义yml文件

背景

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

公共配置文件位置

公共配置文件

启动本地redis(windows版)

启动redis
当前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文件

背景 公司产品微服务架构下有十几个模块&#xff0c;几乎大部分模块都要连接redis。每次在客户那里部署应用&#xff0c;都要改十几遍配置&#xff0c;太痛苦了。当然可以用nacos配置中心的功能&#xff0c;配置公共参数。不过我是喜欢在应用级别上解决问题&#xff0c;因为并不…...

【C/C++】静态函数调用类中成员函数方法 -- 最快捷之一

背景 注册回调函数中&#xff0c;回调函数是一个静态函数。需要调用类对象中的一个成员函数进行后续通知逻辑。 方案 定义全局指针&#xff0c;用于指向类对象this指针 static void *s_this_obj;类构造函数中&#xff0c;将全局指针指向所需类的this指针 s_this_obj this…...

佣金的定义和类型

1. 佣金的定义 基本定义&#xff1a;佣金是指在商业交易中&#xff0c;代理人或中介机构为促成交易所获得的报酬。它通常是按交易金额的一定比例计算和支付的。支付方式&#xff1a;佣金可以是固定金额&#xff0c;也可以是交易金额的百分比。 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、定位慢查询 方案一、开源工具 调试工具&#xff1a;Arthas运维工具&#xff1a;Prometheus、Skywalking 方案二、MySQL自带慢日志 在MySQL配置文件 /etc/my.conf 中配置&#xff1a; # …...

vue-cli 项目打包优化-基础篇

1、项目打包完运行空白 引用资源路径问题&#xff0c;打包完的【index.html】文件引用其他文件的引用地址不对 参考配置&#xff1a;https://cli.vuejs.org/zh/config 修改vue.config.js &#xff0c;根据与 后端 或 运维 沟通修改 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 为自己选择的颜色&#xff0c;核心代码如下&#xff1a; // 处理主题样式 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&#xff1f; Git是一款分布式版本控制系统&#xff0c;由Linux之父Linus Torvalds于2005年开发。它旨在快速、高效地处理从小型到大型项目的所有内容。Git与传统的版本控制系统相比&#xff0c;具备显著的优势&#xff0c;主要体现在其分布式架构、强大的…...

创建OpenWRT虚拟机

环境&#xff1a;Ubuntu 2204&#xff0c;VM VirtualBox 7.0.18 安装必备软件包&#xff1a; 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…...

智慧安防新篇章:如何科学设定可燃气体报警器校准检测周期

随着科技的快速发展&#xff0c;智慧安防系统已成为现代社会不可或缺的一部分。在各类安全监测设备中&#xff0c;可燃气体报警器因其对潜在危险的及时预警功能而备受关注。 接下来&#xff0c;佰德将围绕可燃气体报警器的校准检测周期进行深入探讨&#xff0c;以确保其在智慧…...

如何优化Spring Boot应用的启动时间

如何优化Spring Boot应用的启动时间 大家好&#xff0c;我是免费搭建查券返利机器人省钱赚佣金就用微赚淘客系统3.0的小编&#xff0c;也是冬天不穿秋裤&#xff0c;天冷也要风度的程序猿&#xff01;今天我们将讨论如何优化Spring Boot应用的启动时间&#xff0c;提升应用的性…...

(Effective C) 2.3 作用域

(Effective C) 2.3 作用域 文章目录 (Effective C) 2.3 作用域前言&#x1f522;4大作用域1️⃣文件作用域2️⃣块作用域3️⃣函数原型作用域4️⃣函数作用域 ⭐作用域性质&#x1f4d6;实例CodeEND关注我 前言 作用域应用于标识符的某个特定声明。 标识符包含对象&#xff0…...

Python 基础 (标准库):堆 heap

1. 官方文档 heapq --- 堆队列算法 — Python 3.12.4 文档 2. 相关概念 堆 heap 是一种具体的数据结构&#xff08;concrete data structures&#xff09;&#xff1b;优先级队列 priority queue 是一种抽象的数据结构&#xff08;abstract data structures&#xff09;&…...

动手学深度学习(Pytorch版)代码实践 -卷积神经网络-30Kaggle竞赛:图片分类

30Kaggle竞赛&#xff1a;图片分类 比赛链接&#xff1a; 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&#xff0c;请返回数组中第 k 个最大的元素。 请注意&#xff0c;你需要找的是数组排序后的第 k 个最大的元素&#xff0c;而不是第 k 个不同的元素。 你必须设计并实现时间复杂度为 O(n) 的算法解决此问题。 解题思路 第一种是快排&#xff0c;快…...

Keil5.38ARM,旧编译器(V5)安装

站内文章KEIL5MDK最新版(3.37)安装以及旧编译器(V5)安装_keil5 mdk-CSDN博客...

【perl】脚本编程的一些坑案例

引言 记录自己跳进的【perl】编程小坑&#xff0c;以己为鉴。 1、eq $str1 "12345\n"; $str2 "12345"; if ($str1 eq $str2) { print "OK" } 上述代码不会打印 OK。特别在读文件 &#xff0c;匹配字符串时容易出BUG。 案例说明&#xff1a; 有…...

MIX OTP——使用 GenServer 进行客户端-服务器通信

在上一章中&#xff0c;我们使用代理来表示存储容器。在 mix 的介绍中&#xff0c;我们指定要命名每个存储容器&#xff0c;以便我们可以执行以下操作&#xff1a; 在上面的会话中&#xff0c;我们与“购物”存储容器进行了交互。 由于代理是进程&#xff0c;因此每个存储容器…...

铭豹扩展坞 USB转网口 突然无法识别解决方法

当 USB 转网口扩展坞在一台笔记本上无法识别,但在其他电脑上正常工作时,问题通常出在笔记本自身或其与扩展坞的兼容性上。以下是系统化的定位思路和排查步骤,帮助你快速找到故障原因: 背景: 一个M-pard(铭豹)扩展坞的网卡突然无法识别了,扩展出来的三个USB接口正常。…...

微信小程序 - 手机震动

一、界面 <button type"primary" bindtap"shortVibrate">短震动</button> <button type"primary" bindtap"longVibrate">长震动</button> 二、js逻辑代码 注&#xff1a;文档 https://developers.weixin.qq…...

Linux离线(zip方式)安装docker

目录 基础信息操作系统信息docker信息 安装实例安装步骤示例 遇到的问题问题1&#xff1a;修改默认工作路径启动失败问题2 找不到对应组 基础信息 操作系统信息 OS版本&#xff1a;CentOS 7 64位 内核版本&#xff1a;3.10.0 相关命令&#xff1a; uname -rcat /etc/os-rele…...

算法:模拟

1.替换所有的问号 1576. 替换所有的问号 - 力扣&#xff08;LeetCode&#xff09; ​遍历字符串​&#xff1a;通过外层循环逐一检查每个字符。​遇到 ? 时处理​&#xff1a; 内层循环遍历小写字母&#xff08;a 到 z&#xff09;。对每个字母检查是否满足&#xff1a; ​与…...

Web中间件--tomcat学习

Web中间件–tomcat Java虚拟机详解 什么是JAVA虚拟机 Java虚拟机是一个抽象的计算机&#xff0c;它可以执行Java字节码。Java虚拟机是Java平台的一部分&#xff0c;Java平台由Java语言、Java API和Java虚拟机组成。Java虚拟机的主要作用是将Java字节码转换为机器代码&#x…...

Java数组Arrays操作全攻略

Arrays类的概述 Java中的Arrays类位于java.util包中&#xff0c;提供了一系列静态方法用于操作数组&#xff08;如排序、搜索、填充、比较等&#xff09;。这些方法适用于基本类型数组和对象数组。 常用成员方法及代码示例 排序&#xff08;sort&#xff09; 对数组进行升序…...

shell脚本质数判断

shell脚本质数判断 shell输入一个正整数,判断是否为质数(素数&#xff09;shell求1-100内的质数shell求给定数组输出其中的质数 shell输入一个正整数,判断是否为质数(素数&#xff09; 思路&#xff1a; 1:1 2:1 2 3:1 2 3 4:1 2 3 4 5:1 2 3 4 5-------> 3:2 4:2 3 5:2 3…...

C++ 类基础:封装、继承、多态与多线程模板实现

前言 C 是一门强大的面向对象编程语言&#xff0c;而类&#xff08;Class&#xff09;作为其核心特性之一&#xff0c;是理解和使用 C 的关键。本文将深入探讨 C 类的基本特性&#xff0c;包括封装、继承和多态&#xff0c;同时讨论类中的权限控制&#xff0c;并展示如何使用类…...

【AI News | 20250609】每日AI进展

AI Repos 1、OpenHands-Versa OpenHands-Versa 是一个通用型 AI 智能体&#xff0c;通过结合代码编辑与执行、网络搜索、多模态网络浏览和文件访问等通用工具&#xff0c;在软件工程、网络导航和工作流自动化等多个领域展现出卓越性能。它在 SWE-Bench Multimodal、GAIA 和 Th…...

[C++错误经验]case语句跳过变量初始化

标题&#xff1a;[C错误经验]case语句跳过变量初始化 水墨不写bug 文章目录 一、错误信息复现二、错误分析三、解决方法 一、错误信息复现 write.cc:80:14: error: jump to case label80 | case 2:| ^ write.cc:76:20: note: crosses initialization…...