Spring Cloud GateWay 简单示例
前提:提供一个注册中心,可以使用Eureka Server。供gateway转发请求时获取服务实例。
一、新建GateWay项目
1、引入maven依赖
<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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
2、在主类上启用服务发现注册注解 @EnableDiscoveryClient
3、配置文件application.yml内容如下:
# 注册中心
eureka:
client:
service-url:
defaultZone: http://test:123456@localhost:9090/os/eureka/
fetch-registry: true
register-with-eureka: true
spring:
application:
name: gateway-service
cloud:
gateway:
discovery:
locator:
enabled: true
lower-case-service-id: true # 服务名小写
routes:
- id: consumer-service #路由的ID,没有固定规则但求唯一,建议配合服务名
uri: lb://consumer-service # 匹配后提供服务的路由地址,lb代表从注册中心获取服务,且以负载均衡方式转发
predicates:
- Path=/consumer/** #断言,路径相匹配的进行路由
filters: # 加上StripPrefix=1,否则转发到后端服务时会带上consumer前缀
- StripPrefix=1
server:
port: 9999
# 暴露监控端点
management:
endpoints:
web:
exposure:
include: "*"
endpoint:
health:
show-details: always
二、新建服务提供者项目ConsumerService
1、引入maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
2、在主类上启用服务发现注册注解 @EnableDiscoveryClient
3、application.yml内容如下:
server:
port: 9700
spring:
application:
name: consumer-service
eureka:
client:
service-url:
defaultZone: http://test:123456@localhost:9090/os/eureka/
fetch-registry: true
register-with-eureka: true
4、新建 IndexController ,添加一个 hello 方法,传入name参数,访问后返回 hi + name 字符串
@RestController
public class IndexController {
@RequestMapping("/hello")
public String hello(String name){
return "hi " + name;
}
}
5、启动eureka、gateway、consumerservice,gateway和consumerservice都注册在eureka了。

通过网关访问consumer-service的hello方法,http://localhost:9999/consumer/hello?name=zy ,效果如下,说明请求已经转发到consumer-service服务上了。
时刻与技术进步,每天一点滴,日久一大步!!!
本博客只为记录,用于学习,如有冒犯,请私信于我。

浙公网安备 33010602011771号