springcloud整合网关(springcloud-gateway)

pom引入依赖


    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-gateway</artifactId>
    </dependency>

    <!-- 服务注册 -->
    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
    </dependency>

application.yml文件内容

server:
  port: 8099
spring:
  application:
    name: serviceGateway
  # nacos服务地址
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848
    gateway:
      #使用服务发现路由
      discovery:
        locator:
          enabled: true
      routes:
        - id: service-hosp #设置路由id  #设置路由断言,代理servicerId为auth-service的/auth/路径
          uri: lb://serviceHosp #设置路由的uri
          predicates:
            - Path=/*/hosp/**

        - id: service-cmn 
          uri: lb://service-cmn
          predicates:
            - Path=/*/cmn/**

处理跨越问题

@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);
    }
}

前端访问后端端口直接配置为网关的端口,路径不变
在这里插入图片描述
nacos服务列表为
在这里插入图片描述

上一篇:Redis7降级6备份不过期数据操作