字符串处理篇
1. 字符串拼接优化
String result = "";
for (int i = 0; i < 100; i++) {
result += i;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 100; i++) {
sb.append(i);
}
String result = sb.toString();
2. 字符串分割优化
String[] parts = str.split("\\.");
String[] parts = StringUtils.split(str, ".");
3. 字符串常量判断
if (str.equals("hello"))
if ("hello".equals(str))
4. 字符串长度判断
if (str != null && str.length() > 0)
if (StringUtils.isNotEmpty(str))
集合操作篇
5. 集合容量预设
List<String> list = new ArrayList<>();
List<String> list = new ArrayList<>(initialCapacity);
6. 集合遍历
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
for (String item : list) {
System.out.println(item);
}
list.forEach(System.out::println);
7. Map遍历
for (String key : map.keySet()) {
System.out.println(key + ":" + map.get(key));
}
map.forEach((key, value) ->
System.out.println(key + ":" + value));
8. 集合判空
if (list != null && list.size() > 0)
if (!CollectionUtils.isEmpty(list))
流式处理篇
9. 列表过滤
List<Integer> evenNumbers = new ArrayList<>();
for (Integer num : numbers) {
if (num % 2 == 0) {
evenNumbers.add(num);
}
}
List<Integer> evenNumbers = numbers.stream()
.filter(num -> num % 2 == 0)
.collect(Collectors.toList());
10. 数据转换
List<String> names = new ArrayList<>();
for (User user : users) {
names.add(user.getName());
}
List<String> names = users.stream()
.map(User::getName)
.collect(Collectors.toList());
异常处理篇
11. 资源关闭处理
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
}
}
}
try (FileInputStream fis = new FileInputStream(file)) {
}
12. 异常日志记录
try {
} catch (Exception e) {
e.printStackTrace();
}
try {
} catch (Exception e) {
log.error("操作失败: {}", e.getMessage(), e);
}
并发处理篇
13. 线程池创建
ExecutorService executor = Executors.newFixedThreadPool(10);
ThreadPoolExecutor executor = new ThreadPoolExecutor(
5,
10,
60L,
TimeUnit.SECONDS,
new LinkedBlockingQueue<>(100),
new ThreadPoolExecutor.CallerRunsPolicy()
);
14. 并发集合使用
Map<String, Object> map = new HashMap<>();
Map<String, Object> map = new ConcurrentHashMap<>();
日期处理篇
15. 日期比较
Date date1 = new Date();
Date date2 = new Date();
if (date1.getTime() < date2.getTime())
LocalDateTime dt1 = LocalDateTime.now();
LocalDateTime dt2 = LocalDateTime.now();
if (dt1.isBefore(dt2))
16. 日期格式化
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String date = sdf.format(new Date());
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String date = LocalDate.now().format(formatter);
性能优化篇
17. 批量处理
for (Order order : orders) {
orderMapper.insert(order);
}
orderMapper.batchInsert(orders);
18. 延迟加载
@OneToMany(fetch = FetchType.EAGER)
private List<Order> orders;
@OneToMany(fetch = FetchType.LAZY)
private List<Order> orders;
代码可读性篇
19. 枚举替代常量
public static final int STATUS_PENDING = 0;
public static final int STATUS_APPROVED = 1;
public static final int STATUS_REJECTED = 2;
public enum OrderStatus {
PENDING, APPROVED, REJECTED
}
20. Optional使用
User user = getUser();
if (user != null) {
Address address = user.getAddress();
if (address != null) {
String city = address.getCity();
if (city != null) {
return city.toUpperCase();
}
}
}
return "UNKNOWN";
return Optional.ofNullable(getUser())
.map(User::getAddress)
.map(Address::getCity)
.map(String::toUpperCase)
.orElse("UNKNOWN");
21. 文件拷贝优化
byte[] buffer = new byte[1024];
try (FileInputStream fis = new FileInputStream(source);
FileOutputStream fos = new FileOutputStream(target)) {
int len;
while ((len = fis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
}
Files.copy(source.toPath(), target.toPath(),
StandardCopyOption.REPLACE_EXISTING);
22. 文件读取优化
BufferedReader reader = new BufferedReader(new FileReader(file));
StringBuilder content = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
content.append(line).append("\n");
}
String content = Files.readString(Path.of("file.txt"));
List<String> lines = Files.readAllLines(Path.of("file.txt"));
23. 文件写入优化
try (FileWriter writer = new FileWriter(file)) {
writer.write(content);
}
Files.writeString(Path.of("file.txt"), content,
StandardCharsets.UTF_8);
反射使用篇
24. 反射缓存优化
Method method = obj.getClass().getDeclaredMethod("methodName");
method.invoke(obj);
public class MethodCache {
private static final Map<Class<?>, Method> cache =
new ConcurrentHashMap<>();
public static Method getMethod(Class<?> clazz, String name) {
return cache.computeIfAbsent(clazz.getName() + "." + name,
k -> {
try {
return clazz.getDeclaredMethod(name);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
});
}
}
25. 反射访问优化
field.setAccessible(true);
field.set(obj, value);
private static final MethodHandles.Lookup lookup =
MethodHandles.lookup();
public static void setValue(Object obj, String fieldName,
Object value) throws Throwable {
Class<?> clazz = obj.getClass();
Field field = clazz.getDeclaredField(fieldName);
MethodHandle setter = lookup.unreflectSetter(field);
setter.invoke(obj, value);
}
序列化优化篇
26. JSON序列化优化
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(obj);
@Component
public class JsonUtils {
private static final ObjectMapper MAPPER = new ObjectMapper();
static {
MAPPER.setSerializationInclusion(Include.NON_NULL);
MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
public static String toJson(Object obj) {
try {
return MAPPER.writeValueAsString(obj);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
}
27. 自定义序列化
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private transient String password;
private void writeObject(ObjectOutputStream out)
throws IOException {
out.defaultWriteObject();
}
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException {
in.defaultReadObject();
}
}
数据库操作篇
28. 批量插入优化
for (User user : users) {
jdbcTemplate.update("INSERT INTO user VALUES(?, ?)",
user.getId(), user.getName());
}
jdbcTemplate.batchUpdate("INSERT INTO user VALUES(?, ?)",
new BatchPreparedStatementSetter() {
@Override
public void setValues(PreparedStatement ps, int i)
throws SQLException {
ps.setLong(1, users.get(i).getId());
ps.setString(2, users.get(i).getName());
}
@Override
public int getBatchSize() {
return users.size();
}
});
29. 分页查询优化
String sql = "SELECT * FROM user LIMIT " + offset + "," + limit;
@Query(value = "SELECT * FROM user WHERE id > :lastId " +
"ORDER BY id LIMIT :limit", nativeQuery = true)
List<User> findByIdGreaterThan(
@Param("lastId") Long lastId,
@Param("limit") int limit);
30. 索引优化
@Query("SELECT u FROM User u WHERE u.email = ?1 OR u.phone = ?2")
User findByEmailOrPhone(String email, String phone);
@Query("SELECT u FROM User u WHERE u.email = ?1 " +
"UNION ALL " +
"SELECT u FROM User u WHERE u.phone = ?2")
User findByEmailOrPhone(String email, String phone);
缓存使用篇
31. 多级缓存实现
@Service
public class UserService {
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private CaffeineCacheManager localCache;
public User getUser(Long id) {
User user = localCache.get(id);
if (user != null) {
return user;
}
user = redisTemplate.opsForValue().get(id);
if (user != null) {
localCache.put(id, user);
return user;
}
user = userMapper.selectById(id);
if (user != null) {
redisTemplate.opsForValue().set(id, user);
localCache.put(id, user);
}
return user;
}
}
32. 缓存穿透处理
@Service
public class CacheService {
private static final String EMPTY_VALUE = "EMPTY";
public String getValue(String key) {
String value = redisTemplate.opsForValue().get(key);
if (EMPTY_VALUE.equals(value)) {
return null;
}
if (value != null) {
return value;
}
value = db.getValue(key);
if (value == null) {
redisTemplate.opsForValue().set(key, EMPTY_VALUE,
5, TimeUnit.MINUTES);
return null;
}
redisTemplate.opsForValue().set(key, value);
return value;
}
}
多线程优化篇
33. 线程安全集合
List<String> list = new ArrayList<>();
list.add("item");
List<String> list = Collections.synchronizedList(new ArrayList<>());
List<String> list = new CopyOnWriteArrayList<>();
34. 原子操作优化
private int count;
public void increment() {
count++;
}
private AtomicInteger count = new AtomicInteger();
public void increment() {
count.incrementAndGet();
}
35. 线程池监控
public class MonitoredThreadPool extends ThreadPoolExecutor {
private final AtomicInteger totalTasks = new AtomicInteger();
private final AtomicInteger completedTasks = new AtomicInteger();
@Override
protected void beforeExecute(Thread t, Runnable r) {
totalTasks.incrementAndGet();
}
@Override
protected void afterExecute(Runnable r, Throwable t) {
completedTasks.incrementAndGet();
if (t != null) {
log.error("Task execution failed", t);
}
}
}
JSON处理优化篇
36. Jackson配置优化
@Configuration
public class JacksonConfig {
@Bean
public ObjectMapper objectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL);
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.registerModule(new JavaTimeModule());
return mapper;
}
}
37. JSON解析性能优化
public class JsonParser {
private static final TypeReference<Map<String, Object>> MAP_TYPE =
new TypeReference<>() {};
private static final TypeReference<List<String>> LIST_TYPE =
new TypeReference<>() {};
public static Map<String, Object> parseMap(String json) {
return MAPPER.readValue(json, MAP_TYPE);
}
public static List<String> parseList(String json) {
return MAPPER.readValue(json, LIST_TYPE);
}
}
网络编程优化篇
38. HTTP客户端优化
for (String url : urls) {
HttpURLConnection conn =
(HttpURLConnection) new URL(url).openConnection();
conn.disconnect();
}
public class HttpClient {
private static final OkHttpClient CLIENT = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.connectionPool(new ConnectionPool(50, 5, TimeUnit.MINUTES))
.build();
public static String get(String url) throws IOException {
Request request = new Request.Builder().url(url).build();
try (Response response = CLIENT.newCall(request).execute()) {
return response.body().string();
}
}
}
39. WebSocket优化
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
@ServerEndpoint("/websocket/{userId}")
@Component
public class WebSocketServer {
private static final Map<String, Session> SESSIONS =
new ConcurrentHashMap<>();
@OnOpen
public void onOpen(Session session, @PathParam("userId") String userId) {
SESSIONS.put(userId, session);
}
@OnClose
public void onClose(@PathParam("userId") String userId) {
SESSIONS.remove(userId);
}
public static void broadcast(String message) {
SESSIONS.values().forEach(session -> {
session.getAsyncRemote().sendText(message);
});
}
}
设计模式应用篇
40. 单例模式优化
public class Singleton {
private static Singleton instance;
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
public class Singleton {
private Singleton() {}
private static class Holder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return Holder.INSTANCE;
}
}
41. 建造者模式优化
@Builder
@Data
public class User {
private Long id;
private String name;
private String email;
private LocalDateTime createTime;
}
User user = User.builder()
.id(1L)
.name("John")
.email("john@example.com")
.createTime(LocalDateTime.now())
.build();
测试相关篇
42. 单元测试优化
@SpringBootTest
public class UserServiceTest {
@MockBean
private UserRepository userRepository;
@Autowired
private UserService userService;
@Test
public void testCreateUser() {
User user = User.builder()
.name("Test")
.email("test@example.com")
.build();
when(userRepository.save(any(User.class)))
.thenReturn(user);
User result = userService.createUser(user);
assertThat(result).isNotNull();
assertThat(result.getName()).isEqualTo("Test");
verify(userRepository, times(1)).save(any(User.class));
}
}
43. 性能测试优化
public class PerformanceTest {
@Test
public void testConcurrentAccess() {
int threadCount = 100;
int requestsPerThread = 1000;
CountDownLatch latch = new CountDownLatch(threadCount);
AtomicInteger successCount = new AtomicInteger();
ExecutorService executor = Executors.newFixedThreadPool(threadCount);
long startTime = System.currentTimeMillis();
for (int i = 0; i < threadCount; i++) {
executor.submit(() -> {
try {
for (int j = 0; j < requestsPerThread; j++) {
if (performOperation()) {
successCount.incrementAndGet();
}
}
} finally {
latch.countDown();
}
});
}
latch.await();
long endTime = System.currentTimeMillis();
long duration = endTime - startTime;
double tps = (threadCount * requestsPerThread * 1000.0) / duration;
System.out.println("总请求数: " + (threadCount * requestsPerThread));
System.out.println("成功请求数: " + successCount.get());
System.out.println("执行时间: " + duration + "ms");
System.out.println("TPS: " + tps);
}
}
44. 接口测试优化
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class UserControllerTest {
@Autowired
private TestRestTemplate restTemplate;
@Test
public void testCreateUser() {
UserDTO userDTO = new UserDTO("Test", "test@example.com");
ResponseEntity<User> response = restTemplate.postForEntity(
"/api/users", userDTO, User.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(response.getBody()).isNotNull();
assertThat(response.getBody().getName()).isEqualTo("Test");
}
}
45. 测试数据生成优化
public class TestDataGenerator {
private static final Faker FAKER = new Faker();
public static User generateUser() {
return User.builder()
.name(FAKER.name().fullName())
.email(FAKER.internet().emailAddress())
.phone(FAKER.phoneNumber().cellPhone())
.address(generateAddress())
.createTime(LocalDateTime.now())
.build();
}
public static Address generateAddress() {
return Address.builder()
.street(FAKER.address().streetAddress())
.city(FAKER.address().city())
.state(FAKER.address().state())
.zipCode(FAKER.address().zipCode())
.build();
}
}
代码质量优化篇
46. 异常处理优化
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(BusinessException.class)
public ResponseEntity<ErrorResponse> handleBusinessException(
BusinessException ex) {
ErrorResponse error = new ErrorResponse(
ex.getCode(), ex.getMessage());
return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResponse> handleException(Exception ex) {
ErrorResponse error = new ErrorResponse(
"SYSTEM_ERROR", "系统异常");
log.error("Unexpected error", ex);
return new ResponseEntity<>(error,
HttpStatus.INTERNAL_SERVER_ERROR);
}
}
47. 参数校验优化
@Data
public class UserDTO {
@NotBlank(message = "用户名不能为空")
@Length(min = 2, max = 20, message = "用户名长度必须在2-20之间")
private String name;
@NotBlank(message = "邮箱不能为空")
@Email(message = "邮箱格式不正确")
private String email;
@Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确")
private String phone;
}
@RestController
public class UserController {
@PostMapping("/users")
public User createUser(@Valid @RequestBody UserDTO userDTO) {
return userService.createUser(userDTO);
}
}
48. 日志记录优化
@Aspect
@Component
public class LogAspect {
@Around("@annotation(LogOperation)")
public Object around(ProceedingJoinPoint point) throws Throwable {
long beginTime = System.currentTimeMillis();
String methodName = point.getSignature().getName();
Object[] args = point.getArgs();
try {
Object result = point.proceed();
long time = System.currentTimeMillis() - beginTime;
log.info("Method: {}, Args: {}, Result: {}, Time: {}ms",
methodName, args, result, time);
return result;
} catch (Exception e) {
log.error("Method: {}, Args: {}, Error: {}",
methodName, args, e.getMessage(), e);
throw e;
}
}
}
49. 接口版本控制
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ApiVersion {
int value();
}
@RestController
@RequestMapping("/api/{version}/users")
public class UserController {
@ApiVersion(1)
@GetMapping("/{id}")
public UserV1DTO getUserV1(@PathVariable Long id) {
}
@ApiVersion(2)
@GetMapping("/{id}")
public UserV2DTO getUserV2(@PathVariable Long id) {
}
}
50. 代码风格检查
public class CheckstyleConfig {
@Bean
public SourceFormatter sourceFormatter() {
SourceFormatter formatter = new SourceFormatter();
formatter.setIndentSize(4);
formatter.setLineLength(120);
formatter.setTrimTrailingWhitespace(true);
formatter.setEndWithNewline(true);
return formatter;
}
}
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>3.1.2</version>
<configuration>
<configLocation>checkstyle.xml</configLocation>
<encoding>UTF-8</encoding>
<consoleOutput>true</consoleOutput>
<failOnViolation>true</failOnViolation>
</configuration>
</plugin>