主要内容:
- zuul的过滤器基本概念及如何自定义过滤器
- 微服务如何调用远程application配置文件
zuul过滤器
zuul作为网关的其中一个重要功能就是请求的鉴权。而这个动作我们往往是通过zuul提供的过滤器来实现的
我们自定义一个过滤器,这个过滤器需要继承ZuulFilter
1.shouldFilter
/**
* 根据请求路径决定是否做登录检查,即下面的run方法
*
* @return
*/
@Override
public boolean shouldFilter() {
//1.获取请求对象
RequestContext currentContext = RequestContext.getCurrentContext();
HttpServletRequest request = currentContext.getRequest();
//2.获取URI
String requestURI = request.getRequestURI();
//3.如果请求的路径是"/login",说明当前正在做登录操作,不做登录检查
if (StringUtils.hasLength(requestURI) && requestURI.endsWith("login")) {
//是登录请求
return false;
}
//说明是登录以外的操作,需要做登录检查以检查当前是否登录
return true;
}
2.run
/**
* 登录检查,检查当前是否登录
*
* @return
* @throws ZuulException
*/
@Override
public Object run() throws ZuulException {
//1.获取请求对象
RequestContext currentContext = RequestContext.getCurrentContext();
HttpServletRequest request = currentContext.getRequest();
HttpServletResponse response = currentContext.getResponse();
//2.设置编码
response.setContentType("application/json;charset=utf-8");
//3.获取请求头中的token
String token = request.getHeader("token");
//4.判断token,
if (!StringUtils.hasLength(token)) {
//5.如果token为空,没登录,返回去登录信息,并且阻止请求继续往下执行
Map<String, Object> result = new HashMap<>(); //AJAXResult
result.put("success", false);
result.put("messsage", "您还没有登录,请先去登录");
try {
response.getWriter().print(JSON.toJSONString(result));
//并且阻止请求继续往下执行:不放行
currentContext.setSendZuulResponse(false);
} catch (IOException e) {
e.printStackTrace();
}
}
//6.如果token不为空,返回null即可,请求会继续往下执行
return null;
}
这样所有的请求都会先走这个过滤器:
当我们在url中加上login时,它报了404没找到资源,说明zuul并没有过滤这个请求,也正是因为没被过滤,这个请求才会去找对应资源发现没找到才报的404:
记得加上@Component
用REST Client伪造一个token测试一下:
调用远程仓库的配置文件
eureka:
client:
serviceUrl:
defaultZone: http://localhost:3000/eureka/,http://localhost:3001/eureka/ #注册中心服务端的注册地址
instance:
prefer-ip-address: true #使用ip进行注册
instance-id: config-server:6001 #服务注册到注册中心的id
server:
port: 6001
#应用的名字
spring:
application:
name: config-server
#码云配置
cloud:
config:
server:
git:
uri: https://gitee.com/myllxy/springcloud-config.git
username: 15892306059
password: 276689237abc
# 拉取config-server的配置文件
# config-server的配置文件会去拉取gitee上的配置文件
spring:
cloud:
config:
uri: http://localhost:6001 #application-order-dev.yml
name : application-order #配置文件的名字
profile : dev #配置文件的环境