一 工程结构
1.1 工程
1.2 搭建gatewayapi工程
1.pom文件
<dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.13</version><scope>test</scope></dependency><!--gateway--><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-gateway</artifactId><!--排除gateway 内部不兼容的 spring-webflux --><exclusions><!-- 排除web依赖--><exclusion><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></exclusion></exclusions></dependency><!--包含了sleuth+zipkin--><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-zipkin</artifactId></dependency><!--SpringCloud ailibaba nacos --><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId></dependency><!--日常通用jar包配置--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><scope>runtime</scope><optional>true</optional></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies>
2.启动类
@SpringBootApplication
@EnableDiscoveryClient
public class App
{public static void main( String[] args ){SpringApplication.run(App.class, args);System.out.println("网关启动完毕.....");}
}
3.配置文件
server:port: 7004
#服务名称
spring:application:name: mscloud-nacos-gateway-api7004zipkin:base-url: http://localhost:9411sleuth:sampler:#采样率值介于 0 到 1 之间,1 则表示全部采集probability: 1cloud:gateway:discovery:locator:enabled: true #开启从注册中心动态创建路由的功能,利用微服务名进行路由routes:- id: payment_routh #payment_route #路由的ID,没有固定规则但要求唯一,建议配合服务名#uri: http://localhost:8001 #匹配后提供服务的路由地址uri: lb://mscloud-cluster-providers #匹配后提供服务的路由地址 http://localhost:9007/payment/get/1?uname=aa 等价于 http://localhost:9003/payment/get/1predicates: ##浏览器上直接访问eureka的应用名不行:ttp://mscloud-cluster-providers/payment/get/1 这样访问不行- Path=/payment/get/** # 断言,路径相匹配的进行路由- id: payment_routh2 #payment_route #路由的ID,没有固定规则但要求唯一,建议配合服务名#uri: http://localhost:8001 #匹配后提供服务的路由地址uri: lb://nacos-payment-provider #匹配后提供服务的路由地址predicates:- Path=/payment/nacos/** # 断言,路径相匹配的进行路由- After=2023-03-12T11:52:37.485+08:00[Asia/Shanghai]#- Cookie=username,zzyy#- Header=X-Request-Id, \d+ # 请求头要有X-Request-Id属性并且值为整数的正则表达式
1.3 测试
1.启动nacos,sleuth
2.启动gatewayapi,mscloud-nacos-provider7001,mscloud-nacos-provider7002
如图:
3.访问
多次刷新:7001和7002 不停的切换