Spring Cloud GateWay的简单使用及跨域配置--02

本文介绍了如何将前端项目renren-fast通过SpringCloud Gateway路由到88端口,统一接口前缀,并配置Nacos服务注册,同时处理跨域问题。涉及Gateway配置、服务发现、负载均衡和Cors配置。
摘要由CSDN通过智能技术生成

SpringCloud Gateway官网地址:Spring Cloud Gateway 

现在要将我们后台管理项目renren-fast由网关统一路由

 1.在前端renren-fast-vue将api接口请求地址统一转发到网关88端口,并且规定全部以/api为前缀。

        在static/config/index.js修改配置

/**
 * 开发环境
 */
;(function () {
  window.SITE_CONFIG = {}

  // api接口请求地址
  window.SITE_CONFIG['baseUrl'] = 'http://localhost:88/api'

  // cdn地址 = 域名 + 版本号
  window.SITE_CONFIG['domain'] = './' // 域名`
  window.SITE_CONFIG['version'] = ''   // 版本号(年月日时分)
  window.SITE_CONFIG['cdnUrl'] = window.SITE_CONFIG.domain + window.SITE_CONFIG.version
})()

2.将renren-fast注册进注册中心 

  • 添加spring-cloud-starter-alibaba-nacos-discovery并引入Common模块
        <dependency>
            <groupId>com.liucan.gulimall</groupId>
            <artifactId>gulimall-common</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
		<dependency>
			<groupId>com.alibaba.cloud</groupId>
			<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
			<version>2.1.0.RELEASE</version>
		</dependency>
  • 在application.yml中配置nacos地址
spring
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1
  • 在renren-fast主启动类上添加@EnableDiscoveryClient以开启服务注册与发现
@EnableDiscoveryClient
@SpringBootApplication
public class RenrenApplication {

	public static void main(String[] args) {
		SpringApplication.run(RenrenApplication.class, args);
	}

}

3.在gateway中配置路由

  • 在application.ym中配置路由信息
