1. Spring Boot 性能优化
1.1 缓存优化
-
使用 Spring Cache:
@Cacheable("users")
public List<User> getAllUsers() {
return userRepository.findAll();
}
2.配置缓存管理器:
@Configuration
public class CacheConfig {
@Bean
public CacheManager cacheManager() {
return new ConcurrentMapCacheManager("users");
}
}
1.2 异步处理
-
使用 @Async 注解:
@Service
public class UserService {
@Async
public CompletableFuture<List<User>> fetchUsersAsync() {
return CompletableFuture.supplyAsync(() -> userRepository.findAll());
}
}
2.配置线程池:
@Configuration
public class AsyncConfig {
@Bean
public Executor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
executor.setMaxPoolSize(50);
executor.setQueueCapacity(100);
executor.setThreadNamePrefix("Async-");
executor.initialize();
return executor;
}
}
1.3 数据库连接池优化
-
使用 HikariCP:
spring.datasource.hikari.maximum-pool-size=20
spring.datasource.hikari.minimum-idle=5
spring.datasource.hikari.idle-timeout=30000
spring.datasource.hikari.connection-timeout=20000
spring.datasource.hikari.max-lifetime=1800000
2. Vue.js 性能优化
2.1 代码分割
-
按需加载组件:
const About = () => import(/* webpackChunkName: "about" */ './views/About.vue');
2.动态导入路由:
const routes = [
{ path: '/about', component: About }
];
const router = new VueRouter({
routes
});
export default router;
2.2 懒加载
-
懒加载路由:
const routes = [
{ path: '/about', component: () => import('./views/About.vue') }
];
const router = new VueRouter({
routes
});
export default router;
2.3 响应式数据绑定优化
-
减少不必要的数据绑定:
new Vue({
el: '#app',
data: {
users: []
},
methods: {
fetchUsers() {
axios.get('/api/users').then(response => {
this.users = response.data;
});
}
},
mounted() {
this.fetchUsers();
}
});
2.使用 v-if 和 v-else 控制 DOM 渲染:
<template>
<div>
<h1>用户列表</h1>
<ul v-if="users.length > 0">
<li v-for="user in users" :key="user.id">{{ user.name }} - {{ user.email }}</li>
</ul>
<p v-else>暂无数据</p>
</div>
</template>
3. 结合使用
3.1 后端优化
-
缓存和异步处理:
@Service
public class UserService {
@Async
@Cacheable("users")
public CompletableFuture<List<User>> fetchUsersAsync() {
return CompletableFuture.supplyAsync(() -> userRepository.findAll());
}
}
3.2 前端优化
-
代码分割和懒加载:
const routes = [
{ path: '/about', component: () => import('./views/About.vue') }
];
const router = new VueRouter({
routes
});
export default router;
2.优化数据绑定:
new Vue({
el: '#app',
data: {
users: []
},
methods: {
fetchUsers() {
axios.get('/api/users').then(response => {
this.users = response.data;
});
}
},
mounted() {
this.fetchUsers();
}
});
总结
通过 Spring Boot 和 Vue.js 的性能优化技巧,可以显著提升应用的性能。这些技巧不仅适用于小型应用,也适用于大型企业级应用。希望本文能帮助你更好地理解和应用这些技术。