美文网首页SpringCloud_Alibaba
十、Gateway网关服务搭建和配置

十、Gateway网关服务搭建和配置

作者: 轻轻敲醒沉睡的心灵 | 来源:发表于2020-12-15 21:17 被阅读0次

    1. 新建服务,pom文件

    新建gateway-server服务,pom文件如下:

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.2.12.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
        <groupId>com.test</groupId>
        <artifactId>gateway-server</artifactId>
        <version>1.0.0-SNAPSHOT</version>
        <name>gateway-server</name>
        <description>gateway网关服务</description>
    
        <properties>
            <java.version>1.8</java.version>
            <spring-cloud-alibaba.version>2.2.1.RELEASE</spring-cloud-alibaba.version>
            <spring-cloud.version>Hoxton.SR9</spring-cloud.version>
        </properties>
    
        <dependencies>
            <!-- 测试路由用的,
            可访问 http://ip:port/actuator/gateway/routes 
            查看路由是否配置生效 -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-actuator</artifactId>
            </dependency>
            <!-- Nacos注册和服务配置,网关也要放到nacos上的 -->
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
            </dependency>
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
            </dependency>
            <!-- 后续关联sentinel用 -->
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-gateway</artifactId>
            </dependency>
            <!-- 使用openfeign的 -->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-openfeign</artifactId>
            </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>
                <exclusions>
                    <exclusion>
                        <groupId>org.junit.vintage</groupId>
                        <artifactId>junit-vintage-engine</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>javax.servlet-api</artifactId>
            </dependency>
            
            <!-- log4j2 -->
            <!-- Spring Boot官方文档中解释,在启用spring-boot-starter后会默认使用logback作为日志框架, 本项目选用log4j2,因此需要全局exclude掉Spring 
                Boot默认日志 -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter</artifactId>
                <exclusions>
                    <exclusion>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-starter-logging</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-log4j2</artifactId>
            </dependency>
        </dependencies>
    
        <dependencyManagement>
            <dependencies>
                <dependency>
                    <groupId>org.springframework.cloud</groupId>
                    <artifactId>spring-cloud-dependencies</artifactId>
                    <version>${spring-cloud.version}</version>
                    <type>pom</type>
                    <scope>import</scope>
                </dependency>
                <dependency>
                    <groupId>com.alibaba.cloud</groupId>
                    <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                    <version>${spring-cloud-alibaba.version}</version>
                    <type>pom</type>
                    <scope>import</scope>
                </dependency>
            </dependencies>
        </dependencyManagement>
    
        <build>
            <finalName>gateway-service</finalName>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                    <configuration>
                        <excludes>
                            <exclude>
                                <groupId>org.projectlombok</groupId>
                                <artifactId>lombok</artifactId>
                            </exclude>
                        </excludes>
                    </configuration>
                </plugin>
                <!-- 编译打包跳过test -->
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <configuration>
                        <skip>true</skip>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </project>
    

    特别注意:

    • Spring Cloud Gateway 不使用 Web 作为服务器,而是 使用 WebFlux 作为服务器,Gateway 项目已经依赖了 starter-webflux,所以这里 千万不要依赖 starter-web
    • 由于过滤器等功能依然需要 Servlet 支持,故这里还需要依赖 javax.servlet:javax.servlet-api

    2. 跨域配置

    因为不是Web 作为服务器,和其他的稍有不同

    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.http.HttpHeaders;
    import org.springframework.web.cors.CorsConfiguration;
    import org.springframework.web.cors.reactive.CorsWebFilter;
    import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
    import org.springframework.web.reactive.config.CorsRegistry;
    import org.springframework.web.reactive.config.WebFluxConfigurer;
    
    /**
     * 跨域配置
     */
    @Configuration
    public class CorsConfig implements WebFluxConfigurer 
      
      @Override
      public void addCorsMappings(CorsRegistry registry) {
          registry.addMapping("/**")
                  .allowCredentials(true)
                  .allowedOrigins("*")
                  .allowedHeaders("*")
                  .allowedMethods("*")
                  .exposedHeaders(HttpHeaders.SET_COOKIE);
      }
      
      /**
       * 跨域过滤器
       * @return
       */
      @Bean
      public CorsWebFilter corsWebFilter() {
          CorsConfiguration corsConfiguration = new CorsConfiguration();
          corsConfiguration.setAllowCredentials(true);
          corsConfiguration.addAllowedHeader("*");
          corsConfiguration.addAllowedMethod("*");
          corsConfiguration.addAllowedOrigin("*");
          corsConfiguration.addExposedHeader(HttpHeaders.SET_COOKIE);
          UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();
          corsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
          return new CorsWebFilter(corsConfigurationSource);
      }
    }
    

    3. 启动文件添加@EnableFeignClients注解

    @SpringBootApplication
    @EnableDiscoveryClient
    @EnableFeignClients
    public class GatewayServerApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(GatewayServerApplication.class, args);
        }
    
    }
    

    4. nacos中配置信息

    # 1.server
    server:
      port: 10000
    # 2.log
    logging:
      level:
        org.springframework.cloud.gateway: info
    # 3. openfeign
    feign:
      sentinel:
        enabled: true
    # 4. 为了监控网关
    management:
      endpoints:
        web:
          exposure:
            include: "*"
    # 5.spring
    spring: 
      # 统一设置返回的时间格式
      jackson: 
        date-format: yyyy-MM-dd HH:mm:ss
        time-zone: GMT+8
        default-property-inclusion: NON_NULL
      cloud: 
        gateway:
          discovery:
            locator:
              enabled: true
          routes:
              # 自定义路由 ID
            - id: service-dict
              # 采用 LoadBalanceClient 方式请求,以 lb:// 开头,后面的是注册在 Nacos 上的服务名
              uri: lb://service-dict
              # Predicate 翻译过来是“谓词”的意思,必须,主要作用是匹配用户的请求,有很多种用法
              predicates:
                # 路径匹配,以 api 开头,直接配置是不生效的,看 filters 配置
                - Path=/api/dict/**
              filters:
                # 前缀过滤,默认配置下,我们的请求路径是 http://localhost:9000/myshop-service-consumer-item/** 这时会路由到指定的服务
                # 此处配置去掉 1 个路径前缀,再配置上面的 Path=/api/**,就能按照 http://localhost:9000/api/** 的方式访问了
                - StripPrefix=1
            - id: service-file
              uri: lb://service-file
              predicates:
                - Path=/api/file/**
              filters:
                - StripPrefix=1
    

    相关文章

      网友评论

        本文标题:十、Gateway网关服务搭建和配置

        本文链接:https://www.haomeiwen.com/subject/yeqggktx.html