栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

GateWay网关

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

GateWay网关

1.概念:

Spring cloud gateway是spring官方基于Spring 5.0、Spring Boot2.0和Project Reactor等技术开发的网关,Spring Cloud Gateway旨在为微服务架构提供简单、有效和统一的API路由管理方式,Spring Cloud Gateway作为Spring Cloud生态系统中的网关,目标是替代Netflix Zuul,其不仅提供统一的路由方式,并且还基于Filer链的方式提供了网关基本的功能,例如:安全、监控/埋点、限流等

如图:gateway网关流程图如下

 

2.SpringBoot配置GateWay网关 (1)pom.xml文件:
  
      org.springframework.cloud
      spring-cloud-starter-gateway
  
​
  
  
      com.alibaba.cloud
      spring-cloud-starter-alibaba-nacos-discovery
  
(2)application.yml文件:
    # 服务端口
    server:
      port: 80
​
    spring:
      application:
        name: service-gateway # 服务名
      # nacos服务地址
      cloud:
        nacos:
          discovery:
            server-addr: 127.0.0.1:8848
        gateway:
          discovery:
            locator:
              enabled: true #开启从注册中心动态创建路由的功能,利用微服务名进行路由
          #设置路由id
          routes:
            - id: service1  #路由的ID,没有固定规则,但要求唯一,建议配合服务名
              uri: lb://service1  #匹配后提供服务的路由地址
              predicates:
                - Path=service2
    @SpringBootApplication
    @EnableDiscoveryClient //开启nacos服务注册
    public class GateWayMainApplication {
        public static void main(String[] args) {
            SpringApplication.run(GateWayMainApplication.class,args);
        }
    }
(4)编写配置类:
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.cors.CorsConfiguration;
    import org.springframework.web.cors.reactive.CorsWebFilter;
    import org.springframework.web.cors.reactive.UrlbasedCorsConfigurationSource;
    import org.springframework.web.util.pattern.PathPatternParser;
​
    
    @Configuration
    public class CorsConfig {
        @Bean
        public CorsWebFilter corsFilter() {
            CorsConfiguration config = new CorsConfiguration();
            config.addAllowedMethod("*");
            config.addAllowedOrigin("*");
            config.addAllowedHeader("*");
            UrlbasedCorsConfigurationSource source = new                      
                                UrlbasedCorsConfigurationSource(new PathPatternParser());
            source.registerCorsConfiguration("/**", config);
            return new CorsWebFilter(source);
        }
    }
​
(5)测试网关:

如图:测试入口改成 ==> http://localhost/

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/306420.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号