1、zuul路由网关
zuul包含两个最主要的功能:
- 路由功能:负责将外部的请求转发到具体的微服务实例,实现外部的统一访问入口
- 过滤功能:负责对请求的处理过程进行干预,实现请求校验
创建网关微服务外
1、导入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zuul</artifactId>
</dependency>
2、配置路由
zuul:
#ignored-services: springcloud-provider-dept # 不能再使用 springcloud-provider-dept 访问了
prefix: /icoding
ignored-services: "*" # 通配符,隐藏全部的服务
routes:
mydept.serviceId: springcloud-provider-dept
mydept.path: /mydept/**
3、启动类添加注解@EnableZuulProxy
@EnableZuulProxy // 开启 zuul 的代理
@SpringBootApplication
public class SpringCloudZuulApp9527 {
public static void main(String[] args) {
SpringApplication.run(SpringCloudZuulApp9527.class,args);
}
}
路由公共前缀,测试访问
2、分布式配置中心
SpringCloud Config为微服务提供集中化的外部配置支持
在码云创建一个仓库
得到仓库地址:https://gitee.com/aikomj/sc-config.git
创建一个Config Server 服务端
1、导入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
2、主启动类增加@EnableConfigServer注解开启配置服务器的功能
@SpringBootApplication
@EnableEurekaClient
@EnableConfigServer
public class ConfigServerApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigServerApplication.class,args);
}
}
3、配置文件application.yaml
server:
port: 3344
spring:
application:
name: sc-config
cloud:
config:
server:
git:
# git仓库地址
uri: https://gitee.com/aikomj/sc-config
# 如果是私有仓库需要填写用户名和密码,公开仓库不用填写
# username:
# password:
# 如果配置文件不在仓库根目录下,需要配置路径,如在目录 respo/xxx
# search-paths:
# 仓库分支,默认是master
# label: master
info:
app.name: 配置服务中心
company.name: jude
远程仓库https://gitee.com/aikomj/sc-config下有个文件provider-dept-dev.yml
启动工程,浏览器访问http://localhost:3344/provider-dept-dev.yml
证明配置服务中心可以从远程仓库获取配置信息。
http请求地址和资源文件映射如下:
- /{application}/{profile}[/{label}]
- /{application}-{profile}.yml
- /{label}/{application}-{profile}.yml
- /{application}-{profile}.properties
- /{label}/{application}-{profile}.properties
配置Congif client 客户端
修改两个微服务provider-dept、provider-edu从配置服务中心读取配置
1、导入依赖
<!-- 客户端的依赖配置 -->
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-config-server -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
2、配置文件bootstrap.yml或者bootstrap.properties
spring:
cloud:
config:
uri: http://localhost:3344 # 配置服务中心地址
label: master # 仓库分支
profile: dev # 环境配置
# name: provider-dept # 远程github的资源名称,不需要yml后缀的,默认与application.name相同
application.yml的配置:
为什么有两个配置文件?
application.yml 用户级别的资源配置 bootstrap.yml 系统级别的配置,优先级更高分工,bootstrap和application分离
3、测试访问远程配置
@Value("${author}")
String author;
@RequestMapping(value = "/author")
public String author(){
return author;
}
依次启动服务注册中心eureka-server、配置服务中心sc-config、provider-dept
浏览器访问http://localhost:8001/author
证明provider-dept 从配置服务中心sc-config读取了配置文件。
看provider-dept的启动过程,先是连接配置服务中心获取配置文件信息的。