springcloud gateway使用

28 篇文章 0 订阅
11 篇文章 0 订阅

第一首先是pom文件

<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>

要添加上面的依赖

然后有两站实现方式,一种是通过yml配置实现,一种是通过配置类实现,

1配置类实现

 

import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class GatewayRoutes {
    @Bean
    public RouteLocator routeLocator(RouteLocatorBuilder builder) {
        return builder.routes()
                .route(r ->
                        r.path("/hello/**")
                                .filters(
                                        f -> f.stripPrefix(1))
                                .uri("lb://hello")
                )
                .build();
    }

这里的paht: hello/**   hello参数 ** 所有的方法  uri   lb 负载均衡  lb://hello 是注册在eureka的服务的名字

eureka:
  client:
        registerWithEureka: true
        fetchRegistry: true
        service-url:
           defaultZone: http://localhost:9601/eureka/
server:
  port: 9801

配置文件如上面的就可以了.浏览器打开http://localhost:9801/hello/get1 就可以看到相应的结果.

下面说通过配置实现:

配置文件如下:

eureka:
  client:
        registerWithEureka: true
        fetchRegistry: true
        service-url:
           defaultZone: http://localhost:9601/eureka/,http://localhost:9602/eureka/
server:
  port: 9801
spring:
   cloud:
     gateway:
       routes:
       - id: host1
         uri: http://localhost:9606
         predicates:
         - Path=/hello/**
         filters:
            - StripPrefix=1

其中的 filters: - StripPrefix=1  这个必须要有否则控制台没有错误,但是就是不能得到结果,我试了好久才知道的.

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值