Kite的学习历程SpringCloud之Gateway网关路由配置

    技术2022-07-11  117

    Kite学习历程的第二十四天

    目录

    Kite学习历程的第二十四天1. Gateway网关路由配置1. 1 创建cloud-gateway-gateway-9527网关微服务1.1.1 修改pom.xml引入依赖文件1.1.2 创建application.xml依赖文件1.1.3 创建主启动类 2 进行测试

    1. Gateway网关路由配置

    创建一个网关的微服务,并且注册进eureka注册中心

    1. 1 创建cloud-gateway-gateway-9527网关微服务

    1.1.1 修改pom.xml引入依赖文件

    注意这里不要引入: spring-boot-starter-web mybatis-spring-boot-starter依赖

    <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> <!--引入自己创建的entities包--> <dependency> <groupId>cn.kitey.spring</groupId> <artifactId>cloud-api-commons</artifactId> <version>${project.version}</version> </dependency> <!--热部署--> <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>

    1.1.2 创建application.xml依赖文件

    首先设置端口号 9527配置微服务名称 :cloud-gateway配置路由转发(我这里配置了三个) 一个为8001 的获取id的方法 一个为获取端口号的方法 一个时访问腾讯新闻的路由转发 - id: payment_routh # #匹配后提供服务的路由地址 uri: http://localhost:8001 predicates: # #断言,路径相匹配的进行路由 - Path=/payment/get/** - id: payment_routh2 uri: http://localhost:8001 predicates: - Path=/payment/lb/** - id: payment_routh3 uri: https://new.qq.com predicates: - Path=/ch/world/ 将该服务注册进行eureka注册中心 server: port: 9527 spring: application: name: cloud-gateway cloud: gateway: routes: # 路由的id,没有固定的规则进行要求,建议配合服务名 - id: payment_routh # #匹配后提供服务的路由地址 uri: http://localhost:8001 predicates: # #断言,路径相匹配的进行路由 - Path=/payment/get/** - id: payment_routh2 uri: http://localhost:8001 predicates: - Path=/payment/lb/** - id: payment_routh3 uri: https://new.qq.com predicates: - Path=/ch/world/ eureka: instance: hostname: cloud-gateway=service client: register-with-eureka: true fetch-registry: true service-url: #服务提供正provider注册进eureka服务列表中 defaultZone: http://eureka7001.com:7001/eureka

    1.1.3 创建主启动类

    package cn.kitey.springclou; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; @SpringBootApplication @EnableEurekaClient public class GateWayMain9527 { public static void main(String[] args) { SpringApplication.run(GateWayMain9527.class,args); } }

    2 进行测试

    启动注册中心7001, 服务器8001, 以及网关9527

    访问:http://eureka7001.com:7001/ 进入注册中心查看: 访问:通过路由转发访问 http://localhost:9527/payment/get/1 3 通过路由转发访问腾讯新闻 http://localhost:9527/ch/world/ 通过以上测试表明配置完成!
    Processed: 0.010, SQL: 9