You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
trea1/ServiceGateway.java

65 lines
2.0 KiB

package com.soa.gateway;
import com.soa.bus.ServiceBus;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* 服务网关 - 负责请求的路由、认证、限流等
*/
public class ServiceGateway {
private static final Logger logger = LogManager.getLogger(ServiceGateway.class);
private final ServiceBus serviceBus;
public ServiceGateway() {
this.serviceBus = ServiceBus.getInstance();
}
/**
* 处理请求
*/
public String handleRequest(String serviceName, String request, String apiKey) {
// 1. 验证API Key
if (!validateApiKey(apiKey)) {
logger.warn("Invalid API Key: {}", apiKey);
return "Error: Unauthorized access - Invalid API Key";
}
// 2. 日志请求
logger.info("Request received for service: {}, with API Key ending in: {}",
serviceName, apiKey.substring(apiKey.length() - 4));
// 3. 检查限流(简单实现)
if (!checkRateLimit(apiKey)) {
logger.warn("Rate limit exceeded for API Key: {}", apiKey);
return "Error: Rate limit exceeded";
}
// 4. 路由到服务总线
return serviceBus.callService(serviceName, request);
}
/**
* 验证API Key
*/
private boolean validateApiKey(String apiKey) {
// 简化实现 - 实际应该从数据库或配置中验证
return apiKey != null && apiKey.startsWith("valid_");
}
/**
* 检查限流
*/
private boolean checkRateLimit(String apiKey) {
// 简化实现 - 实际应该使用令牌桶或漏桶算法
return true;
}
/**
* 获取服务状态
*/
public String getServiceStatus(String serviceName) {
boolean available = serviceBus.isServiceAvailable(serviceName);
return "Service: " + serviceName + " - Status: " + (available ? "Available" : "Unavailable");
}
}