项目背景:
测试项目,本项目中没有登录业务,所以在前端用户请求微服务的时候会先经过网关,网关设置请求头信息AddRequestHeader 将用户的id存到请求头中,具体实现路径如图所示
添加请求头信息
在gateway网关服务的application.yml配置文件中的添加全局过滤器来添加请求头
通过微服务中的拦截器获取请求头信息
package com.hmall.common.pojo;
/**
* @author:Dikk
* @create: 2023-07-09 20:39
* @Description: BaseContext
*/
public class BaseContext {
public static ThreadLocal<Long> threadLocal = new ThreadLocal<>();
public static void setCurrentId(Long id) {
threadLocal.set(id);
}
public static Long getCurrentId() {
return threadLocal.get();
}
public static void removeCurrentId() {
threadLocal.remove();
}
}
package com.hmall.item.interceptor;
import com.hmall.common.constants.HeaderConstant;
import com.hmall.common.pojo.BaseContext;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author:Dikk
* @create: 2023-07-10 20:16
* @Description: HandlerInterceptor
*/
@Component
public class ItemInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//获取请求头信息
String authorization = request.getHeader(HeaderConstant.HEADER_NAME);
if (authorization == null) {
//设置状态401
response.setStatus(401);
return false;
}
//将请求头信息
BaseContext.setCurrentId(Long.valueOf(authorization));
return true;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
BaseContext.removeCurrentId();
}
}
再通过SpringMVC的消息扩展来将自定义的拦截器添加进去
package com.hmall.item.configs;
import com.hmall.item.interceptor.ItemInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
/**
* @author:Dikk
* @create: 2023-07-13 10:08
* @Description: MvcConfig
*/
@Configuration
public class MvcConfig extends WebMvcConfigurationSupport {
@Autowired
private ItemInterceptor itemInterceptor;
@Override
protected void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(itemInterceptor).addPathPatterns("/**");
}
}
以上就完成了模拟登录的请求
验证
启动微服务,直接访问8081端口 页面返回代码401
现在请求网关10010
错误码为500,预期中的错误,说明网关有将请求路由到item微服务中