← 返回学习路线

SYSTEM

面试话术

后端实战二、面试话术blog-dev
src/content/notes/blog-dev/面试话术.md

二、面试话术

“我用 Redisson 实现了布隆过滤器,作为缓存穿透的第一道防线。项目启动时用 @PostConstruct 把所有文章 ID 加载进去,查询时先过布隆过滤器,不存在的 ID 直接返回。同时我还做了状态监控接口可以随时查看当前元素数和误判率,以及手动重建接口——因为布隆过滤器的容量是初始化时定死的,如果文章数量接近上限,可以重建扩容。第二道防线是空值缓存,两层防护基本杜绝了缓存穿透。

旧优化

1.Repository层:自定义 @Query JPQL + Pageable

@Query("SELECT a FROM Article a WHERE a.categoryId = :cid AND (a.title LIKE :kw OR a.content LIKE :kw)")
Page<Article> searchByCategoryAndKeyword(@Param("cid") String cid,
                                         @Param("kw") String kw,
                                         Pageable pageable);

重点:

  1. JPQL 不要手写 ORDER BY(你当前代码写死了ORDER BY createTime DESC,属于瑕疵!)
  2. 不要写 LIMIT
  3. 排序交给 Pageable 控制;JPA 根据 Pageable 自动拼接排序 + LIMIT

❌ 不推荐(写死排序,失去灵活性)

@Query("SELECT a FROM Article a ... ORDER BY a.createTime DESC")

2.统一返回结果

改动项 优化前 优化后 价值
无参 success ❌ ✅ success() 删除/更新操作不需要返回数据时更简洁
带 code 的 error ❌ ✅ error(Integer code, String message) Security 鉴权失败返回 401,业务异常返回自定义业务码
成功消息文案 “成功” “操作成功” 更通用,适用于增删改查所有场景

问:项目的统一返回结果怎么设计的?

“我设计了泛型 Result 类,提供 success() 和 error() 静态工厂方法。 success() 支持带数据和不带数据两种重载, error() 支持默认 500 和自定义状态码两种重载。这样无论是正常业务、业务异常还是 Security 鉴权失败,都能用同一套格式返回,前端统一处理。”

3.去掉 Bearer 前缀

在 JwtAuthenticationFilter.java 取到 token 后,去掉 Bearer 前缀;加个 trim() 防止前后空格:

String token = request.getHeader("Authorization");

// 新增:去掉 Bearer 前缀(如果有)
if (token != null && token.startsWith("Bearer ")) {
    token = token.substring(7).trim();
}

// 后面逻辑不变
if (token == null || token.isEmpty()) {
    filterChain.doFilter(request, response);
    return;
}

这样改完后:

  • 前端发纯 token → startsWith("Bearer ") 为 false → token 不变 → 正常工作
  • Postman 发 Bearer xxx → 去掉前缀 → 正常工作

4.加日志依赖(推荐,符合企业规范)

pom.xml 加(Spring Boot 一般自动带了,确认一下就行):

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-logging</artifactId>
</dependency>

5.SecurityConfig.java

把字段注入改成构造器注入,更符合企业规范:

private final JwtAuthenticationFilter jwtAuthenticationFilter;
private final SecurityAuthenticationEntryPoint authenticationEntryPoint;

public SecurityConfig(JwtAuthenticationFilter jwtAuthenticationFilter,
                      SecurityAuthenticationEntryPoint authenticationEntryPoint) {
    this.jwtAuthenticationFilter = jwtAuthenticationFilter;
    this.authenticationEntryPoint = authenticationEntryPoint;
}