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服务上了。

 

posted @   codedot  阅读(976)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 字符编码:从基础到乱码解决

喜欢请打赏

扫描二维码打赏

了解更多

点击右上角即可分享
微信分享提示