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网关于springboot中的使用相关推荐

  1. Spring Cloud Gateway 2.1.0 中文官网文档

    目录 1. How to Include Spring Cloud Gateway 2. Glossary 3. How It Works 4. Route Predicate Factories 5 ...

  2. Spring Cloud Alibaba微服务项目中集成Redis实现分布式事务锁实践

    引言 我们知道同一个进程里面为了解决资源共享而不出现高并发的问题可以通过高并发编程解决,通过给变量添加volatile关键字实现线程间变量可见:通过synchronized关键字修饰代码块.对象或者方 ...

  3. Spring Cloud 注册中心在tomcat中部署

    前言 最近刚刚接触spring boot 和spring cloud,只知道可以直接通过main方法启动服务,一直不会将项目部署到tomcat中,今天学了一下,做个记录备忘. 步骤 pom文件 在po ...

  4. 关于Spring Cloud Zuul网管上传文件乱码问题

    Spring Cloud Zuul现在对于上传文件有两种处理方式,一种是用spring mvc,另一种是zuulServlet.spring mvc对文件处理不是很好,会导致乱码问题,zuulServ ...

  5. Spring Cloud分布式微服务系统中利用redssion实现分布式锁

    在非分布式系统中要实现锁的机制很简单,利用java.util.concurrent.locks包下的Lock和关键字synchronized都可以实现.但是在分布式系统中,如何实现各个单独的微服务需要 ...

  6. Spring cloud系列之Zuul配置项中sensitiveHeaders和ignoredHeaders

    sensitiveHeaders:会过滤客户端请求中的和该配置项匹配的headers 比如: zuul: sensitiveHeaders: X-ABC 如果客户端在发请求是带了X-ABC,那么X-A ...

  7. 关于Spring Cloud:Mapper<>中的泛型红线:Type ‘org.apache.ibatis.annotations.Mapper‘ does not have type paramet

    Type 'org.apache.ibatis.annotations.Mapper' does not have type parameters 解决办法: 检查mapper接口中导入的包是不是通用 ...

  8. spring cloud 之 网管 (网关) 技术点集锦

    应用场景: 1.聚合api: 一个电商系统可能会涉及多个微服务,在ui展示页面时可能需要从多个微服务中聚合数据,而且服务的划分位置结构可能会有所改变.网关就可以对外暴露聚合API,屏蔽内部微服务的微小 ...

  9. Spring Cloud 中文文档

    Spring Cloud 官方文档 Spring Cloud为开发人员提供了用于快速构建分布式系统中某些常见模式的工具(例如,配置管理,服务发现,断路器,智能路由,微代理,控制总线).分布式系统的协调 ...

最新文章

  1. docker安装logstash及logstash配置
  2. 玩转ECS第5讲 | 弹性计算安全组最佳实践及新特性介绍
  3. [译] React Hooks: 没有魔法,只是数组
  4. java面向对象基础代码_JAVA基础知识点之Java面向对象
  5. python调用系统命令_linux里面python调用系统命令问题
  6. Python内置函数sorted()和列表方法sort()排序规则不得不说的事
  7. vuejs切换导航条高亮路由高亮做法
  8. grideh SelectedRows Bookmark
  9. System.Exception: 操作必须使用一个可更新的查询
  10. java经典算法(六)---zws
  11. GitHub 漫游指南
  12. 数字信号处理专题(1)——DDS函数发生器环路Demo
  13. 我的python面试简历
  14. base64编码类------源代码(C#)
  15. C语言static关键字的作用(有三个作用)
  16. Integral Object Mining via Online Attention Accumulation
  17. JS逆向之美团网模拟登录!这教程杠杠滴~
  18. 搭建团队文档协作平台(OnlyOffice)Linux 系统部署
  19. Bosun中es表达语法
  20. Whale帷幄 - 车企数字化转型案例

热门文章

  1. 计算机端口 closewait,TCP端口状态说明ESTABLISHED、TIME_WAIT、 CLOSE_WAIT
  2. Oracle新建的用户看不到表,Oracle 创建用户及数据表的方法
  3. 决策树算法(C4.5算法)
  4. 盛迈坤电商:店铺运营具体需要怎么操作
  5. traceroute命令讲解
  6. 跑不过时间就跑过昨天的自己(早安心语)
  7. 学习-Java字符串之正则表达式之元字符之判断字符串是否符合规则
  8. 第27章 登录/注销的定义实现
  9. 工控机(ubuntu系统)和R2000雷达已经通过网线连接,雷达ip未知,如何获取雷达IP地址
  10. 如何做好自动化机械设计,一起学起来