Springcloud gateway使用

Springcloud gateway使用

学习中笔记


1、基于代码配置

  • 引入依赖
<dependency>
    <groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
  • 注解配置
    在这里插入图片描述

2、配置文件中配置网关

  • 引入依赖
  • 配置文件设置
    在这里插入图片描述
    字段含义:
    Id:路由id 唯一
    Url:目标服务地址
    Predicates:路由条件,Predicate 接受一个输入参数,返回一个布尔值结果。该接口包含多种默认方法来将 Predicate 组合成其他复杂的逻辑(比如:与,或,非)。这里使用path
    Filters: 过滤条件设置过滤1个路径,2表示两个路径,以此类推。
  • 访问方式
    http:// g a t e w a y I P : {gatewayIP}: gatewayIP:{gatewayPORT}/${id}/接口url
    访问http://127.0.0.1:8203/wx-pa-api/root/getTest会路由到上路地址http://127.0.0.1:8086/root/getTest

3、使用服务发现实现动态路由,路由断言及拦截均为默认

  • 引入依赖
dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
  • 配置文件
    #表明gateway开启服务注册和发现的功能,并且spring cloud gateway自动根据服务发现为每一个服务创建了一个router,这个router将以服务名开头的请求路径转发到对应的服务
    sring.cloud.gateway.discovery.locator.enabled=true
    #将请求路径上的服务名配置为小写(因为服务注册的时候,向注册中心注册时将服务名转成大写的了)
    spring.cloud.gateway.discovery.locator.lower-case-service-id=true

4、Gateway路由断言及规则动态加载(使用nacos)

基于gateway RouteDefinitionWriter提供的增删路由功能及nacos的监听功能在这里插入图片描述在这里插入图片描述

  • 配置
@Component
public class NacosDynamicRouteService implements ApplicationEventPublisherAware {

    private static final Logger log = LoggerFactory.getLogger(NacosDynamicRouteService.class);

    @Autowired
    private RouteDefinitionWriter routedefinitionWriter;

    private ApplicationEventPublisher publisher;

    private String dataId = "gateway-router.properties";
    private String group = "DEFAULT_GROUP";
    @Value("${spring.cloud.nacos.discovery.server-addr}")
    private String serverAddr;
    @Value("${spring.cloud.nacos.discovery.namespace}")
    private String namespace;

    private static final List<String> ROUTE_LIST = new ArrayList<>();

    @PostConstruct
    public void dynamicRouteByNacosListener() {
        try {
            Properties prop = new Properties();
            prop.put("serverAddr", serverAddr);
            prop.put("namespace", namespace);
            ConfigService config = NacosFactory.createConfigService(prop);
            String content = config.getConfig(dataId, group, 5000);
            publisher(content);
            config.addListener(dataId, group, new Listener() {
                @Override
                public void receiveConfigInfo(String config) {
                    publisher(config);
                }
                @Override
                public Executor getExecutor() {
                    return null;
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     *  增加路由
     *
     *  @author: earl
     */
    public Boolean addRoute(RouteDefinition def) {
        try {
            routedefinitionWriter.save(Mono.just(def)).subscribe();
            ROUTE_LIST.add(def.getId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }
    /**
     *  删除路由
     *  
     *  @author: earl
    */
    public Boolean clearRoute() {
        for(String id: ROUTE_LIST) {
            routedefinitionWriter.delete(Mono.just(id)).subscribe();
        }
        ROUTE_LIST.clear();
        return false;
    }
    /**
     *  发布路由
     *  
     *  @author: earl
    */
    private void publisher(String config) {
        clearRoute();
        try {
            log.info("重新更新动态路由");
            List<RouteDefinition> gateway = JSONObject.parseArray(config, RouteDefinition.class);
            for(RouteDefinition route: gateway) {
                addRoute(route);
            }
            publisher.publishEvent(new RefreshRoutesEvent(this.routedefinitionWriter));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher app) {
        publisher = app;
    }
}

在nacos做路由新增后网关服务变回进行更新
在这里插入图片描述

栗子:
1、nacos添加如下配置(namespace需要注意相同,dataid为gateway-router.properties)

[
    {
    "filters": [{
        "name": "StripPrefix",
        "args": { "_genkey_0": "1" }
    }],
    "id": "wx-pa-api",
    "order": 0,
    "predicates": [{
        "args": {
            "pattern": "/**"
        },
        "name": "Path"
    }],
    "uri": "lb://wx-pa-api"
}
]

可以达到配置文件一样的效果,配置文件lb://wx-pa-api更换为uri:http://127.0.0.1:8086其他配置与不使用nacos相同
lb协议是 spring cloud gateway 在微服务中自动为我们创建的负载均衡uri
lb://serviceName 表示启用Gateway 的负载均衡功能。

5、网关跨域配置

@Configuration
public class GlobalCorsConfig {

    @Bean
    public CorsWebFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedMethod("*");
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
        source.registerCorsConfiguration("/**", config);
        return new CorsWebFilter(source);
    }

}

6、GateWay⾼可⽤

⽹关作为⾮常核⼼的⼀个部件,如果挂掉,那么所有请求都可能⽆法路由处理,因此我们需要做GateWay的⾼可⽤。
GateWay的⾼可⽤很简单:可以启动多个GateWay实例来实现⾼可⽤,在GateWay的上游使⽤Nginx等负载均衡设备进⾏负载转发以达到⾼可⽤。

#配置多个GateWay实例
upstream gateway {
    server 127.0.0.1:8202;
    server 127.0.0.1:8203;
}
location / {
     proxy_pass http://gateway;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值