IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Java知识库 -> Springboot从数据库读取配置文件 -> 正文阅读

[Java知识库]Springboot从数据库读取配置文件

springboot常规的项目是直接读取resources/application.properties文件或者application.yml或者bootstrap.properties文件。还有常见的玩法是把nacos或eureka或zookeeper来实现远程读取配置文件。

----------------------------------------正文开始-------------------------------------------------

今天我们在cloud的基础上从数据库读取配置文件信息。在开始之前,我们需要知道三个大的概念,springboot,spring-cloud-config-server,spring-cloud-starter-config。

概念1,springboot是常规的java开发框架,这里不多说。

概念2,spring-cloud-config-server,是在常规的springboot基础上,把这个项目变成一个config-server,这个config-server可以理解为就是把数据库的配置文件读取出来,然后其余的项目的配置文件只要请求的地址是这个地址就能读取到数据库的配置信息。还可以扩展到native,jdbc,git,svn。这里我们只讲jdbc的,其余的请自行研究。

----------------------------------------服务端? config server--------------------------------------

1、新建一个普通的springboot项目,名字随便叫一个springboot-config-server。

2、pom的配置文件如下,大家可以参照下,这里的重点是springboot的版本和spring-cloud的版本,自己要注意,版本不兼容也会导致启动失败。本文的版本是经过测试和验证可用的版本。

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>cn.renkai721</groupId>
	<artifactId>ncs</artifactId>
	<version>1.0.0</version>
	<packaging>jar</packaging>

	<name>ncs</name>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.4.2</version>
		<relativePath/>
	</parent>

	<properties>
		<encoding>UTF-8</encoding>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
		<maven.compiler.source>${java.version}</maven.compiler.source>
		<maven.compiler.target>${java.version}</maven.compiler.target>
		<lombok.version>1.18.0</lombok.version>
		<spring-cloud.version>Finchley.RELEASE</spring-cloud.version>
	</properties>

	<repositories>
		<!--阿里云仓库 -->
		<repository>
			<id>aliyun</id>
			<url>https://maven.aliyun.com/repository/public/</url>
		</repository>
	</repositories>

	<dependencies>
		<!-- Spring Boot Web 依赖 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<!-- 配置文件从数据库读取 -->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-config-server</artifactId>
			<version>3.0.6</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>8.0.11</version>
		</dependency>
		<!-- 数据库连接池 -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.2.6</version>
		</dependency>

		<!-- config server需要用户名和密码才可以访问 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-security</artifactId>
		</dependency>

	</dependencies>


	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<configuration>
					<mainClass>cn.renkai721.NcsApplication</mainClass>
				</configuration>
			</plugin>
		</plugins>
	</build>


</project>

3、新建一个NcsApplication.java文件,这个项目下只有这一个文件。注意必须导入@EnableConfigServer。

package cn.renkai721;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;

@SpringBootApplication
@EnableConfigServer
public class NcsApplication {


	public static void main(String[] args) {
		SpringApplication.run(NcsApplication.class, args);
		System.out.println("naturobot-config-server项目启动成功!");
	}


}
4、新建一个application.properties文件。
# active selection value=native、jdbc、git、svn
# 如果是从数据库读取,这里必须是jdbc
server.servlet.context-path=/ncs
spring.application.name=ncs

# active selection value=native、jdbc、git、svn
# 如果是从数据库读取,这里必须是jdbc
spring.profiles.active=jdbc


#test
server.port=9092
spring.datasource.url=jdbc:mysql://192.168.1.123:3306/springbootconfig?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai&useSSL=false&allowMultiQueries=true
spring.datasource.username=root
spring.datasource.password=123456

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.initialSize=1
spring.datasource.minIdle=3
spring.datasource.maxActive=20
spring.datasource.maxWait=60000
spring.datasource.timeBetweenEvictionRunsMillis=60000
spring.datasource.minEvictableIdleTimeMillis=30000
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
spring.datasource.validationQuery=select 1
spring.jpa.hibernate.ddl-auto=update

# 下面的关键配置
spring.cloud.config.label=master
spring.cloud.config.server.jdbc=true
# 动态从数据库读取配置信息
spring.cloud.config.server.jdbc.sql=SELECT propname, propvalue from config_properties where application=? and profile=? and label=? and isdel=0

