springcloud路由网关
一、什么是网关
Zuul的主要功能是路由转发和过滤器。路由功能是微服务的一部分,比如/api/user转发到到user服务,/api/shop转发到到shop服务。zuul默认和Ribbon结合实现了负载均衡的功能, 类似于nginx转发。
二、搭建SpringCloud网关
2.1 创建工程service-zuul 目录展示
2.2 导入依赖
<!--eureka依赖--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-zuul</artifactId> </dependency> <dependencyManagement> <dependencies> <!--springCloud依赖--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Greenwich.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>
2.3 application.yml配置文件
2.4 StartSpringCloudZuul启动类
package com.zn; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.cloud.netflix.zuul.EnableZuulProxy; @EnableEurekaClient @SpringBootApplication @EnableZuulProxy public class StartSpringCloudZuul { public static void main(String[] args) { SpringApplication.run(StartSpringCloudZuul.class,args); } }
2.5 效果展示
SpringCloud服务过滤filter
一、目录展示
二、application.yml配置文件
三、MyZuulFilter
package com.zn.filter; import com.netflix.zuul.ZuulFilter; import com.netflix.zuul.context.RequestContext; import com.netflix.zuul.exception.ZuulException; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; import java.io.IOException; @Component public class MyZuulFilter extends ZuulFilter { /** * 过滤类型 * @return */ @Override public String filterType() { return "pre"; } /** * 请求过滤顺序 * @return */ @Override public int filterOrder() { return 0; } @Override public boolean shouldFilter() { return true; } @Override public Object run() throws ZuulException { //获取token参数 RequestContext rc = RequestContext.getCurrentContext(); HttpServletRequest request = rc.getRequest(); String token = request.getParameter("token"); if (token!=null){ return null; } //表示不进行路由 rc.setSendZuulResponse(false); rc.setResponseStatusCode(401); rc.getResponse().setContentType("text/html;charset=utf-8"); try { rc.getResponse().getWriter().write("没有传递正确参数,请校验后重试!"); } catch (IOException e) { e.printStackTrace(); } return null; } }
四、StartSpringCloudZuul启动类
package com.zn; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.cloud.netflix.zuul.EnableZuulProxy; @EnableEurekaClient @SpringBootApplication @EnableZuulProxy public class StartSpringCloudZuul { public static void main(String[] args) { SpringApplication.run(StartSpringCloudZuul.class,args); } }
五、效果展示