为什么配置服务器

有时候,微服务要做集群,这就意味着,会有多个微服务实例。 在业务上有时候需要修改一些配置信息,比如说 版本信息吧~ 倘若没有配置服务, 那么就需要挨个修改微服务,挨个重新部署微服务,这样就比较麻烦。

为了减少工作量,可以把 这些配置信息就会放在一个公共的地方,比如git, 然后通过配置服务器把它获取下来,然后微服务再从配置服务器上取下来。

这样只要修改git上的信息,那么同一个集群里的所有微服务都立即获取相应信息了,这样就大大节约了开发,上线和重新部署的时间了。

如图所示,我们先在 git 里保存 version 信息, 然后通过 ConfigServer 去获取 version 信息, 接着不同的视图微服务实例再去 ConfigServer 里获取 version.

SpringCloud学习笔记(八、配置服务器)_git

在git上创建配置文件

本来想在github上面创建的,结果网卡了一点,所以就在码云上创建了一个。码云可以直接用github的账号登录。

1、创建仓库

选择公开吧,免得还得输密码什么的。

SpringCloud学习笔记(八、配置服务器)_git_02

2、创建文件夹

创建一个名为respo的文件夹

SpringCloud学习笔记(八、配置服务器)_微服务_03

3、创建配置文件

创建配置文件product-view-service-dev.properties

里面就一行东西:

version = LaughterYoung springcloud version 1.0

创建子项目

创建子项目cofig-server

pom.xml

添加spring-cloud-config-serve依赖

<?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">
<parent>
<artifactId>springcloud</artifactId>
<groupId>edu.hpu.springcloud</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>

<artifactId>config-server</artifactId>


<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<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>
</dependency>

</dependencies>


</project>

配置

application.yml:

spring:
application:
name: config-server
cloud:
config:
label: master #表示分支
server:
git:
uri: https://gitee.com/LaughterYoung/springCloudConfig/ #表示git地址
searchPaths: respo #表示目录
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/

启动类

ConfigServerApplication:

package edu.hpu.springcloud;

import cn.hutool.core.util.NetUtil;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.config.server.EnableConfigServer;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@SpringBootApplication
@EnableConfigServer //表示这是一个配置服务器
@EnableDiscoveryClient
@EnableEurekaClient
public class ConfigServerApplication {
public static void main(String[] args) {
int port = 8030;
if(!NetUtil.isUsableLocalPort(port)) {
System.err.printf("端口%d被占用了,无法启动%n", port );
System.exit(1);
}
new SpringApplicationBuilder(ConfigServerApplication.class).properties("server.port=" + port).run(args);

}
}

启动并访问

运行启动类,访问地址:http://localhost:8030/version/dev

SpringCloud学习笔记(八、配置服务器)_git_04




参考:

【1】、​​http://how2j.cn/k/springcloud/springcloud-config-server/2047.html#nowhere​​​

​​​​