在前后端分离的微服务项目中,前端给后端发送请求都是从一个配置好的默认路径发送给对应服务的,如renren-fast-vue,在项目的staic/config/index.js文件中,我们可以观察到默认路径如下:
;(function () { window.SITE_ConFIG = {}; // api接口请求地址(默认路径) window.SITE_CONFIG['baseUrl'] = 'http://localhost:8080/renren-fast'; // cdn地址 = 域名 + 版本号 window.SITE_CONFIG['domain'] = './'; // 域名 window.SITE_CONFIG['version'] = ''; // 版本号(年月日时分) window.SITE_CONFIG['cdnUrl'] = window.SITE_CONFIG.domain + window.SITE_CONFIG.version; })();
即默认访问本机的8080端口下的renren-fast项目,而在微服务项目中,前端会去调用多个微服务项目的接口,不可能只访问这一个地址,为了解决这个问题,就有了api网关,前端只需要往api网关项目的地址发送请求,有api网关去根据请求信息去访问对应的微服务项目就可以了
架构图如下:
2、api网关的实现,以人人开源项目为例注:这里演示将renren-fast-vue的请求交由网关处理并路由到renren-fast后台管理系统的过程
1、首先修改前端项目的默认api地址,将所有请求发送至网关;(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、创建springboot网关项目,引入技术栈,并进行基本配置
【1】引入技术栈:
注册中心:spring cloud alibaba nacos
网关 :spring cloud gateway
【2】配置项目的基本信息,端口号与前端默认地址保持一致,网关需要到注册中心获取服务,因此必须配置nacos地址,并在应用启动类上加入注解@EnableDiscoveryClient注册到nacos上
spring: # 应用名称 application: name: mxshop-gateway # nacos地址 nacos: server-addr: 127.0.0.1:8848 # 端口号 server: port: 88
@SpringBootApplication @EnableDiscoveryClient public class MxshopGatewayApplication { public static void main(String[] args) { SpringApplication.run(MxshopGatewayApplication.class, args); }3、网关配置(重点)
前端同一发送请求给网关,那么网关就必须要具有根据请求地址调用对应微服务的功能,对此,spring cloud gateway提供了routes路由配置来实现根据请求地址路由到对应微服务。配置如下:
spring: gateway: # 进行路由配置 routes: # 路由id,声明多个id可配置多个路由 - id: admin_route # renren-fast是微服务应用名,lb是负载均衡,若有多个同名微服务会进行负载均衡 uri: lb://renren-fast # 断言,匹配以api为开始的地址片段,匹配起始点是端口号后,匹配成功则路由到上方的uri predicates: - Path=/api package io.renren.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class CorsConfig implements WebMvcConfigurer { // @Override // public void addCorsMappings(CorsRegistry registry) { // registry.addMapping("/**") // .allowedOrigins("*") // .allowCredentials(true) // .allowedMethods("GET", "POST", "PUT", "DELETe", "OPTIONS") // .maxAge(3600); // } }如果不对renren-fast跨站请求配置删除,会有以下错误,并登录不上:
Access to XMLHttpRequest at 'http://localhost:88/api/sys/login' from origin 'http://localhost:8001' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains multiple values 'http://localhost:8001, http://localhost:8001', but only one is allowed.
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)