当服务需要做url鉴权管理、流量监控、统一身份认证等时工作时,在所有消费者服务集群之前需增加网关服务。
1 在根项目下创建Maven Module网关项目springcloud-gateway:
此项目需以eureka消费者的角色注册入eureka服务中心。
pom.xml如下:
<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">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.mxx.springcloud</groupId>
<artifactId>springcloud-root</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>springcloud-gateway</artifactId>
<name>gateway</name>
<description>gateway</description>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!-- spring-admin-actuator相关 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
</project>
启动类:GatewayApplication.java
package com.mxx.springcloud.gateway;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableEurekaClient
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
}
配置application.yml:
#端口
server:
port: 9000
#应用名称
spring:
application:
name: gateway-eureka-client
cloud:
gateway:
routes:
- id: path_route
#uri: http://cxytiandi.com
uri: lb://euraka-ribbon-consumer
predicates:
- Path= /testConsumer
#eureka
eureka:
instance:
instance-id: euraka-client-a-local:9000
prefer-ip-address: true
client:
service-url:
defaultZone: http://192.168.125.66:8888/eureka/
#管理端点的配置
management:
endpoints:
web:
exposure:
include: "*"
endpoint:
health:
show-details: ALWAYS
测试:http://网关ip:9000//testConsumer,
同消费服务:http://euraka-ribbon-consumer:9001//testConsumer,
本文详细介绍如何使用Spring Cloud Gateway实现服务路由、鉴权及统一身份认证等功能。通过具体步骤,包括项目搭建、依赖引入、配置文件设置及启动类编写,展示了网关服务在微服务架构中的重要作用。
2392

被折叠的 条评论
为什么被折叠?



