Nacos作为注册中心和配置中心,下面结合Spring Cloud Gateway作为网关一起进行尝试。
网关是所有微服务的门户,常用的应用场景有请求路由,服务限流、统一鉴权等。Spring Cloud Gateway作为网关,几个关键概念如下
实例
项目结构参考如下
Nacos服务作为注册中心和配置中心
项目前缀-gateway工程作为服务网关
项目前缀-order作为订单服务
项目前缀-product作为商品服务
1、启动Nacos服务,具体下载安装启动请参考上篇《https://blog.csdn.net/leijie0322/article/details/126426099?spm=1001.2014.3001.5501》
windows环境下进入bin目录,执行如下命令start -m standalone启动即可。
2、创建gateway工程,其他参数上篇
pom依赖
<!--Spring Cloud & Alibaba-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<!-- 注册中心-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>
<!-- 配置中心 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
bootstrap.yml文件
spring:
application:
name: msbd-gateway
profiles:
active: dev
其中name对应Nacos配置管理中的Data Id,在Nacos中,Data Id的完成格式如下
${prefix}-${spring.profiles.active}.${file-extension}
server:
port: 9999
spring:
cloud:
nacos:
# 注册中心
discovery:
server-addr: http://localhost:8848
# 配置中心
config:
# 本地启动
## server-addr: ${spring.cloud.nacos.discovery.server-addr}
server-addr: http://localhost:8848
file-extension: yaml
shared-configs[0]:
data-id: youlai-common.yaml
refresh: true
gateway:
discovery:
locator:
# 使用服务发现路由
enabled: true
# 设置路由id 理论上随便写,建议用服务名
routes:
- id: mall-order
#uri: http://localhost:8803
uri: lb://mall-order
predicates:
- Path=/order/**
- id: mall-product
#uri: http://localhost:8804
uri: lb://mall-product
predicates:
- Path=/product/**
上面配置中字段的含义简单说明下:
启动类
@EnableDiscoveryClient
@SpringBootApplication
public class MsbdGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(MsbdGatewayApplication.class, args);
}
}
3、应用
启动gateway服务,order服务,product服务,在Nacos中如下

访问order服务

访问product服务

访问网关的地址


读取Nacos配置管理中order服务的配置

