面试题答案
一键面试微代理的主要功能
- 路由:根据请求的URL等信息,将请求转发到相应的微服务实例。例如,把对
/user-service/*
的请求转发到用户服务实例。 - 过滤:在请求转发前后进行处理,如身份验证、日志记录、流量监控等。可以在请求进入时检查JWT令牌进行身份验证,在请求处理后记录响应时间。
- 负载均衡:当有多个相同微服务实例时,合理分配请求到不同实例,提高系统整体性能和可用性。例如采用轮询、随机等负载均衡策略。
- 熔断:当某个微服务出现故障或响应时间过长时,防止级联故障,快速返回错误响应,避免大量请求积压。
配置简单路由规则(以Spring Cloud Gateway为例)
- 引入依赖:在
pom.xml
文件中添加Spring Cloud Gateway依赖。
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
- 配置路由规则:在
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为例)
- 引入依赖:在
pom.xml
文件中添加Zuul依赖。
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>
- 启用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);
}
}
- 配置路由规则:在
application.yml
文件中配置路由。假设要将/api/user/**
的请求转发到名为user-service
的微服务实例。
zuul:
routes:
user-service-route:
path: /api/user/**
serviceId: user-service
这里path
指定匹配的请求路径,serviceId
指定目标微服务名。