springcloud远程配置中心案例
1.创建一个configserver微服务,负责配置的读写操作;而configserver微服务配置读取远程配置的configserver
2.configserver微服务配置:
application.yml
spring:
profiles:
active: jdbc
application:
name: config-server
datasource:
url: jdbc:mysql://127.0.0.1:3306/springcloudconfig?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8&serverTimezone=GMT%2B8
username: root
password: XXXX
driver-class-name: com.mysql.jdbc.Driver
cloud:
config:
label: master
server:
jdbc: true
server:
port: 8888
spring.cloud.config.server.jdbc.sql: SELECT config_key, config_value FROM config_properties_t WHERE application_name =? AND config_profile =? AND config_label =?
cloud.config.lable: 对应数据库表中config_label字段
数据库脚本:
CREATE TABLE `config_properties_t` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`config_key` varchar(50) COLLATE utf8_bin NOT NULL,
`config_value` varchar(500) COLLATE utf8_bin DEFAULT NULL,
`application_name` varchar(255) COLLATE utf8_bin NOT NULL,
`config_profile` varchar(255) COLLATE utf8_bin NOT NULL,
`config_label` varchar(255) COLLATE utf8_bin DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
INSERT INTO `springcloudconfig`.`config_properties_t` (`id`, `config_key`, `config_value`, `application_name`, `config_profile`, `config_label`) VALUES ('3', 'server.port', '8880', 'microservice-name', 'dev', 'master');
INSERT INTO `springcloudconfig`.`config_properties_t` (`id`, `config_key`, `config_value`, `application_name`, `config_profile`, `config_label`) VALUES ('4', 'server.port', '8880', 'micorservice-name', 'sit', 'master');
INSERT INTO `springcloudconfig`.`config_properties_t` (`id`, `config_key`, `config_value`, `application_name`, `config_profile`, `config_label`) VALUES ('5', 'pc_url', 'www.xxx.com', 'microservice-name', 'dev', 'master');
3.configclient配置:
@SpringBootApplication
@RestController
public class SpringcloudConfigclientApplication {
public static void main(String[] args) {
SpringApplication.run(SpringcloudConfigclientApplication.class, args);
}
@Value("${pc_url}")
String url;
@RequestMapping(value = "/url")
public String hi() {
return url;
}
}
spring:
application:
name: microservice-name
cloud:
config:
uri: http://localhost:8888
fail-fast: true
profiles:
active: dev
microservice-name:对应数据库表中application_name字段
profiles.active:对应数据库表中config_profile字段 --可指定 开发环境dev SIT环境sit UAT环境uat
4.先启动configserver,再启动configclient,再访问localhost:8880/url
这个简单案例成功!!