zl程序教程

您现在的位置是:首页 >  后端

当前栏目

微服务架构开发实战:如何集成Zuul和实现API网关?

集成架构服务API开发 实现 如何 实战
2023-06-13 09:14:12 时间

如何集成 Zuul

本节将基于Zuul来实现API网关。作为Spring Cloud 的一部分,集成Zuul会变得非常简单。

Zuul简介

路由是微服务架构中必需的一部分,如“”可能映射到Web程序上、“/api/users”可能映射到用户服务上、“/api/shop”可能映射到商品服务商。通过路由,让不同的服务都集中到统一的入口上来,这就是API网关的作用。

Zuul是Netflix出品的一个基于JVM路由和服务端的负载均衡器。

Zuul 功能如下。

  • 认证。
  • 压力测试。
  • 金丝雀测试。
  • 动态路由。
  • 负载削减。
  • 安全。
  • 静态响应处理。
  • 主动/主动交换管理。

Zuul的规则引擎允许通过任何JVM语言来编写规则和过滤器,支持基于Java和Groovy的构建。

在 micro-weather-cureka-client的基础上稍作修改,即可成为一个新的应用micro-weather-cure-ka-client-zuul,将其作为示例。

所需环境

为了演示本例,需要采用如下开发环境。

.JDK8。

. Gradle 4.0。

Spring Boot 2.0.0.M3。

.Spring Cloud Starter Netflix Eureka Client Finchley.M2。

.Spring Cloud Starter Netflix Zuul Finchley.M2。

更改配置

要使用Zuul,最简单的方式莫过于添加Zuul依赖。

dependencies{
/l...
//添加Spring Cloud Starter Netflix Zuul依赖
compile('org.springframework.cloud:spring-cloud-starter-netflix-zuul')
}

使用Zuul

要启用Zuul,最简单的方式就是在应用的根目录Application类上添加 org.springframework.cloud.netflix.zuul.EnableZuulProxy注解。

package com.waylau.spring.cloud.weather;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscovery
Client;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
/**
主应用程序.
*
*@since 1.0.0 2017年11月05日
* author <a href="https://waylau.com">Way Lau</a>
*/
@SpringBootApplication
EnableDiscoveryClient
@EnableZuulPrOxy
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}

其中,@EnableZuulProxy启用了Zuul作为反向代理服务器。

最后,修改application.properties。修改为如下配置。

spring.application.name: micro-weather-eureka-client-zuul
eureka.client.serviceUrl.defaultZone: http://localhost:8761/eureka/
zuul.routes.hi.path: /hi/**
zuul.routes.hi.serviceId: micro-weather-eureka-client

其中:

  • zuul.routes.hi.path :为要拦截请求的路径;
  • zuul.routes.hi.serviceld:为要拦截请求的路径所要映射的服务。本例将所有/hi下的请求,都转发到micro-weather-eureka-client应用中去。

运行和测试

启动在之前章节中创建的 micro-weather-eureka-server和micro-weather-eureka-client两个项目,以及本例的micro-weather-eureka-client-zuul项目。

如果一切正常,那么 micro-weather-eureka-server运行的管理界面能看到上述服务的信息。

通过浏览器访问micro-weather-zuul服务(本例地址为http:/localhost:8080),当试图访问接口时,如果一切正常,可以在控制台看到“Hello world”字样,这就是转发请求到 micro-weather-eu-reka-client服务时响应的内容,如图10-3所示。

源码

本节示例所涉及的源码,见 micro-weather-cureka-server、micro-weather-cureka-client,以及mi-cro-weather-cureka-client-zuul。

实现API网关

本节将在天气预报系统中使用API网关。

下面基于Zuul来实现API网关,由这个API网关来处理所有的用户请求。API网关将根据不同的请求路径,将请求路由到不同的微服务中去。

之前的天气预报微服务 msa-weather-report-eureka-feign最初是依赖于天气数据API微服务及城市数据API微服务。现在把这两个API微服务都合并到了API网关中,由API网关来负责请求的转发。那么,最后新的天气预报微服务就只需要依赖于API网关即可。这里将新的应用命名为msa-weather-report-eureka-feign-gatewayo

在前面创建的 micro-weather-eureka-client-zuul应用基础之上,再创建一个新的应用msa-weath-er-eureka-client-zuul,作为本节的API网关示例程序。

配置API网关

修改 msa-weather-eureka-client-zuul的 application.properties配置文件。修改为如下配置。

spring.application.name: msa-weather-eureka-client-zuul
eureka.client.serviceUrl.defaultZone: http://localhost:8761/eureka/
zuul.routes.city.path:/city/**
zuul.routes.city.serviceId: msa-weather-city-eureka
zuul.routes.data.path:/data/**
zuul.routes.data.serviceId:msa-weather-data-eureka

图10-4所示的是API网关的路由规则:当访问的路径匹配“city”时,则API网关将请求转发到msa-weather-city-eureka微服务中去;当访问的路径匹配“data”时,则API网关将请求转发到msa-weather-data-eureka微服务中去。

修改新的天气预报微服务

在 msa-weather-report-cureka-feign的基础上稍作修改,就能成为新版的msa-weather-report-cu-reka-feign-gateway。

主要的修改项集中在Feign'客户端。

1.修改Feign客户端

下面删除原来的CityClient、WeatherDataClient,并新建了DataClient用于获取城市列表数据及天气数据。

package com.waylau.spring.cloud.weather.service;
import java.util.List;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import com.waylau.spring.cloud.weather.vo.City;
import com.waylau.spring.cloud.weather.vo.WeatherResponse;
/*★
*访问数据的客户端
*@since 1.0.0 2017年11月6日
*@author <a href="https://waylau.com">Way Lau</a>
*/
@FeignClient("msa-weather-eureka-client-zuul")
public interface DataClient {
/*★
*获取城市列表
*
*@return
@throws Exception
*/
GetMapping("/city/cities")
List<City> listCity( throws Exception;
/**
*根据城市工D查询天气数据
*
*@param cityId
* @return
*/
@GetMapping("/data/weather/cityId/{cityId}")
WeatherResponse getDataByCityId (Pathvariable("cityId")String
cityId);
}

其中,在@FeignClient注解中,将服务地址指向了API网关 msa-weather-cureka-client-zul应用。

同时,修改WeatherReportServicelmpl,将依赖WeatherDataClient的地方改为了DataClient。

package com.waylau.spring.cloud.weather.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.waylau.spring.cloud.weather.vo.Weather;
import com.waylau.spring.cloud.weather.vo.WeatherResponse;
/**
*天气预报服务
* @since 1.0.0 2017年11月05日
*author <a href="https://waylau.com">Way Lau</a>
*/
@service
public class WeatherReportServiceImpl implements WeatherReportService {
@Autowired
private DataClient dataClient;
@override
public Weather getDataByCityId(String cityId){
/由天气数据API微服务来提供数据
WeatherResponse response = dataclient.getDataByCityld(cityId);
returnresponse.getData();
}
}

修改WeatherReportController,将依赖CityClient的地方改为了DataClient。

package com.waylau.spring.cloud.weather.controller;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import com.waylau.spring.cloud.weather.service.DataClient;
import com.waylau.spring.cloud.weather.service.WeatherReportService;
import com.waylau.spring.cloud.weather.vo.City;
/**
*天气预报API.
*
*Csince 1.0.0 2017年10月29日
* @author <a href="https://waylau.com">Way Lau</a>
*/
@RestController
RequestMapping("/report")
public class weatherReportController
private final static Logger logger = LoggerFactory.getLogger(Weather
ReportController.class);
@Autowired
private DataClient dataClient;
@Autowired
private WeatherReportService weatherReportService;
GetMapping("/cityId/{cityId}")
public ModelAndView getReportByCityId(PathVariable ("cityId")string
cityId,Model model) throws Exception {
//由城市数据API微服务来提供数据
List<City> cityList= null;
try
//调用城市数据API
cityList = dataclient.listCity();
catch(Exception e){
logger.error("获取城市信息异常!",e);
throw new RuntimeException("获取城市信息异常!",e);
)
model.addAttribute("title","老卫的天气预报");
model.addAttribute("cityId",cityId);
model.addAttribute("cityList",cityList);
model.addAttribute ("report", weatherReportService.getDataBy
cityId(city1d));
return new ModelAndView("weather/report", "reportModel",model);
}
}

