目录
一,入门案例
1.1 创建gateway 模块并导入依赖
在项目中添加新的模块 shop_gateway_server ,并导入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
- 注意SpringCloud Gateway使用的web框架为webflux,和SpringMVC不兼容。引入的限流组件是 hystrix。redis底层不再使用jedis,而是lettuce。
因为这个spring-cloud-strarter-gateway 依赖里面有 下面这个依赖,所以我们不需要引入这个依赖,但是父类里面有这个依赖,所以我们把这个依赖从父类里去除,哪个模块需要这个依赖单独加进去就好了
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
1.2 配置启动类
@SpringBootApplication
public class GatewayServerApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayServerApplication.class, args);
}
}
1.3 编写配置文件
创建 application.yml 配置文件
server:
port: 8080 #服务端口
spring:
application:
name: api-gateway #指定服务名
cloud:
gateway:
routes:
#配置路由:路由id,路由到微服务的url,断言(判断条件)
- id: product-service
uri: http://127.0.0.1:9001
predicates:
- Path=/product/**
id:我们自定义的路由 ID,保持唯一
uri:目标服务地址,
predicates:路由条件,
Predicate 接受一个输入参数,返回一个布尔值结果。该接口包含多种默 认方法来将 Predicate 组合成其他复杂的逻辑(比如:与,或,非)。
filters:过滤规则,暂时没用。
上面这段配置的意思是,配置了一个 id 为 product-service的路由规则,当访问网关请求地址以 product 开头时,会自动转发到地址: http://127.0.0.1:9002/ 。配置完成启动项目即可在浏览器 访问进行测试,当我们访问地址 http://localhost:8080/product/1 时会展示页面展示如下: