网关的功能
服务工程结构
添加依赖
在leadnews-gateway
模块中添加网关依赖:
pom.xml<dependencies> <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>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId> </dependency> <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.yamlserver: 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:是配置的网关前缀,路由时会去掉该前缀