servlet-gateway-spring-boot-starter组件是一组基于Servlet体系的业务转发HTTP组件,主要目的是在现有Spring Boot 框架的基础上,添加基于Filter过滤器的转发能力,丰富框架的业务能力。
源码地址:https://gitee.com/dt_research_institute/java-business-kernel
目前支持三种模式:
ROUTE_MODE_HEADER:基于请求头的转发
ROUTE_MODE_PREFIX:基于请求Uri的请求前缀匹配转发
ROUTE_MODE_SUFFIX:基于请求URI的后缀匹配转发规则
使用方法,在Spring Boot的框架中,pom.xml中引入当前组件,代码如下:
<dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>servlet-gateway-spring-boot-starter</artifactId> <version>1.0</version> </dependency>在Spring Boot框架的application.yml配置文件中进行配置,示例如下:
server: servlet: gateway: enable: true cloud: enable: true # Routes节点,可以配置多个 routes: - mode: ROUTE_MODE_PREFIX # 将所有以/abb开头的请求接口全部转发到uri中的目标服务 value: /abb/ uri: # 配置发送默认请求头(可选配置) headers: code: TESS针对代理请求鉴权功能,该组件提供了ServletGatewayAuthentication接口,对于接入该组件的项目需要实现该接口,并且注入到 Spring 的容器中
public interface ServletGatewayAuthentication { /** * 权限校验 * @param request 请求request对象 * @param response 响应对象 * @return 是否权限校验通过 */ boolean auth(ServletRequest request, ServletResponse response); /** * 权限校验失败后的处理逻辑 * @param request 请求对象 * @param response 响应对象 */ void failedHandle(ServletRequest request, ServletResponse response); /** * 是否需要鉴权,默认true * @return 是否需要鉴权 */ default boolean required(){return true;} }以下是一个项目中通过Shiro控制权限的例子,对于代理的请求,需要验证当前的请求是否已经登录过
public class AideShiroAuthentication implements ServletGatewayAuthentication { private final OtsWebSessionManager otsWebSessionManager; private final RedisTemplate redisTemplate; Logger logger= LoggerFactory.getLogger(AideShiroAuthentication.class); public AideShiroAuthentication(OtsWebSessionManager otsWebSessionManager, RedisTemplate redisTemplate) { this.otsWebSessionManager = otsWebSessionManager; this.redisTemplate = redisTemplate; } @Override public boolean auth(ServletRequest request, ServletResponse response) { Serializable sessionId = otsWebSessionManager.getShiroSessionId(request, response); if (sessionId!=null){ Object object= redisTemplate.opsForValue().get(MyRedisSessionDao.PREFIX + sessionId.toString()); if (object!=null){ Session session = (Session)object; return session!=null&&session.getId()!=null; } } return false; } @Override public void failedHandle(ServletRequest request, ServletResponse response) { logger.info("权限校验失败"); response.setCharacterEncoding("UTF-8"); response.setContentType("application/json; charset=utf-8"); RestResult<String> result = new RestResult<>(); result.setErrCode(BusinessErrorCode.NO_CURRENT_LOGIN_USER.getCode()); result.setData(BusinessErrorCode.NO_CURRENT_LOGIN_USER.getMessage()); try (PrintWriter out = response.getWriter()) { out.append(JSON.toJSONString(result)); } catch (IOException e2) { return; } } }