网关的功能

服务工程结构

添加依赖

leadnews-gateway模块中添加网关依赖:

pom.xml
<dependencies>
<!-- gateway -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<!-- nacos -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<!-- jwt -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
</dependency>
</dependencies>

完善工程

删除leadnews-gateway下的src目录,创建leadnews-app-gateway子模块

子模块的src下创建包com.swx.app.gateway

创建启动类

AppGatewayApplication
@SpringBootApplication
@EnableDiscoveryClient
public class AppGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(AppGatewayApplication.class, args);
}
}

配置文件

resources下创建bootstrap.yaml

bootstrap.yaml
server:
port: 51601
spring:
application:
name: leadnews-app-gateway
cloud:
nacos:
discovery:
server-addr: xxx.xxx.xxx.xxx:8848
config:
server-addr: xxx.xxx.xxx.xxx:8848
file-extension: yml

其他配置信息使用Nacos配置中心配置,配置完成点击发布即可

spring:
cloud:
gateway:
globalcors:
cors-configurations:
'[/**]': # 匹配所有请求
allowedOrigins: '*' # 跨域处理,允许所有的域
allowedMethods: # 支持的方法
- GET
- POST
- PUT
- DELETE
routes:
- id: user
uri: lb://leadnews-user
predicates:
- Path=/user/**
filters:
- StripPrefix= 1

启动项目

启动AppGatewayApplication网关服务

使用接口测试工具访问:

http://localhost:51601/user/api/v1/login/login_auth
  • 51601:是配置的网关端口
  • /user:是配置的网关前缀,路由时会去掉该前缀