diff --git a/MicroserviceDemo.java b/MicroserviceDemo.java new file mode 100644 index 0000000..553359f --- /dev/null +++ b/MicroserviceDemo.java @@ -0,0 +1,191 @@ +package com.soa.microservice.core; + +import com.soa.microservice.registry.InMemoryServiceRegistry; +import com.soa.microservice.transaction.TwoPhaseCommitTransactionManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * 微服务治理平台演示类 + * 展示服务注册发现、负载均衡、熔断降级和分布式事务功能 + */ +public class MicroserviceDemo { + private static final Logger logger = LoggerFactory.getLogger(MicroserviceDemo.class); + + public static void main(String[] args) throws Exception { + logger.info("Starting microservice governance platform demo..."); + + // 1. 初始化服务注册中心 + InMemoryServiceRegistry registry = new InMemoryServiceRegistry(); + logger.info("Service registry initialized"); + + // 2. 初始化服务客户端 + DefaultServiceClient serviceClient = new DefaultServiceClient(registry); + logger.info("Service client initialized"); + + // 3. 注册测试服务实例 + registerTestServices(registry); + + // 4. 测试服务发现和负载均衡 + testServiceDiscoveryAndLoadBalancing(serviceClient); + + // 5. 测试熔断功能 + testCircuitBreaker(serviceClient); + + // 6. 测试分布式事务 + testDistributedTransaction(); + + logger.info("Demo completed successfully!"); + } + + /** + * 注册测试服务 + */ + private static void registerTestServices(InMemoryServiceRegistry registry) { + // 注册用户服务的3个实例 + for (int i = 1; i <= 3; i++) { + ServiceInstance userService = new ServiceInstance( + "user-service-" + i, + "user-service", + "localhost", + 8000 + i + ); + userService.addMetadata("version", "v1"); + registry.register(userService); + } + + // 注册订单服务的2个实例 + for (int i = 1; i <= 2; i++) { + ServiceInstance orderService = new ServiceInstance( + "order-service-" + i, + "order-service", + "localhost", + 9000 + i + ); + orderService.addMetadata("version", "v1"); + registry.register(orderService); + } + + logger.info("Registered test services: {}", registry.getServices()); + } + + /** + * 测试服务发现和负载均衡 + */ + private static void testServiceDiscoveryAndLoadBalancing(DefaultServiceClient client) throws Exception { + logger.info("\n--- Testing Service Discovery and Load Balancing ---"); + + // 测试轮询负载均衡 + logger.info("Testing round-robin load balancing..."); + Map instanceCount = new HashMap<>(); + + for (int i = 0; i < 10; i++) { + Object result = client.invoke("user-service", "getUserInfo", i); + logger.info("Invocation result: {}", result); + + // 统计每个实例的调用次数 + String instanceInfo = result.toString(); + String instanceId = instanceInfo.split("on ")[1]; + instanceCount.computeIfAbsent(instanceId, k -> new AtomicInteger(0)).incrementAndGet(); + } + + // 打印负载均衡结果 + logger.info("Load balancing distribution:"); + for (Map.Entry entry : instanceCount.entrySet()) { + logger.info("Instance {}: {} calls", entry.getKey(), entry.getValue().get()); + } + } + + /** + * 测试熔断功能 + */ + private static void testCircuitBreaker(DefaultServiceClient client) throws Exception { + logger.info("\n--- Testing Circuit Breaker ---"); + + // 创建一个会失败的服务客户端 + ServiceClient failingClient = new DefaultServiceClient(new InMemoryServiceRegistry()) { + @Override + public Object invoke(String serviceName, String method, Object... params) throws Exception { + // 模拟服务调用失败 + throw new Exception("Service unavailable"); + } + }; + + // 测试熔断触发 + int failureCount = 0; + for (int i = 0; i < 10; i++) { + try { + failingClient.invoke("test-service", "testMethod"); + } catch (Exception e) { + failureCount++; + logger.info("Invocation {} failed: {}", i+1, e.getMessage()); + } + } + + logger.info("Total failures: {}", failureCount); + logger.info("Circuit breaker should be open after consecutive failures"); + } + + /** + * 测试分布式事务 + */ + private static void testDistributedTransaction() throws Exception { + logger.info("\n--- Testing Distributed Transaction ---"); + + TwoPhaseCommitTransactionManager transactionManager = new TwoPhaseCommitTransactionManager(); + + // 创建测试事务参与者 + TestTransactionParticipant participant1 = new TestTransactionParticipant("participant-1"); + TestTransactionParticipant participant2 = new TestTransactionParticipant("participant-2"); + + // 开始事务 + String txId = transactionManager.beginTransaction(); + logger.info("Transaction {} began", txId); + + // 添加参与者 + transactionManager.addParticipant(txId, participant1); + transactionManager.addParticipant(txId, participant2); + + // 提交事务 + boolean committed = transactionManager.commitTransaction(txId); + logger.info("Transaction {} committed: {}", txId, committed); + } + + /** + * 测试用的事务参与者 + */ + static class TestTransactionParticipant implements TransactionParticipant { + private final String participantId; + private static final Logger logger = LoggerFactory.getLogger(TestTransactionParticipant.class); + + public TestTransactionParticipant(String participantId) { + this.participantId = participantId; + } + + @Override + public boolean prepare(String transactionId) { + logger.info("Participant {} preparing for transaction {}", participantId, transactionId); + return true; // 模拟准备成功 + } + + @Override + public void commit(String transactionId) { + logger.info("Participant {} committing transaction {}", participantId, transactionId); + } + + @Override + public void rollback(String transactionId) { + logger.info("Participant {} rolling back transaction {}", participantId, transactionId); + } + + @Override + public String getParticipantId() { + return participantId; + } + } +} \ No newline at end of file