SpringCloud项目中搭建网关

发布时间 2023-06-09 18:12:33作者: wzh_Official

引入依赖

点击查看代码
<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>
     <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
        </dependency>
    <dependency>
        <groupId>io.jsonwebtoken</groupId>
        <artifactId>jjwt</artifactId>
    </dependency>

编写启动类

编写bootstrap.yml配置

点击查看代码
server:
  port: 51601
spring:
  application:
    name: leadnews-app-gateway #网关微服务名称,nacos中的配置DataId要与该名称一致
  cloud:
    nacos:
      discovery:
        server-addr: 192.168.200.130:8848  #nacos地址
      config:
        server-addr: 192.168.200.130:8848
        file-extension: yml

在nacos的配置中心创建DataId为leadnews-app-gateway的yml配置

点击查看代码
spring:
  cloud:
    gateway:
      globalcors:
        add-to-simple-url-handler-mapping: true
        corsConfigurations:
          '[/**]':
            allowedHeaders: "*"
            allowedOrigins: "*"
            allowedMethods:
              - GET
              - POST
              - DELETE
              - PUT
              - OPTION
      routes:
        # 平台管理
        - id: user
          uri: lb://leadnews-user  #这个是要路由到具体某个微服务的名称。
          predicates:
            - Path=/user/**
          filters:
            - StripPrefix= 1