25. 尚融宝网关配置

一、创建模块service-gateway

1、pom

<dependencies>
    
    <dependency>
        <groupId>org.springframework.cloudgroupId>
        <artifactId>spring-cloud-starter-gatewayartifactId>
    dependency>
    
    <dependency>
        <groupId>com.alibaba.cloudgroupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
    dependency>
dependencies>

2、application.yml

server:
  port: 80 # 服务端口
spring:
  profiles:
    active: dev # 环境设置
  application:
    name: service-gateway # 服务名
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 # nacos服务地址
    gateway:
      discovery:
        locator:
          enabled: true # gateway可以发现nacos中的微服务,并自动生成转发路由

4、logback-spring.xml

修改日志输出目录名为 gateway

5、main

package com.indi.srb.gateway;

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

6、启动网关

**注意:**因为nginx和网关同时使用了80端口,因此先停止nginx,然后再启动网关

nginx.exe -s stop

7、测试自动路由转发

http://localhost/service-core/admin/core/integralGrade/list

规则:

http://Gateway_HOST:Gateway_PORT/serviceId/**

二、路由配置

1、基本配置

application.yml文件中添加路由配置

#spring:
# cloud:
#   gateway:
      routes:
      - id: service-core
        uri: lb://service-core
        predicates:
        - Path=/*/core/**
      - id: service-sms
        uri: lb://service-sms
        predicates:
        - Path=/*/sms/**
      - id: service-oss
        uri: lb://service-oss
        predicates:
        - Path=/*/oss/**

2、测试路由转发

http://localhost/admin/core/integralGrade/list

三、跨域配置

1、配置文件

service-gateway中添加跨域配置

com.indi.srb.gateway.config

CorsConfig.java

package com.indi.srb.gateway.config;

@Configuration
public class CorsConfig {
     
    @Bean
    public CorsWebFilter corsFilter() {
     
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true); //是否允许携带cookie
        config.addAllowedOrigin("*"); //可接受的域,是一个具体域名或者*(代表任意域名)
        config.addAllowedHeader("*"); //允许携带的头
        config.addAllowedMethod("*"); //允许访问的方式
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return new CorsWebFilter(source);
    }
}

2、删除后端跨域配置

删除所有微服务中的跨域注解@CrossOrigin

你可能感兴趣的:(尚融宝,Spring,Cloud,网关,gateway)