字符串处理篇

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, ".");  // Apache Commons

3. 字符串常量判断

// 不推荐
if (str.equals("hello")) // 可能抛NPE

// 推荐
if ("hello".equals(str))  // 常量写在前面

4. 字符串长度判断

// 不推荐
if (str != null && str.length() > 0)

// 推荐
if (StringUtils.isNotEmpty(str))  // 更简洁

集合操作篇

5. 集合容量预设

// 不推荐
List<String> list = new ArrayList<>();  // 默认容量10

// 推荐
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) {  // 使用forEach
    System.out.println(item);
}

// 更推荐(Java 8+)
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")); // Java 11+
// 或
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);

// 推荐
// 使用MethodHandle(性能更好)
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)
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;
        }
        
        // 查Redis缓存
        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);
        
        // 注册Java 8时间模块
        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<>() {};
    
    // 复用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. 建造者模式优化

// 使用Lombok简化建造者模式
@Builder
@Data
public class User {
    private Long id;
    private String name;
    private String email;
    private LocalDateTime createTime;
    
    // Lombok自动生成建造者代码
}

// 使用方式
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();
            
        // Mock依赖行为
        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();
        
        // 计算执行时间和TPS
        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) {
        // V1版本接口实现
    }
    
    @ApiVersion(2)
    @GetMapping("/{id}")
    public UserV2DTO getUserV2(@PathVariable Long id) {
        // V2版本接口实现
    }
}

50. 代码风格检查

// 配置checkstyle规则
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;
    }
}

// Maven插件配置
<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>