1、创建一个Eureka Server工程,项目名称:eureka-server
2、创建一个Eureka Client 服务提供者 工程,项目名称:eureka-client1
工程eureka-server和eureka-client1 创建请参考
Spring Cloud(三)Eureka实战
启动eureka-server、eureka-client1
PS:eureka-client1 在idea中通过多实例启动
查看 Eureka 控制台
项目名称:service-zuul
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.yi</groupId> <artifactId>service-zuul</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>service-zuul</name> <description>Zuul路由转发和过滤器</description> <parent> <groupId>com.yi</groupId> <artifactId>finchley</artifactId> <version>0.0.1-SNAPSHOT</version> </parent> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-zuul</artifactId> </dependency> </dependencies> </project> @SpringBootApplication @EnableZuulProxy @EnableEurekaClient @EnableDiscoveryClient public class ServiceZuulApplication { public static void main(String[] args) { SpringApplication.run(ServiceZuulApplication.class, args); } }@EnableZuulProxy:开启zuul的功能
eureka: client: serviceUrl: defaultZone: http://localhost:8761/eureka/ server: port: 8769 spring: application: name: service-zuul zuul: routes: api-a: path: /service/a/** serviceId: service-ribbon1 api-b: path: /service/b/** serviceId: service-ribbon2/service/a/ 开头的请求都转发给service-ribbon1服务 /service/b/ 开头的请求都转发给service-ribbon2服务
浏览器访问两个请求,验证Zuul路由功能是否发挥作用
http://localhost:8769/service/a/hello?name=yi http://localhost:8769/service/b/hello?name=yi自定义过滤器
自定义登录过滤器。如果请求参数存在token,则请求有效,否则拦截。
@Component public class LoginFilter extends ZuulFilter { private static Logger log = LoggerFactory.getLogger(LoginFilter.class); @Override public String filterType() { // 定义为前置过滤器 return FilterConstants.PRE_TYPE; } @Override public int filterOrder() { // 在处理请求头之前进行拦截 return FilterConstants.PRE_DECORATION_FILTER_ORDER - 1; } @Override public boolean shouldFilter() { // 开启过滤器 return true; } @Override public Object run() { // 获取请求上下文,此作用域范围:从请求到达zuul一直到路由结束后返回给客户端这个完整流程.但是它不会存在微服务内,只存在zuul中 RequestContext ctx = RequestContext.getCurrentContext(); HttpServletRequest request = ctx.getRequest(); //获取请求参数 String accessToken = request.getParameter("token"); //判断是否存在 if (StringUtils.isBlank(accessToken)) { //不存在,未登录,进行拦截 ctx.setSendZuulResponse(false); ctx.setResponseStatusCode(HttpStatus.FORBIDDEN.value()); } return null; } } http://localhost:8769/service/a/hello?name=yi http://localhost:8769/service/a/hello?name=yi&token=yyy 正常访问服务git项目源码:https://github.com/yilei111/-Spring-Cloud-Finchley