2.修改应用配置

应用配置修改如下。

#热部署静态文件
spring.thymeleaf.cache=false
spring.application.name: msa-weather-report-eureka-feign-gateway
eureka.client.serviceUrl.defaultZone: http://localhost:8761/eureka/
feign.client.config.feignName.connectTimeout:5000
feign.client.config.feignName.readTimeout: 5000

运行微服务实例

首先运行Eureka Server实例 micro-weather-eureka-server,它在8761端口启动。

其次要运行Redis服务器。

而后分别在8081和8082上启动 msa-weather-collection-cureka-feign实例两个,在8083和8084上启动msa-weather-data-eureka实例两个,在8085和 8086上启动msa-weather-city-eureka实例两个,在8087和8088上启动msa-weather-report-cureka-feign-gateway实例两个,在8089上启动msa-weather-cureka-client-zuul API 网关实例。启动脚本如下。

java-jar msa-weather-collection-eureka-feign-1.0.0.jar --server.port=8081
java-jar msa-weather-collection-eureka-feign-1.0.0.jar--server.port=8082
java -jar msa-weather-data-eureka-1.0.0.jar --server.port=8083
java -jar msa-weather-data-eureka-1.0.0.jar --server.port=8084
java -jar msa-weather-city-eureka-1.0.0.jar --server.port=8085
java -jar msa-weather-city-eureka-1.0.0.jar--server.port=8086
java-jar msa-weather-report-eureka-feign-gateway-1.0.0.jar --server.port=8087
java -jar msa-weather-report-eureka-feign-gateway-1.0.0.jar --server.port=8088
java-jar msa-weather-eureka-client-zuul-1.0.0.jar --server.port=8089

这样,就可以在Eureka Server上看到这8个实例的信息。访问http:/localhost:8761,可以看到如图9-3所示的Eureka Server自带的UI管理界面。

访问天气预报微服务的任意一个实例,都能够正常使用天气数据微服务和城市数据微服务。如在浏览器访问其中一个实例( http://localhost:8088/report/cityld/101280601)来进行测试。

源码

本节示例所涉及的源码,见 micro-weather-eureka-server、msa-weather-collection-cureka-feign、msa-weather-data-eureka、msa-weather-city-eureka、msa-weather-report-eureka-feign-gateway .micro-weather-eureka-client-zuul,以及msa-weather-eureka-client-zuul。

本篇文章内容给大家讲解的是如何集成 Zuul和实现API网关

  1. 下篇文章给大家讲解微服务的部署与发布;
  2. 觉得文章不错的朋友可以转发此文关注小编;
  3. 感谢大家的支持!

本文就是愿天堂没有BUG给大家分享的内容,大家有收获的话可以分享下,想学习更多的话可以到微信公众号里找我,我等你哦。‍