MST

星途 面试题库

面试题:Java的Spring Boot构建RESTful API的性能优化与安全加固

假设你已经使用Spring Boot构建了一个高并发的RESTful API,现在需要对其进行性能优化和安全加固。从性能方面,谈谈如何进行缓存设计(如使用Redis),以及如何优化数据库查询;从安全角度,阐述如何防止常见的Web攻击(如SQL注入、XSS攻击),并结合Spring Security进行身份认证和授权的高级配置,给出整体的优化与加固思路及关键配置代码。
46.4万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试

性能优化

  1. 缓存设计(使用Redis)
    • 引入依赖:在pom.xml中添加Redis依赖。
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
- **配置Redis**:在`application.properties`中配置Redis连接信息。
spring.redis.host=localhost
spring.redis.port=6379
- **使用缓存**:在Service层方法上使用`@Cacheable`注解。例如:
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class UserService {

    @Cacheable("users")
    public List<User> getAllUsers() {
        // 数据库查询逻辑
    }
}
  1. 优化数据库查询
    • 使用索引:对频繁查询的字段添加索引。例如,在MySQL中:
CREATE INDEX idx_username ON users(username);
- **分页查询**:避免一次性加载大量数据。在Spring Data JPA中:
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User, Long> {
    Page<User> findAll(Pageable pageable);
}

// 使用
Pageable pageable = PageRequest.of(0, 10);
Page<User> users = userRepository.findAll(pageable);

安全加固

  1. 防止SQL注入
    • 使用参数化查询:在Spring JDBC中,使用NamedParameterJdbcTemplate
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class UserRepository {

    @Autowired
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    public User getUserById(Long id) {
        String sql = "SELECT * FROM users WHERE id = :id";
        SqlParameterSource namedParameters = new MapSqlParameterSource("id", id);
        return namedParameterJdbcTemplate.queryForObject(sql, namedParameters, new UserRowMapper());
    }
}
  1. 防止XSS攻击
    • 对输出进行编码:在Spring MVC中,可以使用HttpMessageConverter对响应数据进行编码。例如,在配置类中:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.charset.StandardCharsets;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Bean
    public StringHttpMessageConverter stringHttpMessageConverter() {
        StringHttpMessageConverter converter = new StringHttpMessageConverter(StandardCharsets.UTF_8);
        converter.setWriteAcceptCharset(false);
        return converter;
    }
}
  1. Spring Security身份认证和授权高级配置
    • 引入依赖:在pom.xml中添加Spring Security依赖。
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
- **配置类**:创建一个配置类继承`WebSecurityConfigurerAdapter`。
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
           .authorizeRequests()
               .antMatchers("/public/**").permitAll()
               .anyRequest().authenticated()
               .and()
           .formLogin()
               .loginPage("/login")
               .permitAll()
               .and()
           .logout()
               .permitAll();
    }

    @Bean
    @Override
    public UserDetailsService userDetailsService() {
        UserDetails user =
            User.withDefaultPasswordEncoder()
               .username("user")
               .password("password")
               .roles("USER")
               .build();

        UserDetails admin =
            User.withDefaultPasswordEncoder()
               .username("admin")
               .password("admin")
               .roles("ADMIN")
               .build();

        return new InMemoryUserDetailsManager(user, admin);
    }
}

整体思路是先从性能角度优化缓存和数据库查询,减少响应时间和资源消耗;再从安全角度防止常见Web攻击,并利用Spring Security进行身份认证和授权,确保API的安全性。关键配置代码如上述所示,根据实际业务场景可能需要进一步调整。