1.添加pom相关依赖
<dependencies> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus</artifactId> <version>3.5.1</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> </dependencies>
2.添加yml相关配置
server: port: 10000 spring: application: name: hello-zuul eureka: client: service-url: defaultZone: http://admin:1234@localhost:7001/eureka/ register-with-eureka: true fetch-registry: true zuul: prefix: /api #路由前缀 routes: emp-provider: # 路由名称 path: /emp/** #url规则 service-id: hello-provider #微服务名称 strip-prefix: false #去路由前缀 emp-consumer: # 路由名称 path: /consumer/emp/** service-id: hello-consumer strip-prefix: false
3.启动类
@SpringBootApplication @EnableEurekaClient @EnableZuulProxy //标识zuul过滤器
4.网关过滤器类 filter
//网关过滤器 @Component public class MyZuulFilter extends ZuulFilter { @Override public String filterType() { return FilterConstants.PRE_TYPE; //调用目标服务前过滤 } @Override public int filterOrder() { return 0; //优先级越小优先级越高 } @Override public boolean shouldFilter() { return true; //是否需要执行过滤逻辑 } @Override public Object run() throws ZuulException { //判断token是否纯在 //获取上下文 RequestContext ctx = RequestContext.getCurrentContext(); //获取请求对象 HttpServletRequest request = ctx.getRequest(); String token = request.getParameter("token"); if(token == null){ // 拒绝访问微服务 ctx.setResponseStatusCode(HttpStatus.SC_UNAUTHORIZED); ctx.setSendZuulResponse(false); HttpServletResponse response = ctx.getResponse(); Result<Object> result = Result.fail(20006, "请求未授权"); try { response.setContentType("application/json;charset=utf-8"); response.getWriter().write(JSON.toJSONString(result)); } catch (IOException e) { e.printStackTrace(); } } return null; } }