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.
58 lines
2.1 KiB
58 lines
2.1 KiB
package mxdx2;
|
|
|
|
//服务总线接口(中介者模式)
|
|
public interface ServiceBus {
|
|
// 注册服务
|
|
void registerService(String serviceName, ServiceEndpoint endpoint);
|
|
// 路由请求
|
|
Object routeRequest(String serviceName, String method, Object... params);
|
|
// 注册监控器
|
|
void registerMonitor(ServiceMonitor monitor);
|
|
}
|
|
|
|
//服务总线实现
|
|
public class EnterpriseServiceBus implements ServiceBus {
|
|
// 服务注册表:服务名 -> 服务端点
|
|
private Map<String, ServiceEndpoint> serviceRegistry = new ConcurrentHashMap<>();
|
|
// 监控器列表
|
|
private List<ServiceMonitor> monitors = new CopyOnWriteArrayList<>();
|
|
|
|
@Override
|
|
public void registerService(String serviceName, ServiceEndpoint endpoint) {
|
|
serviceRegistry.put(serviceName, endpoint);
|
|
notifyMonitor("REGISTER", serviceName, "Service registered");
|
|
}
|
|
|
|
@Override
|
|
public Object routeRequest(String serviceName, String method, Object... params) {
|
|
ServiceEndpoint endpoint = serviceRegistry.get(serviceName);
|
|
if (endpoint == null) {
|
|
notifyMonitor("ERROR", serviceName, "Service not found");
|
|
throw new ServiceNotFoundException("Service " + serviceName + " not found");
|
|
}
|
|
|
|
try {
|
|
long startTime = System.currentTimeMillis();
|
|
Object result = endpoint.invoke(method, params);
|
|
long cost = System.currentTimeMillis() - startTime;
|
|
notifyMonitor("INVOKE", serviceName, "Success, cost=" + cost + "ms");
|
|
return result;
|
|
} catch (Exception e) {
|
|
notifyMonitor("ERROR", serviceName, "Invocation failed: " + e.getMessage());
|
|
throw new ServiceInvocationException(e);
|
|
}
|
|
}
|
|
|
|
@Override
|
|
public void registerMonitor(ServiceMonitor monitor) {
|
|
monitors.add(monitor);
|
|
}
|
|
|
|
// 通知监控器
|
|
private void notifyMonitor(String type, String serviceName, String message) {
|
|
ServiceEvent event = new ServiceEvent(type, serviceName, message, System.currentTimeMillis());
|
|
for (ServiceMonitor monitor : monitors) {
|
|
monitor.onEvent(event);
|
|
}
|
|
}
|
|
} |