一般我们使用网关,大都是配合注册中心进行使用,gateway注册到注册中心,注册中心中可自动实现负载均衡,但是通常会有一些项目不是使用分布式的架构,那么我们单体的springboot项目,如何使用springcloud gateway进行负载均衡和限流 鉴权呢
下图我spring 官网上springcloud的架构图解,可以很清晰的看到服务请求进来的整个过程。
接下来我们看下springcloud gateway的几个主要词汇,路由 断言 处理 和网关处理处理流程图 这里是springcloud gateway官网地址点击直达
如果我们是单体应用的话,单体部署多台服务器上,也可以通过网关分发,达到负载 拦截等效果
接下来我们看下具体的配置参数和处理,先看下 yml 的具体配置
-
-
server:
-
port:
9999
-
-
spring:
-
cloud:
-
gateway:
-
#discovery:
-
#locator:
-
#enabled: true
-
routes:
-
- id: my-consumer-service
-
uri: lb://my-consumer-service
# http://127.0.0.1:8088
-
predicates:
-
- Path=/app/**
#断言处理
-
filters:
-
- StripPrefix=
1
#表示路由时会去除一位 如 api/app/login app/login
-
- name: RequestRateLimiter
#名称必须是RequestRateLimiter
-
args:
-
key-resolver:
"#{@urlResolver}"
#使用SpEL按名称引用bean
-
redis-rate-limiter.replenishRate:
20
#允许用户每秒处理多少个请求
-
redis-rate-limiter.burstCapacity:
10
#令牌桶的容量,允许在一秒钟内完成的最大请求数
-
- name: Hystrix
#断路器的配置
-
args:
-
name: fallbackcmd
-
fallbackUri: forward:/defaultfallback
-
- id: my-consumer-service2
-
uri: http://
127.0
.0
.1:
8088
# http://127.0.0.1:8088 lb://consumer-service lb 代表从注册中心获取服务,且已负载均衡方式转发
-
predicates:
-
- Path=/admin/**
#断言处理
-
filters:
-
- StripPrefix=
1
#表示路由时会去除一位 如 api/app/login app/login
-
- name: RequestRateLimiter
#名称必须是RequestRateLimiter
-
args:
-
key-resolver:
"#{@urlResolver}"
#使用SpEL按名称引用bean
-
redis-rate-limiter.replenishRate:
20
#允许用户每秒处理多少个请求
-
redis-rate-limiter.burstCapacity:
10
#令牌桶的容量,允许在一秒钟内完成的最大请求数
-
- name: Hystrix
#断路器的配置
-
args:
-
name: fallbackcmd
-
fallbackUri: forward:/defaultfallback
-
-
redis:
-
host: localhost
-
port:
6379
-
database:
0
-
-
-
my-consumer-service:
-
ribbon:
-
listOfServers: localhost:
9088,localhost,
9099
-
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RoundRobinRule
如果你要负载到多台上,写法 lb://my-consumer-service ,(单台的话uri 直接ip端口)然后在下面定义你这个服务地址,这是是写死的,不能像注册中心一样灵活感知新增的服务,如果不需要断言处理,不截取前端的话,修改配置,同时去掉
- StripPrefix=1 #表示路由时会去除一位 如 api/app/login app/login
- Path=/**/** #只路由转发
网关拦截 token 白名单操作, 请看如下
-
package com.example.springcloudgateway.
filter;
-
-
import com.alibaba.fastjson.JSON;
-
import com.example.springcloudgateway.config.AppConstants;
-
import com.example.springcloudgateway.dto.CommonResult;
-
import lombok.extern.slf4j.Slf4j;
-
import org.apache.commons.lang.StringUtils;
-
import org.springframework.beans.factory.annotation.Autowired;
-
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
-
import org.springframework.cloud.gateway.filter.GlobalFilter;
-
import org.springframework.context.annotation.Configuration;
-
import org.springframework.core.Ordered;
-
import org.springframework.core.annotation.Order;
-
import org.springframework.core.codec.EncodingException;
-
import org.springframework.core.io.buffer.DataBuffer;
-
import org.springframework.data.redis.core.StringRedisTemplate;
-
import org.springframework.http.HttpStatus;
-
import org.springframework.http.server.reactive.ServerHttpRequest;
-
import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
-
import org.springframework.http.server.reactive.ServerHttpResponse;
-
import org.springframework.stereotype.Component;
-
import org.springframework.web.server.ServerWebExchange;
-
import reactor.core.publisher.Flux;
-
import reactor.core.publisher.Mono;
-
-
import java.io.UnsupportedEncodingException;
-
import java.net.URI;
-
import java.util.Arrays;
-
-
/**
-
* @version V1.0
-
* @author: hqk
-
* @date: 2020/5/12 15:35
-
* @Description: 转发之前拦截 白名单过滤 鉴权
-
*/
-
@
Slf4j
-
@
Component
-
public
class TokenFilter implements GlobalFilter, Ordered {
-
-
@
Autowired
-
private
StringRedisTemplate stringRedisTemplate;
-
-
// 白名单 排除无需验证的 token
-
private
static
final
String[] whiteList = {
"/auth/login",
"/user/register"};
-
-
@
Override
-
public
Mono<
Void>
filter(
ServerWebExchange exchange,
GatewayFilterChain chain) {
-
-
ServerHttpRequest serverHttpRequest = exchange.getRequest();
-
String url =serverHttpRequest.getURI().getPath();
-
-
log.info(
"url:{}", url);
-
//System.out.println("请求地址:"+url);
-
-
//无需过滤的URL
-
if (
Arrays.asList(whiteList).
contains(url)){
-
-
return chain.
filter(exchange);
-
}
-
-
String token =serverHttpRequest.getHeaders().getFirst(
AppConstants.
TOKEN);
-
-
log.info(
"请求token:{}", token);
-
//System.out.println("请求token:"+token);
-
-
if(
StringUtils.isEmpty(token)){
-
-
return setResponse(exchange,
"token 不存在");
-
}
-
-
String redisToken=stringRedisTemplate.opsForValue().
get(
AppConstants.
REDIS_KEY_TOKEN);
-
-
if (
StringUtils.isBlank(redisToken)) {
-
-
return setResponse(exchange,
"token 失效");
-
}
-
-
-
log.info(
"鉴权完毕");
-
return chain.
filter(exchange);
-
-
}
-
-
/**
-
* 设置 拦截返回信息
-
* @param exchange
-
* @param msg
-
* @return
-
*/
-
private
Mono<
Void> setResponse(
ServerWebExchange exchange,
String msg) {
-
-
ServerHttpResponse originalResponse = exchange.getResponse();
-
originalResponse.setStatusCode(
HttpStatus.
UNAUTHORIZED);
-
originalResponse.getHeaders().add(
"Content-Type",
"application/json;charset=UTF-8");
-
byte[] response = null;
-
try
-
{
-
log.info(
"token已失效");
-
response =
JSON.toJSONString(
CommonResult.error(msg,
"")).getBytes(
AppConstants.
UTF8);
-
}
-
catch (
UnsupportedEncodingException e){
-
e.printStackTrace();
-
}
-
DataBuffer buffer = originalResponse.bufferFactory().wrap(response);
-
return originalResponse.writeWith(
Flux.just(buffer));
-
}
-
-
-
@
Override
-
public int getOrder() {
-
return -
200;
-
}
-
-
}
限流代码,这里根据请求地址限流,如果是ip限流,把URL换成 ip ,然后在配置文件中配置,这里之前已经配置了
-
package com.example.springcloudgateway.resolver;
-
-
import lombok.extern.slf4j.Slf4j;
-
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
-
import org.springframework.stereotype.Component;
-
import org.springframework.web.server.ServerWebExchange;
-
import reactor.core.publisher.Mono;
-
-
/**
-
* @version V1.0
-
* @author: hqk
-
* @date: 2020/5/12 13:20
-
* @Description: 限流配置
-
*/
-
@Slf4j
-
@Component
-
public
class UrlResolver implements KeyResolver {
-
-
-
@Override
-
public Mono<String> resolve(ServerWebExchange exchange) {
-
-
//String ip=exchange.getRequest().getRemoteAddress().getAddress().getHostAddress();
-
-
//获取请求地址
-
String url= exchange.getRequest().getURI().toString();
-
-
log.info(
"断言处理后的url:{}",url);
-
//System.out.println("url:"+url);
-
-
return Mono.just(url);
-
}
-
}
接下来我们看下网关熔断的代码,配置已在第一步中配置过了
-
package
com
.example
.springcloudgateway
.controller;
-
-
import
com
.example
.springcloudgateway
.dto
.CommonResult;
-
import
org
.springframework
.web
.bind
.annotation
.RequestMapping;
-
import
org
.springframework
.web
.bind
.annotation
.RestController;
-
-
import
java
.util
.HashMap;
-
import
java
.util
.Map;
-
-
/**
-
* @version V1.0
-
* @author: hqk
-
* @date: 2020/5/11 16:38
-
* @Description: 网关熔断降级返回
-
*/
-
@
RestController
-
public class DefaultHystrixController {
-
-
-
@
RequestMapping("/
defaultfallback")
-
public Object defaultfallback(){
-
System
.out
.println("降级操作...");
-
-
return
CommonResult
.error(401,"网关服务熔断");
-
}
-
-
/*@RequestMapping("/defaultfallback")
-
public Map<String,String> defaultfallback(){
-
System.out.println("降级操作...");
-
Map<String,String> map = new HashMap<>();
-
map.put("resultCode","false");
-
map.put("resultMessage","服务异常");
-
map.put("resultObj","这里测试网关服务熔断");
-
return map;
-
}*/
-
}
这样我们网关 路由转发 断言 拦截 限流,网关熔断都处理完毕,具体代码已上传到码云,点击直达
转载:https://blog.csdn.net/huqiankunlol/article/details/106089438
查看评论