高级Java微服务面试题与深度解析
一、Spring Cloud核心组件深度剖析
1. Eureka服务注册发现机制
题目:详细分析Eureka的AP特性实现原理,包括服务注册、续约、剔除和自我保护机制,并说明与Nacos的CP模式区别。
答案:
Eureka AP实现原理:
// 服务注册核心逻辑
public void register(InstanceInfo info) {
// 写入注册表(ConcurrentHashMap)
registry.put(info.getId(), info);
// 同步到其他节点(异步复制)
replicateToPeers(Action.Register, info);
}
// 服务续约(每30秒)
public boolean renew(String appName, String id) {
Lease<InstanceInfo> lease = registry.get(id);
if (lease != null) {
lease.renew(); // 更新最后更新时间戳
return true;
}
return false;
}
// 服务剔除(每60秒检查)
void evict() {
List<Lease<InstanceInfo>> expiredLeases = new ArrayList<>();
for (Lease<InstanceInfo> lease : registry.values()) {
if (lease.isExpired()) { // 90秒未续约
expiredLeases.add(lease);
}
}
// 随机剔除(避免同时剔除过多服务)
int toEvict = Math.min(expiredLeases.size(),
(int) (registry.size() * 0.85));
for (int i = 0; i < toEvict; i++) {
registry.remove(expiredLeases.get(i).getHolder().getId());
}
}
// 自我保护机制
if (numOfRenews < expectedNumberOfRenewsPerMin * 0.85) {
// 进入保护模式,停止剔除服务
protectionModeOn = true;
}
与Nacos CP模式对比:
- 数据一致性:
- Eureka:最终一致,通过异步复制
- Nacos:Raft协议保证强一致
- 注册表存储:
- Eureka:双层Map(应用-实例)
- Nacos:Distro协议+持久化存储
- 健康检查:
- Eureka:客户端心跳(30秒)
- Nacos:TCP/HTTP/MYSQL主动探测
- 适用场景:
- Eureka:高可用优先场景
- Nacos:配置中心等需要强一致场景
二、Dubbo核心架构深度解析
2. Dubbo服务调用链路
题目:分析Dubbo服务调用过程中的Filter链、负载均衡和集群容错机制,用流程图说明一次RPC调用的完整过程。
答案:
调用流程图:
Consumer → Proxy → FilterChain → LoadBalance → Cluster → Network → Server FilterChain → ServiceImpl
核心组件实现:
// Filter责任链(SPI扩展点)
public interface Filter {
Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException;
}
// 负载均衡策略
public abstract class AbstractLoadBalance implements LoadBalance {
public <T> Invoker<T> select(List<Invoker<T>> invokers, URL url, Invocation invocation) {
if (invokers.isEmpty()) return null;
if (invokers.size() == 1) return invokers.get(0);
return doSelect(invokers, url, invocation); // 模板方法
}
// 具体策略:Random/RoundRobin/LeastActive等
protected abstract <T> Invoker<T> doSelect(...);
}
// 集群容错(Cluster接口)
public class FailoverCluster implements Cluster {
public <T> Invoker<T> join(Directory<T> directory) throws RpcException {
return new FailoverClusterInvoker<>(directory);
}
}
// 网络通信(Netty实现)
public class NettyClient extends AbstractClient {
protected void doOpen() {
bootstrap = new Bootstrap()
.group(eventLoopGroup)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
protected void initChannel(SocketChannel ch) {
ch.pipeline()
.addLast("decoder", new NettyDecoder())
.addLast("encoder", new NettyEncoder())
.addLast("handler", new NettyClientHandler());
}
});
}
}
关键配置项:
# 负载均衡
dubbo.provider.loadbalance=leastactive
# 集群容错
dubbo.consumer.cluster=failover
dubbo.consumer.retries=2
# 超时控制
dubbo.reference.timeout=3000
三、Spring Cloud Alibaba整合
3. Sentinel熔断降级原理
题目:分析Sentinel的滑动窗口统计和熔断规则判断机制,对比Hystrix的实现差异。
答案:
Sentinel核心实现:
// 滑动窗口统计(LeapArray)
public class LeapArray<T> {
private final AtomicReferenceArray<WindowWrap<T>> array;
private final int windowLengthInMs; // 窗口长度(如500ms)
public T currentWindow() {
long time = TimeUtil.currentTimeMillis();
int idx = calculateTimeIdx(time);
long windowStart = calculateWindowStart(time);
while (true) {
WindowWrap<T> old = array.get(idx);
if (old == null) {
// 初始化新窗口
WindowWrap<T> window = new WindowWrap<>(windowLengthInMs, windowStart, newEmptyBucket());
if (array.compareAndSet(idx, null, window)) {
return window.value();
}
} else if (windowStart == old.windowStart()) {
return old.value();
} else if (windowStart > old.windowStart()) {
// 重置过期窗口
if (updateLock.tryLock()) {
try {
return resetWindowTo(old, windowStart);
} finally {
updateLock.unlock();
}
}
}
}
}
}
// 熔断规则判断
public class CircuitBreaker {
protected boolean checkState(StatisticNode node) {
if (rule.getStrategy() == RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO) {
double exception = node.exceptionQps();
double success = node.successQps();
// 异常比例超过阈值
if (success + exception >= rule.getMinRequestAmount()
&& exception / (success + exception) >= rule.getThreshold()) {
return true;
}
}
return false;
}
}
与Hystrix对比:
┌──────────────────┬──────────────────────────────┬──────────────────────────────┐
│ 特性 │ Sentinel │ Hystrix │
├──────────────────┼──────────────────────────────┼──────────────────────────────┤
│ 隔离策略 │ 信号量(并发控制) │ 线程池/信号量 │
│ 熔断维度 │ 资源粒度 │ 命令粒度 │
│ 统计模型 │ 滑动窗口(实时统计) │ 固定窗口(桶计数) │
│ 规则配置 │ 动态规则(支持多种数据源) │ 静态配置 │
│ 系统自适应 │ 支持(Load/QPS/线程数等) │ 不支持 │
│ 热点防护 │ 支持 │ 不支持 │
└──────────────────┴──────────────────────────────┴──────────────────────────────┘
四、分布式事务解决方案
4. Seata的AT模式实现
题目:详细说明Seata AT模式的工作流程,包括全局事务协调、分支事务注册和两阶段提交的具体实现。
答案:
AT模式执行流程:
// 1. 全局事务开始
@GlobalTransactional
public void purchase() {
// 分支事务1
orderService.create();
// 分支事务2
storageService.deduct();
}
// 2. 分支事务注册
public class DataSourceProxy extends AbstractDataSourceProxy {
public ConnectionProxy getConnection() throws SQLException {
// 拦截SQL生成undo_log
Connection conn = targetDataSource.getConnection();
return new ConnectionProxy(conn, dataSourceProxy);
}
}
// 3. 两阶段提交
// 第一阶段:本地事务提交
INSERT INTO undo_log (xid, branch_id, rollback_info, log_status)
VALUES (?, ?, ?, ?);
// 第二阶段:
// - 成功:异步删除undo_log
// - 失败:根据undo_log补偿
核心组件交互:
TM(事务管理器) → TC(事务协调器) ←→ RM(资源管理器)
↑ ↑
| |
全局事务ID 分支事务状态
关键实现细节:
- SQL解析:通过DataSourceProxy拦截SQL,解析表/行数据
- 前置镜像:SELECT获取修改前数据
- 后置镜像:SELECT获取修改后数据
- 全局锁:防止其他事务修改相同数据
性能优化点:
- 异步化第二阶段处理
- 全局锁优化(减少锁持有时间)
- 批量undo_log删除
五、服务网格与云原生
5. Spring Cloud Gateway与Envoy对比
题目:对比分析Spring Cloud Gateway和Envoy的架构设计、性能特点和适用场景。
答案:
架构对比:
// Spring Cloud Gateway核心流程
public class FilteringWebHandler implements WebHandler {
public Mono<Void> handle(ServerWebExchange exchange) {
Route route = exchange.getRequiredAttribute(GATEWAY_ROUTE_ATTR);
List<GatewayFilter> filters = route.getFilters();
return new DefaultGatewayFilterChain(filters)
.filter(exchange)
.then(proxyService.forward(exchange));
}
}
// Envoy过滤器链(C++实现)
void FilterManager::onContinueDecoding() {
for (auto& filter : decoder_filters_) {
FilterStatus status = filter->decodeHeaders(headers, end_stream);
if (status == StopIteration) return;
}
}
特性对比表:
┌──────────────────┬──────────────────────────────┬──────────────────────────────┐
│ 特性 │ Spring Cloud Gateway │ Envoy │
├──────────────────┼──────────────────────────────┼──────────────────────────────┤
│ 开发语言 │ Java │ C++ │
│ 配置方式 │ Java DSL/YAML │ xDS API/YAML │
│ 协议支持 │ HTTP/WebSocket │ HTTP/gRPC/TCP等 │
│ 扩展能力 │ 自定义Filter(Java) │ WASM/Lua插件 │
│ 性能 │ 万级QPS │ 十万级QPS │
│ 服务发现 │ Eureka/Nacos等 │ 集成K8s │
│ 适用场景 │ Spring生态微服务 │ 多语言服务网格 │
└──────────────────┴──────────────────────────────┴──────────────────────────────┘
选型建议:
Spring Cloud Gateway:
- 已有Spring Cloud技术栈
- 需要深度Java定制
- 快速开发API网关
Envoy:
- 多语言混合架构
- 需要高级流量管理(金丝雀/镜像)
- 已使用Istio服务网格