MST

星途 面试题库

面试题:Java之Spring Boot性能调优 - 缓存配置

在Spring Boot项目中,如何配置和使用缓存来提高性能?请以常用的缓存框架(如Ehcache或Redis)为例,说明配置步骤和关键代码。
20.4万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试

使用Ehcache作为缓存框架

  1. 添加依赖:在pom.xml文件中添加Ehcache相关依赖。
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
    <groupId>org.ehcache</groupId>
    <artifactId>ehcache</artifactId>
</dependency>
  1. 配置缓存:在application.properties文件中配置Ehcache。
spring.cache.type=EHCAHE
spring.cache.cache-names=defaultCache
  1. 创建Ehcache配置文件:在resources目录下创建ehcache.xml文件,定义缓存策略。
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
    <cache name="defaultCache"
           maxEntriesLocalHeap="1000"
           eternal="false"
           timeToIdleSeconds="300"
           timeToLiveSeconds="600"
           diskSpoolBufferSizeMB="30"
           maxEntriesLocalDisk="10000000"
           diskPersistent="false"
           diskExpiryThreadIntervalSeconds="120"
           memoryStoreEvictionPolicy="LRU">
    </cache>
</ehcache>
  1. 启用缓存:在Spring Boot主类上添加@EnableCaching注解。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@EnableCaching
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
  1. 使用缓存:在需要缓存的方法上添加@Cacheable注解。
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class ExampleService {

    @Cacheable("defaultCache")
    public String getExampleData() {
        // 这里是实际获取数据的逻辑,比如从数据库查询
        return "example data";
    }
}

使用Redis作为缓存框架

  1. 添加依赖:在pom.xml文件中添加Redis相关依赖。
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
  1. 配置Redis:在application.properties文件中配置Redis连接信息。
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=
spring.cache.type=REDIS
spring.cache.cache-names=defaultCache
  1. 启用缓存:在Spring Boot主类上添加@EnableCaching注解。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@EnableCaching
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
  1. 配置Redis缓存管理器:创建一个配置类来配置Redis缓存管理器。
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;

import java.time.Duration;

@Configuration
@EnableCaching
public class RedisConfig {

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
               .entryTtl(Duration.ofMinutes(10))
               .disableCachingNullValues()
               .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));

        return RedisCacheManager.builder(redisConnectionFactory)
               .cacheDefaults(cacheConfiguration)
               .build();
    }
}
  1. 使用缓存:在需要缓存的方法上添加@Cacheable注解。
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class ExampleService {

    @Cacheable("defaultCache")
    public String getExampleData() {
        // 这里是实际获取数据的逻辑,比如从数据库查询
        return "example data";
    }
}