spring:
  cloud:
    gateway:
      routes:
        - id: admin_route
          uri: lb://renren-fast #lb开启负载均衡 路由到服務名為renren-fast的服务
          #路径中以api开头的请求经过过滤后都会被路由到renren-fast服务
          predicates:
          - Path=/api/**    
          filters:
          - RewritePath=/api/(?<segment>/?.*),/renren-fast/$\{segment}
          # 路径重写 /api/** 的请求路径将会被替换到/renren-fast/**

现在启动我们的项目

可以发现我们的验证码可以正常获取,尝试登陆

登录时遇到跨域问题

什么是跨域?

 出于浏览器的同源策略限制。同源策略(Sameoriginpolicy)是一种约定,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,则浏览器的正常功能可能都会受到影响。可以说Web是构建在同源策略基础之上的,浏览器只是针对同源策略的一种实现。同源策略会阻止一个域的。javascript脚本和另外一个域的内容进行交互。所谓同源(即指在同一个域)就是两个页面具有相同的协议(protocol),主机(host)和端口号(port)

这是因为我们的前端项目地址为 http://localhost:8001/#/login

而我们登录接口的地址为:http://localhost:88/api/sys/login 

端口不同,产生跨域

因为Gateway为所有请求的入口,我们可直接在Gateway模块中添加跨域的配置

跨域配置

1.在Gateway模块中新建一个config文件夹,用于存放我们的配置类

2.在config文件夹中新建一个GuliMallCorconfiguration用于配置Cors相关 

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsConfigurationSource;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.server.ServerWebExchange;

@Configuration
public class GuliMallCorsConfiguration {

    @Bean
    public CorsWebFilter corsWebFilter(){
        CorsConfigurationSource corsConfigurationSource = new CorsConfigurationSource() {
            @Override
            public CorsConfiguration getCorsConfiguration(ServerWebExchange serverWebExchange) {
                CorsConfiguration corsConfiguration = new CorsConfiguration();
                corsConfiguration.addAllowedHeader("*");
                corsConfiguration.addAllowedMethod("*");
                corsConfiguration.addAllowedOrigin("*");
                corsConfiguration.setAllowCredentials(true);


                return corsConfiguration;
            }
        };
        return new CorsWebFilter(corsConfigurationSource);
    }
}

记得用@Configuration标识这是一个配置类,并用@Bean注解将我们自定义的跨域配置类注入容器

到此,我们将renren-fast注册进nacos,并统一交由网关路由,并解决跨域问题,而且也能正常访问登录功能

在后台管理页面【分类维护】增加【三级菜单维护】

获取三级菜单数据的接口在gulimall-product商品服务中:

  1. 将gulimall-product注册进服务中心
  • 添加依赖,导入nacos服务注册与发现
        <dependency>
            <groupId>com.liucan.gulimall</groupId>
            <artifactId>gulimall-common</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
		<dependency>
			<groupId>com.alibaba.cloud</groupId>
			<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
			<version>2.1.0.RELEASE</version>
		</dependency>
  • 在gulimall-product的application.yml中配置,指定nacos地址
spring:
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848
  • 主启动类增加注解@EnableDiscoveryClient
@EnableDiscoveryClient
@SpringBootApplication
public class GulimallProductApplication {

    public static void main(String[] args) {
        SpringApplication.run(GulimallProductApplication.class, args);
    }

}
  • 启动主启动类,进入nacos,可以看见gulimall-product此实例

2. 将gulimall-product交由Gateway进行统一的路由管理

  • 进入Gateway模块,在 application.yml中新增商品服务的路由信息
spring:
  cloud:
    gateway:
      routes:
       - id: product_route            # 商品服务
         uri: lb://gulimall-product #lb開啓負載均衡 路由到服務名為gulimall_product的服务
         predicates:
          - Path=/api/product/**
         filters:
          - RewritePath=/api/product/(?<segment>/?.*),/product/$\{segment}

       - id: admin_route
         uri: lb://renren-fast #lb開啓負載均衡 路由到服務名為renren-fast的服务
         predicates:
         - Path=/api/**
         filters:
         - RewritePath=/api/(?<segment>/?.*),/renren-fast/$\{segment}

        其中:- RewritePath:是将我们前面的地址替换成后面的地址

                例如:我们不通过网关直接访问商品服务中的获取三级菜单接口地址为:localhost://10000/product/category/list/tree

                 而我们通过网关访问商品服务中的获取三级菜单接口地址为:localhost:80//api/product/category/list/tree

                   所以其实我们需要将api/product替换成/product即可

3.在前端渲染数据,树形结构使用的是elementUI的Tree树形控件

<template>
  <div>
    <el-tree :data="data" :props="defaultProps" @node-click="handleNodeClick"></el-tree>
  </div>
</template>

<script>
//这里可以导入其他文件(比如:组件,工具 js,第三方插件 js,json

//例如:import 《组件名称》 from '《组件路径》';

export default {
  //import 引入的组件需要注入到对象中才能使用
  components: {},
  props: {},
  data() {
    //这里存放数据
    return {
      data: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  //计算属性 类似于 data 概念
  computed: {},
  //监控 data 中的数据变化
  watch: {},
  //方法集合
  methods: {
    getMenus() {
      this.dataListLoading = true
      this.$http({
        url: this.$http.adornUrl('/product/category/list/tree'),
        method: 'get'
      }).then(data => {
        console.log('成功获取数据' + data.data.data)
        this.data = data.data.data
      })
    },
    handleNodeClick(data) {
      console.log(data)
    }
  },

  //生命周期 - 创建完成(可以访问当前 this 实例)
  created() {
    this.getMenus()
  },
  //生命周期 - 挂载完成(可以访问 DOM 元素)
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {} //如果页面有 keep-alive 缓存功能,这个函数会触发
}
</script>
<style lang='scss' scoped>
//@import url(); 引入公共 css 类
</style>

4.效果

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

- Hola -

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值