#访问该服务需要用户名和密码
# config server username and password
spring.security.user.name=admin
spring.security.user.password=admin

5、数据库脚本

CREATE TABLE `config_properties` (
  `id` bigint NOT NULL AUTO_INCREMENT COMMENT '自增主键',
  `propname` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT '配置文件的key',
  `propvalue` varchar(500) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL COMMENT '配置文件的value',
  `application` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT '对应访问地址中的config-server',
  `profile` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'dev开发环境配置文件,test测试环境,prod正式环境',
  `label` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL COMMENT '指明远程仓库的分支',
  `isdel` int DEFAULT '0' COMMENT '是否删除,1=删除,0=没有删除,可用',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=66 DEFAULT CHARSET=utf8mb3 COLLATE=utf8_bin COMMENT='springboot项目从数据库读取配置文件';

6、数据库脚本数据


-- ----------------------------
-- Records of config_properties
-- ----------------------------
INSERT INTO `config_properties` VALUES (1, 'server.servlet.context-path', '/qywxzj', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (2, 'server.port', '9091', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (3, 'server.servlet.jsp.init-parameters.development', 'TRUE', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (4, 'server.tomcat.uri-encoding', 'UTF-8', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (5, 'server.servlet.session.timeout', '7200', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (6, 'logging.level.org.springframework.web', 'ERROR', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (7, 'logging.level.com.github.binarywang.demo.wx.cp', 'INFO', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (8, 'logging.level.me.chanjar.weixin', 'INFO', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (9, 'myApp.server', 'http://192.168.1.120:9091/qywxzj/', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (10, 'server.servlet.encoding.force', 'TRUE', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (11, 'server.servlet.encoding.charset', 'UTF-8', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (12, 'server.servlet.encoding.enabled', 'TRUE', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (13, 'spring.mvc.view.prefix', '/WEB-INF/views/', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (14, 'spring.mvc.view.suffix', '.jsp', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (15, 'spring.thymeleaf.cache', 'FALSE', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (16, 'spring.thymeleaf.enabled', 'FALSE', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (17, 'spring.jpa.database', 'MYSQL', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (18, 'spring.datasource.driver-class-name', 'com.mysql.cj.jdbc.Driver', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (19, 'spring.datasource.url', 'jdbc:mysql://192.168.1.123:3306/student?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai&useSSL=false&allowMultiQueries=true', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (20, 'spring.datasource.username', 'root', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (21, 'spring.datasource.password', '123456', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (22, 'spring.datasource.type', 'com.alibaba.druid.pool.DruidDataSource', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (23, 'spring.datasource.initialSize', '1', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (24, 'spring.datasource.minIdle', '3', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (25, 'spring.datasource.maxActive', '20', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (26, 'spring.datasource.maxWait', '60000', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (27, 'spring.datasource.timeBetweenEvictionRunsMillis', '60000', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (28, 'spring.datasource.minEvictableIdleTimeMillis', '30000', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (29, 'spring.datasource.validationQuery', 'select \'x\'', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (30, 'spring.datasource.testWhileIdle', 'TRUE', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (31, 'spring.datasource.testOnBorrow', 'FALSE', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (32, 'spring.datasource.testOnReturn', 'FALSE', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (33, 'spring.jpa.hibernate.ddl-auto', 'update', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (34, 'mybatis-plus.type-aliases-package', 'cn.renkai721.*.*Entity', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (35, 'mybatis-plus.global-config.id-type', '0', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (36, 'mybatis-plus.global-config.field-strategy', '2', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (37, 'mybatis-plus.global-config.db-column-underline', 'TRUE', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (38, 'mybatis-plus.global-config.refresh-mapper', 'TRUE', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (39, 'mybatis-plus.configuration.map-underscore-to-camel-case', 'FALSE', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (40, 'mybatis-plus.configuration.cache-enabled', 'FALSE', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (41, 'mybatis-plus.configuration.call-setters-on-nulls', 'TRUE', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (42, 'mybatis-plus.global-config.db-config.id-type', 'id_worker', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (43, 'mybatis-plus.mapper-locations', 'classpath*:mapper/*Mapper.xml', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (44, 'redisson.singleServerConfig.address', '192.168.1.124:6380', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (45, 'redisson.singleServerConfig.database', '6', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (46, 'redisson.password', '123456', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (47, 'redisson.model', 'SINGLE', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (48, 'springfox.documentation.swagger.use-model-v3', 'FALSE', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (49, 'spring.mvc.pathmatch.matching-strategy', 'ant_path_matcher', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (50, 'management.endpoints.web.exposure.include', '\'*\'', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (51, 'server.tomcat.basedir', 'qywxzj', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (52, 'server.tomcat.accesslog.enabled', 'TRUE', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (53, 'server.tomcat.accesslog.pattern', '%t [%I] %{X-Forwarded-For}i %a \'%r\' %s (%D ms)', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (54, 'boiler.quartz.corePoolSize', '10', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (55, 'boiler.quartz.maxPoolSize', '30', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (56, 'boiler.quartz.queueCapacity', '40', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (57, 'boiler.timeout.connectionRequestTimeout', '3000', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (58, 'boiler.timeout.connectTimeout', '3000', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (59, 'boiler.timeout.readTimeout', '6000', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (60, 'ali.rocketmq.accessKeyId', 'LTAI5t9sdf33FDSFSVS', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (61, 'ali.rocketmq.accessKeySecret', 'C73svKpdfgdfg646GFDGDsx2kwba7H7CYJvbPq', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (62, 'ali.rocketmq.endpoint', 'http://1235689754123656.mqrest.cn-shanghai.aliyuncs.com', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (63, 'ali.rocketmq.qwzj.topic', 'qywx_selfMessage', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (64, 'ali.rocketmq.qwzj.consumerGroupName', 'GID_selfsf', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (65, 'ali.rocketmq.qwzj.instanceId', 'MQ_INST_6464s6df6646werew_BYET1yoq', 'qywxzj', 'test', 'master', 0);
INSERT INTO `config_properties` VALUES (66, 'spring.main.allow-bean-definition-overriding', 'true', 'qywxzj', 'test', 'master', 0);

7、然后启动server-config项目。在浏览器输入http://localhost:9092/ncs/qywxzj/test/master,然后输入admin/admin。就会看到从数据库中读取到的配置文件。返回的json如下。

SQL说明

SELECT KEY, VALUE from PROPERTIES where APPLICATION=? and PROFILE=? and LABEL=?

第一个?: 对应访问地址中的config-server

第二个?: 对应访问地址中的dev,test,prod等

第三个?: 可以为空,可以用来表示版本号

{
    "name": "qywxzj", 
    "profiles": [
        "test"
    ], 
    "label": "master", 
    "version": null, 
    "state": null, 
    "propertySources": [
        {
            "name": "qywxzj-test", 
            "source": {
                "server.servlet.context-path": "/qywxzj", 
                "server.port": "9091", 
                "server.servlet.jsp.init-parameters.development": "TRUE", 
                "server.tomcat.uri-encoding": "UTF-8", 
                "server.servlet.session.timeout": "7200", 
                "logging.level.org.springframework.web": "ERROR", 
                "logging.level.com.github.binarywang.demo.wx.cp": "INFO", 
                "logging.level.me.chanjar.weixin": "INFO", 
                "myApp.server": "http://192.168.1.120:9091/qywxzj/", 
                "server.servlet.encoding.force": "TRUE", 
                "server.servlet.encoding.charset": "UTF-8", 
                "server.servlet.encoding.enabled": "TRUE", 
                "spring.mvc.view.prefix": "/WEB-INF/views/", 
                "spring.mvc.view.suffix": ".jsp", 
                "spring.thymeleaf.cache": "FALSE", 
                "spring.thymeleaf.enabled": "FALSE", 
                "spring.jpa.database": "MYSQL", 
                "spring.datasource.driver-class-name": "com.mysql.cj.jdbc.Driver", 
                "spring.datasource.url": "jdbc:mysql://192.168.1.123:3306/student?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai&useSSL=false&allowMultiQueries=true", 
                "spring.datasource.username": "root", 
                "spring.datasource.password": "123456", 
                "spring.datasource.type": "com.alibaba.druid.pool.DruidDataSource", 
                "spring.datasource.initialSize": "1", 
                "spring.datasource.minIdle": "3", 
                "spring.datasource.maxActive": "20", 
                "spring.datasource.maxWait": "60000", 
                "spring.datasource.timeBetweenEvictionRunsMillis": "60000", 
                "spring.datasource.minEvictableIdleTimeMillis": "30000", 
                "spring.datasource.validationQuery": "select 'x'", 
                "spring.datasource.testWhileIdle": "TRUE", 
                "spring.datasource.testOnBorrow": "FALSE", 
                "spring.datasource.testOnReturn": "FALSE", 
                "spring.jpa.hibernate.ddl-auto": "update", 
                "mybatis-plus.type-aliases-package": "cn.renkai721.*.*Entity", 
                "mybatis-plus.global-config.id-type": "0", 
                "mybatis-plus.global-config.field-strategy": "2", 
                "mybatis-plus.global-config.db-column-underline": "TRUE", 
                "mybatis-plus.global-config.refresh-mapper": "TRUE", 
                "mybatis-plus.configuration.map-underscore-to-camel-case": "FALSE", 
                "mybatis-plus.configuration.cache-enabled": "FALSE", 
                "mybatis-plus.configuration.call-setters-on-nulls": "TRUE", 
                "mybatis-plus.global-config.db-config.id-type": "id_worker", 
                "mybatis-plus.mapper-locations": "classpath*:mapper/*Mapper.xml", 
                "redisson.singleServerConfig.address": "192.168.1.124:6380", 
                "redisson.singleServerConfig.database": "6", 
                "redisson.password": "123456", 
                "redisson.model": "SINGLE", 
                "springfox.documentation.swagger.use-model-v3": "FALSE", 
                "spring.mvc.pathmatch.matching-strategy": "ant_path_matcher", 
                "management.endpoints.web.exposure.include": "'*'", 
                "server.tomcat.basedir": "qywxzj", 
                "server.tomcat.accesslog.enabled": "TRUE", 
                "server.tomcat.accesslog.pattern": "%t [%I] %{X-Forwarded-For}i %a '%r' %s (%D ms)", 
                "boiler.quartz.corePoolSize": "10", 
                "boiler.quartz.maxPoolSize": "30", 
                "boiler.quartz.queueCapacity": "40", 
                "boiler.timeout.connectionRequestTimeout": "3000", 
                "boiler.timeout.connectTimeout": "3000", 
                "boiler.timeout.readTimeout": "6000", 
                "ali.rocketmq.accessKeyId": "LTAI5t9sdf33FDSFSVS", 
                "ali.rocketmq.accessKeySecret": "C73svKpdfgdfg646GFDGDsx2kwba7H7CYJvbPq", 
                "ali.rocketmq.endpoint": "http://1235689754123656.mqrest.cn-shanghai.aliyuncs.com", 
                "ali.rocketmq.qwzj.topic": "qywx_selfMessage", 
                "ali.rocketmq.qwzj.consumerGroupName": "GID_selfsf", 
                "ali.rocketmq.qwzj.instanceId": "MQ_INST_6464s6df6646werew_BYET1yoq", 
                "spring.main.allow-bean-definition-overriding": "true"
            }
        }
    ]
}

----------------------------------------服务端? config client--------------------------------------

1、新建一个普通的springboot项目,名字随便叫一个springboot-config-client。这个client只是一个概念,就是你需要用的实际的项目,刚才的server只是做一个从数据库读取配置文件的服务而已,因为你自己不能直接读取数据库,所以需要它来中转一下。

2、pom.xml文件依赖的jar。


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>cn.renkai721</groupId>
	<artifactId>qywxzj</artifactId>
	<version>1.0.0</version>
	<packaging>jar</packaging>

	<name>qywxzj</name>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.4.2</version>
		<relativePath/>

	<properties>
		<encoding>UTF-8</encoding>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
		<maven.compiler.source>${java.version}</maven.compiler.source>
		<maven.compiler.target>${java.version}</maven.compiler.target>
		<lombok.version>1.18.0</lombok.version>
		<spring-cloud.version>Finchley.RELEASE</spring-cloud.version>
	</properties>

	<repositories>
		<!--阿里云仓库 -->
		<repository>
			<id>aliyun</id>
			<url>https://maven.aliyun.com/repository/public/</url>
		</repository>
	</repositories>

	<dependencies>
		<!-- Spring Boot Web 依赖 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>8.0.11</version>
		</dependency>
		<!-- 数据库连接池 -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.2.6</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-config</artifactId>
			<version>3.0.6</version>
		</dependency>

        <--如果springboot的版本是2.1.6.RELEASE,就不需要下面的bootstrap依赖 -->
        <--springboot2.1.6.RELEASE,对应spring-cloud-starter-config版本2.0.0.RELEASE -->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-bootstrap</artifactId>
			<version>3.1.0</version>
		</dependency>

	</dependencies>

	<build>
		<finalName>qywxzj</finalName>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
		
	</build>


</project>

3、resource/bootstrap.properties文件配置如下。这里必须要注意,不能使用application.properties,否则系统是无法读取到配置信息的,原因未知。

# read mysql db
spring.application.name=qywxzj


## quote config server
spring.cloud.config.uri=http://localhost:9092/ncs
spring.cloud.config.fail-fast=true
spring.cloud.config.name=qywxzj
spring.cloud.config.label=master
spring.cloud.config.profile=test
spring.cloud.config.username=admin
spring.cloud.config.password=admin

4、启动类上必须添加@EnableDiscoveryClient

package cn.renkai721;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import lombok.extern.slf4j.Slf4j;
import springfox.documentation.oas.annotations.EnableOpenApi;


@SpringBootApplication(scanBasePackages = "cn.renkai721")
@EnableTransactionManagement
@MapperScan("cn.**.dao")
@Slf4j
@EnableOpenApi
@EnableDiscoveryClient
public class QywxzjApplication {


	public static void main(String[] args) {
		SpringApplication.run(QywxzjApplication.class, args);
		log.info("swagger api=http://ip:port/qywxzj/swagger-ui.html");
		log.info("swagger api=http://ip:port/qywxzj/doc.html");
	}


}

5、新建一个配置文件类。

package cn.renkai721.configuration;

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;


@Configuration
@Data
@Component
public class QywxProperties {

    // 第三方应用
    public static String myApp = "myApp";

    @Value("${myApp.server}")
    private String myAppServer;
    @Value("${ali.rocketmq.qwzj.instanceId}")
    private String instanceId;
    @Value("${ali.rocketmq.qwzj.topic}")
    private String topic;

}

6、新建一个controller测试。

package cn.renkai721.controller;


import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import cn.renkai721.configuration.QywxProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;

import springfox.documentation.annotations.ApiIgnore;


@Controller
@Slf4j
public class IndexController {

	@Resource
	private QywxProperties qywxProperties;

	@ApiIgnore
	@RequestMapping(value = "/testDiZhi", method = RequestMethod.GET)
	@ResponseBody
	public String testDiZhi() {
		String callback = qywxProperties.getMyAppServer();
		return callback;
	}


}

7、在浏览器输入http://localhost:9091/qywxzj/testDiZhi,返回如下

http://192.168.1.120:9091/qywxzj/

--------------------------------------到此,springboot+springcloud从数据库读取配置文件结束

--------------------------------------扩展

1、如果需要从svn,git读取配置文件的,自行了解。建议使用springboot+nacos,这样比较方便简单。

2、参照地址如下

SpringBoot ConfigServer配置中心 | 无业游民

spring cloud config将配置存储在数据库中-蒲公英云

springboot-config-Server配置文件服务搭建_孟海滨的博客-CSDN博客

  Java知识库 最新文章
计算距离春节还有多长时间
系统开发系列 之WebService(spring框架+ma
springBoot+Cache(自定义有效时间配置)
SpringBoot整合mybatis实现增删改查、分页查
spring教程
SpringBoot+Vue实现美食交流网站的设计与实
虚拟机内存结构以及虚拟机中销毁和新建对象
SpringMVC---原理
小李同学: Java如何按多个字段分组
打印票据--java
上一篇文章      下一篇文章      查看所有文章
加:2022-07-03 10:36:15  更:2022-07-03 10:37:00 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/23 17:15:40-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码