3 GateWay配置路由的两种方式

GateWay配置路由的两种方式

我们现在知道了GateWay的基本配置路由的方式,通过YML来完成,但是实际上GateWay还提供了另外一种配置方式.

GatewayConfig

其实这种配置方式就是通过代码的方式进行配置,也就是通过@Bean注入一个RouteLocator

具体操作

首先我们在新建一个GateWayConfig,其实这里的配置对应的就是我们之前在YML中配置的对应内容

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 GateWayConfig {
    /*
    配置了一个id为path_msb1的路由规则
    当访问地址http://localhost:9999/msb/**
    就会转发到http://localhost:9001/nacos-provider/msb/任何地址
     */

    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder routeLocatorBuilder){
        // 构建多个路由routes
        RouteLocatorBuilder.Builder routes = routeLocatorBuilder.routes();
        // 具体路由地址
        routes.route("path_msb",r -> r.path("/msb/**").uri("http://localhost:9001/nacos-provider")).build();
        // 返回所有路由规则
        return routes.build();
    }
}

我们在9001的DemoController中添加一个控制器

@GetMapping(value = "/custom")
public String customTest(){
    return "网关配置测试~~costom";
}

这个时候我们就可以测试了,启动9999网关服务和9001微服务,然后访问地址:http://localhost:9999/msb/custom 就可以转发到9001中具体的接口中了
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值