Spring Cloud 之 Eureka 和 Zuul 的简单使用
一、Spirng Cloud 是什么?
简单来说 Spring Cloud 就是个框架集合,它里面包含了一系列的技术框架。在微服务如此普及的时代,如何快速构建一系列的稳定服务是比较重要的。
Spirng Cloud 利用 Spring Boot 的开发便利性巧妙地简化了分布式系统基础设施的开发,如服务发现注册、配置中心、消息总线、负载均衡、断路器、数据监控等,都可以用 Spring Boot 的开发风格做到一键启动和部署。
二、服务注册与发现 Eureka
之前写过一篇的服务注册与发现的文章,写的是 Consul,这次写下 Spring 的服务注册组件 Eureka。
1.3.5.RELEASE
org.springframework.boot spring-boot-starter-parent 1.3.5.RELEASE UTF-8 UTF-8 1.8 Brixton.RELEASE org.springframework.cloud spring-cloud-starter-eureka-server org.springframework.boot spring-boot-starter-test test
@EnableEurekaServer
# 自定义端口server.port=1111# 关闭服务端自注册功能eureka.client.register-with-eureka=falseeureka.client.fetch-registry=falseeureka.client.serviceUrl.defaultZone=http://localhost:${server.port}/eureka/
- 启动项目在http://localhost:1111可以看到如下页面
此时只是注册中心的服务端启动起来了,还没有任何服务注册到上面。
- 新建项目 service-A 向 Eureka 服务端进行注册,同样从 Springboot 的网站下载项目代码,pom.xml 文件如下。
org.springframework.boot spring-boot-starter-parent 1.3.5.RELEASE UTF-8 UTF-8 1.8 Brixton.RELEASE org.springframework.boot spring-boot-starter-web org.springframework.cloud spring-cloud-starter-eureka org.springframework.boot spring-boot-starter-test test org.springframework.cloud spring-cloud-dependencies ${spring-cloud.version} pom import
Spring Cloud 的版本保持一致,另外增加了 Eureka 的客户端和 web 依赖。
- 增加自定义测试 controller
package com.example.demo.controller;import org.jboss.logging.Logger;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.cloud.client.ServiceInstance;import org.springframework.cloud.client.discovery.DiscoveryClient;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;@RestControllerpublic class ComputeController { private final Logger logger = Logger.getLogger(getClass()); @Autowired private DiscoveryClient client; @RequestMapping(value = "/add", method = RequestMethod.GET) public String add(@RequestParam Integer a, @RequestParam Integer b) { Integer r = a + b; System.out.println(r); ServiceInstance instance = client.getLocalServiceInstance(); logger.info("/add, host:" + instance.getHost() + ", service_id:" + instance.getServiceId() + ", result:" + r); return r + "--" + instance.getServiceId(); }}
- 编写配置文件
# 注册的服务名称spring.application.name=service-A# 自定义端口server.port=2222# 注册中心地址eureka.client.serviceUrl.defaultZone=http://localhost:1111/eureka/
- 在启动类中增加如下注解,并且启动
package com.example.demo.service;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.EnableAutoConfiguration;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.client.discovery.EnableDiscoveryClient;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;/** * @author silence */@EnableDiscoveryClient@Configuration@EnableAutoConfiguration@SpringBootApplication@ComponentScan({"com.example.demo.*"})public class DemoServiceAApplication { public static void main(String[] args) { SpringApplication.run(DemoServiceAApplication.class, args); }}
- 刷新页面就可以看到 service-A 已经注册到服务中心了
- 调用一下刚才我们增加的接口
三、配合 Eureka 使用 zuul
Zuul 是在云平台上提供动态路由,监控,弹性,安全等边缘服务的框架。
- 按照上面 service-A 的方式,我们再新建个项目 service-B,启动注册到Eureka 服务中心。如图
- 在 Springboot 网站上下载代码 pom.xml 文件如下
org.springframework.boot spring-boot-starter-parent 1.3.5.RELEASE UTF-8 UTF-8 1.8 Brixton.RELEASE org.springframework.cloud spring-cloud-starter-zuul org.springframework.cloud spring-cloud-starter-eureka org.springframework.boot spring-boot-starter-test test
- 编写配置文件
# 自定义服务名称spring.application.name=api-gateway# 自定义端口server.port=5555# 服务注册中心地址eureka.client.serviceUrl.defaultZone=http://localhost:1111/eureka/
@EnableZuulProxy
-
这个时候我们可以通过 zuul 来动态访问 service-A 和 service-B,例如
-
http://127.0.0.1:5555/service-b/add?a=1&b=2
有了 zuul 我们就可以在不需要知道 service-A和 service-B 的情况下,通过Eureka 服务注册中心,直接使用注册过的服务。而且 zuul 也可以对请求做一些检验拦截,以及对请求响应做一些需要的处理。比如我们可以对请求做下 token验证,也就是请求的时候必须带上参数 token。
四、Zuul 的过滤器
- 对token做验证,我们需要通过Zuul的过滤器来实现。写个类继承ZuulFilter.java
package com.example.eureka.demo.zuul.filter;import com.netflix.zuul.ZuulFilter;import com.netflix.zuul.context.RequestContext;import org.apache.commons.lang.StringUtils;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import javax.servlet.http.HttpServletRequest;/** *
* 功能:
* 作者:@author Silence
* 日期:2018-03-12 17:00
* 详细说明:无
*/public class AuthFilter extends ZuulFilter { private final Logger logger = LoggerFactory.getLogger(AuthFilter.class); /** * 可以在请求被路由之前调用 * 定义filter的类型,有pre、route、post、error四种 * * @return */ @Override public String filterType() { return "pre"; } /** * 定义filter的顺序,数字越小表示顺序越高,越先执行 * * @return */ @Override public int filterOrder() { return 0; } /** * 表示是否需要执行该filter,true表示执行,false表示不执行 * * @return */ @Override public boolean shouldFilter() { return true; } /** * filter需要执行的具体操作 * * @return */ @Override public Object run() { RequestContext ctx = RequestContext.getCurrentContext(); HttpServletRequest request = ctx.getRequest(); logger.info("--->>> AuthFilter {},{}", request.getMethod(), request.getRequestURL().toString()); //获取请求的参数 String token = request.getParameter("token"); if (StringUtils.isNotBlank(token)) { //对请求进行路由 ctx.setSendZuulResponse(true); ctx.setResponseStatusCode(200); ctx.set("isSuccess", true); return null; } else { //不对其进行路由 ctx.setSendZuulResponse(false); ctx.setResponseStatusCode(400); ctx.setResponseBody("token is empty"); ctx.set("isSuccess", false); return null; } }}
ZuulFilter.java 需要覆盖四个方法,
- filterType() 返回的是字符串,有四个值pre、route、post、error,分别对应请求的状态。
- filterOrder() 定义filter的顺序,数字越小表示顺序越高,越先执行
- shouldFilter() 表示是否需要执行该filter,true表示执行,false表示不执行
- run() filter需要执行的具体操作具体执行的逻辑
- 在启动类里面初始化过滤器
package com.example.eureka.demo.zuul;import com.example.eureka.demo.zuul.filter.AuthFilter;import org.springframework.boot.SpringApplication;import org.springframework.cloud.client.SpringCloudApplication;import org.springframework.cloud.netflix.zuul.EnableZuulProxy;import org.springframework.context.annotation.Bean;/** * @author silence */@EnableZuulProxy@SpringCloudApplicationpublic class DemoZuulApplication { public static void main(String[] args) { SpringApplication.run(DemoZuulApplication.class, args); } /** * 注入权限过滤器 * * @return */ @Bean public AuthFilter authFilter() { return new AuthFilter(); }}
-
重启zuul项目
-
重新访问service-A和service-B服务
不增加token参数
增加token参数