- Added comprehensive course structure with 11 modules - Included theoretical content, practical examples, and tasks - Multi-language code examples (Java, Rust, Node.js, Python) - Detailed analysis of architectural approaches and trade-offs - Complete caching strategies documentation - Architecture examples from real-world systems (Twitter, Netflix, Uber) - Structured navigation and learning path - Ready for educational use
5.3 KiB
5.3 KiB
Performance Testing
Навигация
Типы тестов производительности
1. Load Testing
// Load тестирование с JMeter
@Component
public class LoadTestRunner {
public void runLoadTest() {
// Настройка JMeter теста
JMeterEngine engine = new StandardJMeterEngine();
// Загрузка тестового плана
HashTree testPlanTree = new HashTree();
TestPlan testPlan = new TestPlan();
testPlan.setName("User Service Load Test");
// Настройка потока
ThreadGroup threadGroup = new ThreadGroup();
threadGroup.setName("Users");
threadGroup.setNumThreads(100);
threadGroup.setRampUp(60);
threadGroup.setDuration(300); // 5 минут
// Настройка HTTP запроса
HTTPSamplerProxy httpSampler = new HTTPSamplerProxy();
httpSampler.setDomain("localhost");
httpSampler.setPort(8080);
httpSampler.setPath("/api/users");
httpSampler.setMethod("GET");
// Добавление элементов в тест
testPlanTree.add(testPlan);
testPlanTree.add(testPlan, threadGroup);
testPlanTree.add(threadGroup, httpSampler);
// Запуск теста
engine.configure(testPlanTree);
engine.run();
}
}
2. Stress Testing
// Stress тестирование
@Service
public class StressTestService {
@Autowired
private UserService userService;
public void runStressTest() {
int numberOfThreads = 200;
int requestsPerThread = 1000;
ExecutorService executor = Executors.newFixedThreadPool(numberOfThreads);
CountDownLatch latch = new CountDownLatch(numberOfThreads);
for (int i = 0; i < numberOfThreads; i++) {
executor.submit(() -> {
try {
for (int j = 0; j < requestsPerThread; j++) {
// Выполняем запрос
userService.getUser((long) (Math.random() * 1000));
// Небольшая задержка
Thread.sleep(10);
}
} catch (Exception e) {
log.error("Stress test error", e);
} finally {
latch.countDown();
}
});
}
try {
latch.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
executor.shutdown();
}
}
3. Endurance Testing
// Endurance тестирование
@Component
public class EnduranceTestRunner {
@Autowired
private UserService userService;
@Scheduled(fixedRate = 1000) // каждую секунду
public void runEnduranceTest() {
try {
// Выполняем запрос
userService.getUser(1L);
// Логируем метрики
log.info("Endurance test - request completed");
} catch (Exception e) {
log.error("Endurance test error", e);
}
}
}
Автоматизация тестов производительности
1. Automated Performance Tests
// Автоматизированные performance тесты
@SpringBootTest
@TestPropertySource(properties = {
"spring.datasource.url=jdbc:h2:mem:testdb",
"spring.jpa.hibernate.ddl-auto=create-drop"
})
public class PerformanceTestSuite {
@Autowired
private UserService userService;
@Test
public void testUserServicePerformance() {
// Подготовка данных
List<User> users = createTestUsers(1000);
// Измерение времени выполнения
long startTime = System.currentTimeMillis();
for (User user : users) {
userService.createUser(user);
}
long endTime = System.currentTimeMillis();
long duration = endTime - startTime;
// Проверка производительности
assertThat(duration).isLessThan(5000); // менее 5 секунд
// Проверка пропускной способности
double throughput = (double) users.size() / duration * 1000;
assertThat(throughput).isGreaterThan(100); // более 100 RPS
}
@Test
public void testDatabaseQueryPerformance() {
// Подготовка данных
createTestUsers(10000);
// Измерение времени выполнения запроса
long startTime = System.currentTimeMillis();
List<User> users = userService.findUsersByName("Test");
long endTime = System.currentTimeMillis();
long duration = endTime - startTime;
// Проверка производительности
assertThat(duration).isLessThan(1000); // менее 1 секунды
}
}