MST

星途 面试题库

面试题:微服务架构下Spring Cloud微代理的基础应用

在Spring Cloud微服务架构中,简述微代理(如Zuul或Spring Cloud Gateway)的主要功能,并说明如何配置一个简单的路由规则,将特定请求转发到指定的微服务实例。
29.6万 热度难度
后端开发微服务架构

知识考点

AI 面试

面试题答案

一键面试

微代理的主要功能

  1. 路由:根据请求的URL等信息,将请求转发到相应的微服务实例。例如,把对/user-service/*的请求转发到用户服务实例。
  2. 过滤:在请求转发前后进行处理,如身份验证、日志记录、流量监控等。可以在请求进入时检查JWT令牌进行身份验证,在请求处理后记录响应时间。
  3. 负载均衡:当有多个相同微服务实例时,合理分配请求到不同实例,提高系统整体性能和可用性。例如采用轮询、随机等负载均衡策略。
  4. 熔断:当某个微服务出现故障或响应时间过长时,防止级联故障,快速返回错误响应,避免大量请求积压。

配置简单路由规则(以Spring Cloud Gateway为例)

  1. 引入依赖:在pom.xml文件中添加Spring Cloud Gateway依赖。
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
  1. 配置路由规则:在application.yml文件中配置路由。假设要将/api/user/**的请求转发到名为user-service的微服务实例。
spring:
  cloud:
    gateway:
      routes:
      - id: user-service-route
        uri: lb://user-service
        predicates:
        - Path=/api/user/**

上述配置中,id为路由的唯一标识;uri指定了目标微服务,lb://表示使用负载均衡,后面跟着微服务名;predicates中的Path表示匹配的请求路径。

配置简单路由规则(以Zuul为例)

  1. 引入依赖:在pom.xml文件中添加Zuul依赖。
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>
  1. 启用Zuul:在启动类上添加@EnableZuulProxy注解。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;

@SpringBootApplication
@EnableZuulProxy
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
  1. 配置路由规则:在application.yml文件中配置路由。假设要将/api/user/**的请求转发到名为user-service的微服务实例。
zuul:
  routes:
    user-service-route:
      path: /api/user/**
      serviceId: user-service

这里path指定匹配的请求路径,serviceId指定目标微服务名。