SpringBoot 整合 gateway

1.添加依赖

1.1 在springboot项目中注意 pom文件配置<parent>节点,否则nacos依赖会出问题

<parent>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-parent</artifactId>
	<version>2.3.2.RELEASE</version>
</parent>

1.2 添加springcloud alibaba nacos 配置注册依赖

<!-- nacos-config配置中心依赖 -->
<dependency>
	<groupId>com.alibaba.cloud</groupId>
	<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
	<version>2.2.3.RELEASE</version>
</dependency>
<!-- nacos-discovery注册中心依赖 -->
<dependency>
	<groupId>com.alibaba.cloud</groupId>
	<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
	<version>2.2.3.RELEASE</version>
</dependency>

1.3 添加 spring-cloud-gateway依赖

<!--在springboot的pom文件中,该依赖已经集成了springMVC等web启动器,不需要再添加spring-boot-starter-web 依赖了-->
<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-gateway</artifactId>
	<version>2.2.3.RELEASE</version>
</dependency>

2.配置

由于节点比较多使用properties个人觉得不是很好看,也不便维护,所以使用yml文件配置

2.1 配置application.properties

spring.application.name= springboot-gateway-service
spring.main.allowBeanDefinitionOverriding= true
spring.profiles.active= dev
server.port= 9992

2.2 配置application-dev.yml文件

spring:
  cloud:
    # nacos 配置
    nacos:
      # 服务注册配置
      discovery:
        server-addr: 127.0.0.1:8848

    # gateway 配置
    gateway:
      discovery:
        locator:
          #表明gateway开启服务注册和发现的功能,并且spring cloud gateway自动根据服务发现为每一个服务创建了一个router,这个router将以服务名开头的请求路径转发到对应的服务
          enabled: true
          #是将请求路径上的服务名配置为小写(因为服务注册的时候,向注册中心注册时将服务名转成大写的了
          lowerCaseServiceId: true
          #另一种写法
          #lower-case-service-id: true
      #路由配置
      routes:
        # nacos中的服务1(每个服务中可集群多个应用,可在nacos中配置与治理)
        - id: springboot-base-service
          uri: lb://springboot-base-service
          predicates:
            - Path=/springboot/**
          filters:
            # 校验
            # 去除一个前缀
            - StripPrefix=1

      #跨域设置
      globalcors:
        corsConfigurations:
          '[/**]':
            allowedOriginPatterns: "*"
            allowed-methods: "*"
            allowed-headers: "*"
            allow-credentials: true
            exposedHeaders: "Content-Disposition,Content-Type,Cache-Control"

# 安全配置
security:
  # 不校验白名单
  ignore:
    insurance-bff-app:
      whites:
        - /springboot/user/login
        - /springboot/user/register
        - /springboot/v2/api-docs

# 暴露监控端点
management:
  endpoints:
    web:
      exposure:
        include: '*'

3.启动使用

在启动过程中,查看在nacos上注册的服务是否都被拉下来

3.1 springboot-base-service服务接口

3.2 通过 gateway调用的springboot-base-service服务接口 

猜你喜欢

转载自blog.csdn.net/qq_37778018/article/details/122626157