spring cloud---Getway网关
spring cloud—Getway网关
相当于nginx,不过更牛逼,即以后不需使用nginx了
客户端和服务端之间的一面墙,可以起到很多作用:请求转发、负载均衡、权限控制、跨域(如果使用getway来跨域,就得删除模块那个跨域注解)等
1:getway使用(负载均衡)
创建一个新的子模块,创建普通启动类即可
需要将该模块和需要到的模块全部弄到nacos中
1.1:引入依赖
<dependencies><!--这个是自定义的那个--><dependency><groupId>com.atguigu</groupId><artifactId>common_utils</artifactId><version>0.0.1-SNAPSHOT</version></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-gateway</artifactId></dependency><!--gson--><dependency><groupId>com.google.code.gson</groupId><artifactId>gson</artifactId></dependency><!--服务调用--><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-openfeign</artifactId></dependency>
</dependencies>
1.2:编写配置文件
application.properties类型配置文件
# 服务端口
server.port=8222
# 服务名
spring.application.name=service-gateway
# nacos服务地址
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848#使用服务发现路由
spring.cloud.gateway.discovery.locator.enabled=true#配置service-edu服务
#设置路由id
spring.cloud.gateway.routes[0].id=service-edu
#设置路由的uri lb://nacos注册服务名称
spring.cloud.gateway.routes[0].uri=lb://service-edu
#设置路由断言,代理servicerId为auth-service的/auth/路径
spring.cloud.gateway.routes[0].predicates= Path=/eduservice/**#配置service-msm服务
spring.cloud.gateway.routes[1].id=service-msm
spring.cloud.gateway.routes[1].uri=lb://service-msm
spring.cloud.gateway.routes[1].predicates= Path=/edumsm/**#配置service-cms服务
spring.cloud.gateway.routes[2].id=service-cms
spring.cloud.gateway.routes[2].uri=lb://service-cms
spring.cloud.gateway.routes[2].predicates= Path=/educms/**#配置service-order服务
spring.cloud.gateway.routes[3].id=service-order
spring.cloud.gateway.routes[3].uri=lb://service-order
spring.cloud.gateway.routes[3].predicates= Path=/eduorder/**#配置service-oss服务
spring.cloud.gateway.routes[4].id=service-oss
spring.cloud.gateway.routes[4].uri=lb://service-oss
spring.cloud.gateway.routes[4].predicates= Path=/eduoss/**#配置service-statistics服务
spring.cloud.gateway.routes[5].id=service-statistics
spring.cloud.gateway.routes[5].uri=lb://service-statistics
spring.cloud.gateway.routes[5].predicates= Path=/statistics/**#配置service-ucenter服务
spring.cloud.gateway.routes[6].id=service-ucenter
spring.cloud.gateway.routes[6].uri=lb://service-ucenter
spring.cloud.gateway.routes[6].predicates= Path=/educenter/**#配置service-vod服务
spring.cloud.gateway.routes[7].id=service-vod
spring.cloud.gateway.routes[7].uri=lb://service-vod
spring.cloud.gateway.routes[7].predicates= Path=/eduvod/**
yml类型配置文件
server:port: 8222spring:application:cloud:gateway:discovery:locator:enabled: trueroutes:- id: SERVICE-ACLuri: lb://SERVICE-ACLpredicates:- Path=/*/acl/** # 路径匹配- id: SERVICE-EDUuri: lb://SERVICE-EDUpredicates:- Path=/eduservice/** # 路径匹配- id: SERVICE-UCENTERuri: lb://SERVICE-UCENTERpredicates:- Path=/ucenter/** # 路径匹配nacos:discovery:server-addr: 127.0.0.1:8848
1.3:编写启动类
package com.zpc.gateway;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;@SpringBootApplication
@EnableDiscoveryClient
public class ApiGatewayApplication {public static void main(String[] args) {SpringApplication.run(ApiGatewayApplication.class, args);}
}
2:getway的跨域
在1的基础上进行
这几个代码都是固定的,不需要更改
2.1:创建配置类
package com.zpc.gateway.config;import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.gateway.discovery.DiscoveryClientRouteDefinitionLocator;
import org.springframework.cloud.gateway.discovery.DiscoveryLocatorProperties;
import org.springframework.cloud.gateway.route.RouteDefinitionLocator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.http.codec.support.DefaultServerCodecConfigurer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsUtils;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import org.springframework.web.util.pattern.PathPatternParser;
import reactor.core.publisher.Mono;/*** <p>* 处理跨域* </p>** @author qy* @since 2019-11-21*/
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.util.pattern.PathPatternParser;/*** description:** @author wangpeng* @date 2019/01/02*/
@Configuration
public class CorsConfig {@Beanpublic CorsWebFilter corsFilter() {CorsConfiguration config = new CorsConfiguration();config.addAllowedMethod("*");config.addAllowedOrigin("*");config.addAllowedHeader("*");UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());source.registerCorsConfiguration("/**", config);return new CorsWebFilter(source);}
}
2.2:全局Filter
统一处理会员登录与外部不允许访问的服务
package com.zpc.gateway.filter;import com.google.gson.JsonObject;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;import java.nio.charset.StandardCharsets;
import java.util.List;/*** <p>* 全局Filter,统一处理会员登录与外部不允许访问的服务* </p>** @author qy* @since 2019-11-21*/
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {private AntPathMatcher antPathMatcher = new AntPathMatcher();@Overridepublic Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {ServerHttpRequest request = exchange.getRequest();String path = request.getURI().getPath();//谷粒学院api接口,校验用户必须登录if(antPathMatcher.match("/api/**/auth/**", path)) {List<String> tokenList = request.getHeaders().get("token");if(null == tokenList) {ServerHttpResponse response = exchange.getResponse();return out(response);} else {// Boolean isCheck = JwtUtils.checkToken(tokenList.get(0));
// if(!isCheck) {ServerHttpResponse response = exchange.getResponse();return out(response);
// }}}//内部服务接口,不允许外部访问if(antPathMatcher.match("/**/inner/**", path)) {ServerHttpResponse response = exchange.getResponse();return out(response);}return chain.filter(exchange);}@Overridepublic int getOrder() {return 0;}private Mono<Void> out(ServerHttpResponse response) {JsonObject message = new JsonObject();message.addProperty("success", false);message.addProperty("code", 28004);message.addProperty("data", "鉴权失败");byte[] bits = message.toString().getBytes(StandardCharsets.UTF_8);DataBuffer buffer = response.bufferFactory().wrap(bits);//response.setStatusCode(HttpStatus.UNAUTHORIZED);//指定编码,否则在浏览器中会中文乱码response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");return response.writeWith(Mono.just(buffer));}
}
2.3:自定义异常处理
package com.zpc.gateway.handler;import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.result.view.ViewResolver;import java.util.Collections;
import java.util.List;/*** 覆盖默认的异常处理** @author yinjihuan**/
@Configuration
@EnableConfigurationProperties({ServerProperties.class, ResourceProperties.class})
public class ErrorHandlerConfig {private final ServerProperties serverProperties;private final ApplicationContext applicationContext;private final ResourceProperties resourceProperties;private final List<ViewResolver> viewResolvers;private final ServerCodecConfigurer serverCodecConfigurer;public ErrorHandlerConfig(ServerProperties serverProperties,ResourceProperties resourceProperties,ObjectProvider<List<ViewResolver>> viewResolversProvider,ServerCodecConfigurer serverCodecConfigurer,ApplicationContext applicationContext) {this.serverProperties = serverProperties;this.applicationContext = applicationContext;this.resourceProperties = resourceProperties;this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);this.serverCodecConfigurer = serverCodecConfigurer;}@Bean@Order(Ordered.HIGHEST_PRECEDENCE)public ErrorWebExceptionHandler errorWebExceptionHandler(ErrorAttributes errorAttributes) {JsonExceptionHandler exceptionHandler = new JsonExceptionHandler(errorAttributes,this.resourceProperties,this.serverProperties.getError(),this.applicationContext);exceptionHandler.setViewResolvers(this.viewResolvers);exceptionHandler.setMessageWriters(this.serverCodecConfigurer.getWriters());exceptionHandler.setMessageReaders(this.serverCodecConfigurer.getReaders());return exceptionHandler;}
}
package com.zpc.gateway.handler;import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.boot.autoconfigure.web.reactive.error.DefaultErrorWebExceptionHandler;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.web.reactive.function.server.*;import java.util.HashMap;
import java.util.Map;/*** 自定义异常处理** <p>异常时用JSON代替HTML异常信息<p>** @author yinjihuan**/
public class JsonExceptionHandler extends DefaultErrorWebExceptionHandler {public JsonExceptionHandler(ErrorAttributes errorAttributes, ResourceProperties resourceProperties,ErrorProperties errorProperties, ApplicationContext applicationContext) {super(errorAttributes, resourceProperties, errorProperties, applicationContext);}/*** 获取异常属性*/@Overrideprotected Map<String, Object> getErrorAttributes(ServerRequest request, boolean includeStackTrace) {Map<String, Object> map = new HashMap<>();map.put("success", false);map.put("code", 20005);map.put("message", "网关失败");map.put("data", null);return map;}/*** 指定响应处理方法为JSON处理的方法* @param errorAttributes*/@Overrideprotected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);}/*** 根据code获取对应的HttpStatus* @param errorAttributes*/@Overrideprotected int getHttpStatus(Map<String, Object> errorAttributes) {return 200;}
}
spring cloud---Getway网关相关推荐
- Spring Cloud服务网关(Zuul)的配置项sensitiveHeaders
如果我们在一个服务中添加了Cookie,如下图所示: public static void set(HttpServletResponse response,String name,String va ...
- Spring Cloud Gateway网关
Spring Cloud Gateway网关 1. 简介 Spring Cloud Gateway是Spring官网基于Spring 5.0. Spring Boot 2.0.Project Reac ...
- Spring Cloud Gateway网关实现短网址生成、解析、转发
Spring Cloud Gateway网关实现短网址生成.解析.转发 1.概述 2.基础实现 3.路由处理HandlerFunction 4.配置路由 5.测试 1.概述 在一些生成二维码等场景中, ...
- spring cloud的网关服务Zuul
微服务架构讲究系统的高内聚性,即只做该系统该做的事情,而其他的事情可以通过网关去做.spring cloud的zuul可以快速的搭建一个网关系统,其主要功能如下: 当加入了spring cloud的z ...
- 从0开始构建你的api网关--Spring Cloud Gateway网关实战及原理解析
API 网关 API 网关出现的原因是微服务架构的出现,不同的微服务一般会有不同的网络地址,而外部客户端可能需要调用多个服务的接口才能完成一个业务需求,如果让客户端直接与各个微服务通信,会有以下的问题 ...
- Spring Cloud Zuul网关 Filter、熔断、重试、高可用的使用方式
时间过的很快,写springcloud(十):服务网关zuul初级篇还在半年前,现在已经是2018年了,我们继续探讨Zuul更高级的使用方式. 上篇文章主要介绍了Zuul网关使用模式,以及自动转发机制 ...
- Spring Cloud GatewayAPI网关服务
一.Gateway 简介 Gateway是在Spring生态系统之上构建的API网关服务,基于Spring 5,Spring Boot 2和 Project Reactor等技术.Gateway旨在提 ...
- SPRING CLOUD服务网关之ZUUL
服务网关是微服务架构中一个不可或缺的部分.通过服务网关统一向外系统提供REST API的过程中,除了具备服务路由.均衡负载功能之外,它还具备了权限控制等功能.Spring Cloud Netflix中 ...
- spring cloud gateway 网关_微服务网关Spring Cloud Gateway全搞定
一.微服务网关Spring Cloud Gateway 1.1 导引 文中内容包含:微服务网关限流10万QPS.跨域.过滤器.令牌桶算法. 在构建微服务系统中,必不可少的技术就是网关了,从早期的Zuu ...
- Spring Cloud Zuul网关 Filter、熔断、重试、高可用的使用方式。
时间过的很快,写springcloud(十):服务网关zuul初级篇还在半年前,现在已经是2018年了,我们继续探讨Zuul更高级的使用方式. 上篇文章主要介绍了Zuul网关使用模式,以及自动转发机制 ...
最新文章
- 论坛报名 | 视觉大模型是实现视觉智能的必由之路吗?
- 金融风控实战——模型融合
- ML之HMM:HMM算法相关论文、关键步骤、测试代码配图集合
- boost::math模块通过 Gauss 和 Gauss-Kronrod 正交的数值积分
- matlab lu分解 l不是下三角,在MATLAB中执行LU分解而不进行旋转
- HDU 2818 Building Block
- java list 遍历查找_Java用list储存,遍历,查询指定信息过程详解
- 【转载】socket as an IPC
- python 学习爬虫教程~
- VC++、MFC Sqlite3数据库的使用
- 如何才是真正的大牛?遇见同行博士大牛,感慨自己太渣
- 数据结构(树状结构-树)
- Vue中常用的组件传值方式
- 【转】MySQL日期时间函数大全
- 使用selenium自动化工具爬取微博内容和评论
- 【愚公系列】2022年12月 使用win11系统自带SSH,远程控制VMware中Liunx虚拟机系统
- Chrome 浏览器常用设置及问题(vimium)
- 笔记本电脑远程另一台电脑(无网络)
- 无线网dns的服务器地址是多少,宽带通dns的服务器地址是多少
- 今天,我们算一算数据中心停机的账
热门文章
- 【计算机硬件基础】--学习笔记
- jQuery进度条插件rangeSlider,带刻度,rangeSlider实现进度范围选择案例
- JS input 文本框事件
- 讲讲关于Precision 与 Recall 的概念
- layui使用tips_layer 的提示层 tips的一般使用
- java to c converter_Java to C Converter专业版-Java to C Converter正式版下载-最火手机站
- 计算机毕业设计JAVA靓车汽车销售网站mybatis+源码+调试部署+系统+数据库+lw
- Discuz论坛短信群发、动网自动发贴源代码
- Mac 安装软件包管理工具Homebrew
- 超级好用的代码阅读器source insight破解版安装和使用