Spring-Cloud-Zuul API Gateway

本文介绍如何使用Spring Cloud Zuul实现API网关功能,包括面向服务的路由配置及自定义全局过滤器的方法。

首先,引入spring-cloud-starter-zuul,还有dependencyManagement中的spring-cloud-dependencies

注意,如果使用的spring-cloud-dependencies是版本Finchley.SR2,结合spring-boot-starter-parent版本2.1.1.RELEASE,会报错:

The bean 'counterFactory', defined in class path resource [org/springframework/cloud/netflix/zuul/ZuulServerAutoConfiguration$ZuulCounterFactoryConfiguration.class], could not be registered. A bean with that name has already been defined in class path resource [org/springframework/cloud/netflix/zuul/ZuulServerAutoConfiguration$ZuulMetricsConfiguration.class] and overriding is disabled.

解决办法:把sprinboot降级到2.0.6.RELEASE即可。以下是全部POM:

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.6.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.sc</groupId>
	<artifactId>zuul-gateway</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>zuul-gateway</name>
	<description>Demo project for Spring Boot of Spring Cloud Zuul Gateway</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-zuul</artifactId>
			<version>1.4.6.RELEASE</version>
		</dependency>
	</dependencies>
	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.springframework.cloud</groupId>
				<artifactId>spring-cloud-dependencies</artifactId>
				<version>Finchley.SR2</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

接着,在application.properties定义路由:

spring.application.name=zuul-gateway
server.port=5555
zuul.routes.api-a-url.path=/api-a-url/**
zuul.routes.api-a-url.url=http://localhost:8081/

那么,当我们访问http://localhost:5555/api-a-url/hello, API网关服务会讲请求路由到http://localhost:8081/hello. 如图:

特别的,Spring-Cloud-Zuul默认引入spring-cloud-actuator, 所以在启动的时候可以看到日志:

但是,这种基于传统路由的配置方式对于运维非常不友好,所以,必须实现面向服务的路由!

首先,引入spring-clould-eureka:

		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-eureka</artifactId>
			<version>1.4.6.RELEASE</version>
		</dependency>

定义serviceId和path:

spring.application.name=zuul-gateway
server.port=5555
#zuul.routes.api-a-url.path=/api-a-url/**
#zuul.routes.api-a-url.url=http://localhost:8081/
zuul.routes.api-a.path=/api-a/**
zuul.routes.api-a.serviceId=hello-service
zuul.routes.api-b.path=/api-b/**
zuul.routes.api-b.serviceId=feign-consumer
eureka.client.service-url.defaultZone=http://localhost:12451/eureka/,http://localhost:12452/eureka/

那么,访问curl http://127.0.0.1:5555/api-a/hello/等同于访问curl http://127.0.0.1:8081/hello/或者curl http://127.0.0.1:8082/hello/

访问curl http://127.0.0.1:5555/api-b/feign-consumer3/等同于访问curl http://127.0.0.1:9001/feign-consumer3/

如图:

在eureka面板可以看到服务zuul-gateway

接着,我们思考假设需要在url必须附带一个accessToken才实现转发,也就是增加一个全局filter,

那么新定义一个AccessFilter继承com.netflix.zuul.ZuulFilter:

注意,

  • 里面的方法filterType返回pre表示前置,
  • filterOrder返回0表示顺序,
  • shouldFilter返回true表示应该执行filter
  • run表示具体执行filter,主要是对com.netflix.zuul.context.RequestContext中的HttpServletRequest进行赋值
package com.sc.zuulgateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;

public class AccessFilter  extends ZuulFilter{

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        this.logger.info("send {} request to {}", request.getMethod(), request.getRequestURL().toString());
        Object accessToken = request.getParameter("accessToken");
        if (accessToken == null){
            this.logger.warn("access token is empty");
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            return null;
        }
        this.logger.info("access token ok");
        return null;
    }
}

然后,创建具体的Bean启动过滤器:

package com.sc.zuulgateway;

import com.sc.zuulgateway.filter.AccessFilter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
@EnableZuulProxy
public class ZuulGatewayApplication {

	public static void main(String[] args) {
		SpringApplication.run(ZuulGatewayApplication.class, args);
	}

	@Bean
	public AccessFilter accessFilter(){
		return new AccessFilter();
	}

}

结果:当url不附带accessToken的时候返回http statusCode为401,并且Content-Length为0.

在人工智能技术快速演进的推动下,视频监控领域的智能化已成为研究重点。结合对比语言-图像预训练模型与单次检测算法的智能监控方案由此产生。该方案主要实现实时目标识别、文本化检索请求、并行计算处理、双语言适配、反例样本构建、高效系统设计及运行状态即时监测等功能。对比语言-图像预训练模型通过海量图文配对数据预先学习,建立了视觉内容与文字描述间的语义关联,使其在处理监控影像时能更精准地响应用户的文本查询。单次检测算法将目标定位问题转化为回归任务,直接在图像中推算物体的位置框与类别概率,以其高效的处理速度与较高的识别精度在智能监控中得到普遍采用。文本化检索功能使用户能够通过日常语言描述来搜索监控画面中的特定对象或事件,降低了使用门槛,扩展了系统的适用场景与用户基础。并行计算技术通过同时处理多个视频流,显著提升了数据处理的即时性,缩短了响应延迟,增强了系统的实际可用性。双语言适配能力使系统可同时解析中文与英文等多种语言的查询指令,适应全球化应用需求,有助于技术在国际范围内的普及。反例样本构建在机器学习过程中起到关键作用,通过合理生成与利用反例数据,能够提升模型的泛化性能,防止过拟合现象,从而加强监控系统的准确度与鲁棒性。高效系统架构注重计算资源的合理调配、数据处理流程的优化以及系统的可扩展性,为实时视频分析提供稳定的基础支撑。运行状态即时监测持续跟踪系统各项性能指标,便于及时识别并处理潜在问题,保障系统长期可靠运行。该方案在安全防护、智能检索与视频内容解析等多个领域均有重要应用。在安防场景中,它能提升监控效能,加快对安全事件的反应速度;在检索应用中,用户可借助自然语言快速定位目标视频片段;在内容分析方面,系统能对海量视频进行智能解析,抽取关键信息以辅助决策。这一融合对比语言-图像预训练与单次检测算法的智能监控方案,不仅体现了技术层面的创新,更具备广泛的实际应用潜力与发展前景,预计将在未来的安防与智能分析领域发挥日益重要的作用。资源来源于网络分享,仅用于学习交流使用,请勿用于商业,如有侵权请联系我删除!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值