高级java每日一道面试题-2027年6月07日-基础篇[JCache(JSR-107)]-在 Java EE 或 Spring Boot 环境中,如何集成和启用 JCache? - getCacheNames()) {

📅 2026-11-30 👤 拼多多助力营销技巧 📂 拼多多助力神器 👁️ 527 次阅读

Java EE 和 Spring Boot 中集成 JCache 的完整指南

我将从基础到高级,详细讲解在两种环境中集成 JCache 的全过程。

1. Java EE 环境中集成 JCache

1.1 Maven 依赖配置

javax

javaee-api

8.0

provided

javax.cache

cache-api

1.1.1

org.ehcache

ehcache

3.10.8

com.hazelcast

hazelcast

5.3.0

com.hazelcast

hazelcast-jcache

5.3.0

org.infinispan

infinispan-cachestore-jdbc

14.0.0.Final

org.infinispan

infinispan-jcache

14.0.0.Final

javax.enterprise

cdi-api

2.0

provided

1.2 Java EE XML 配置文件

xmlns="http://www.ehcache.org/v3"

xmlns:jsr107="http://www.ehcache.org/v3/jsr107"

xsi:schemaLocation="

http://www.ehcache.org/v3 https://www.ehcache.org/schema/ehcache-core-3.0.xsd

http://www.ehcache.org/v3/jsr107 https://www.ehcache.org/schema/ehcache-107-ext-3.0.xsd">

java.lang.String

com.example.User

30

1000

50

1.3 Java EE 配置类

import javax.cache.Cache;

import javax.cache.CacheManager;

import javax.cache.Caching;

import javax.cache.configuration.MutableConfiguration;

import javax.cache.expiry.CreatedExpiryPolicy;

import javax.cache.expiry.Duration;

import javax.cache.spi.CachingProvider;

import javax.enterprise.context.ApplicationScoped;

import javax.enterprise.inject.Produces;

import javax.inject.Inject;

import java.net.URI;

import java.util.concurrent.TimeUnit;

/**

* Java EE JCache 配置类

*/

@ApplicationScoped

public class JCacheConfiguration {

private static final String CACHE_CONFIG_XML = "/WEB-INF/ehcache.xml";

/**

* 生产 CacheManager(CDI Producer)

*/

@Produces

@ApplicationScoped

public CacheManager createCacheManager() {

try {

CachingProvider cachingProvider = Caching.getCachingProvider();

// 从 webapp 目录加载配置

URI configUri = getClass()

.getClassLoader()

.getResource(CACHE_CONFIG_XML)

.toURI();

return cachingProvider.getCacheManager(

configUri,

getClass().getClassLoader()

);

} catch (Exception e) {

throw new RuntimeException("无法创建 CacheManager", e);

}

}

/**

* 生产 User Cache(CDI Producer)

*/

@Produces

@ApplicationScoped

@Named("userCache")

public CachecreateUserCache(CacheManager cacheManager) {

// 如果配置文件中已定义,直接获取 拼多多帮助力入口

Cachecache = cacheManager.getCache("userCache", String.class, User.class);

if (cache == null) {

// 动态创建缓存

MutableConfigurationconfig = new MutableConfiguration<>();

config.setTypes(String.class, User.class)

.setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(

new Duration(TimeUnit.MINUTES, 30)))

.setStatisticsEnabled(true)

.setManagementEnabled(true);

cache = cacheManager.createCache("userCache", config);

}

return cache;

}

/**

* 生产 Product Cache

*/

@Produces

@ApplicationScoped

@Named("productCache")

public CachecreateProductCache(CacheManager cacheManager) {

return cacheManager.createCache("productCache",

new MutableConfiguration()

.setTypes(Long.class, Product.class)

.setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(

new Duration(TimeUnit.HOURS, 1)))

.setStoreByValue(false) // 存储引用,提高性能

.setStatisticsEnabled(true));

}

}

1.4 EJB 中使用 JCache

import javax.cache.Cache;

import javax.ejb.Stateless;

import javax.inject.Inject;

import javax.inject.Named;

/**

* EJB 中使用 JCache 的示例

*/

@Stateless

public class UserService {

@Inject

@Named("userCache")

private CacheuserCache;

@Inject

private CacheManager cacheManager;

/**

* 查找用户(带缓存)

*/

public User findUserById(String userId) {

// 1. 首先尝试从缓存获取

User cachedUser = userCache.get(userId);

if (cachedUser != null) {

return cachedUser;

}

// 2. 缓存未命中,从数据库查询

User user = userRepository.findById(userId);

if (user != null) {

// 3. 放入缓存

userCache.put(userId, user);

}

return user;

}

/**

* 更新用户(更新缓存)

*/

@TransactionAttribute(TransactionAttributeType.REQUIRED)

public User updateUser(User user) {

// 1. 更新数据库

User updatedUser = userRepository.update(user);

// 2. 更新缓存

userCache.put(user.getId(), updatedUser);

return updatedUser;

}

/**

* 删除用户(清除缓存)

*/

@TransactionAttribute(TransactionAttributeType.REQUIRED)

public void deleteUser(String userId) {

// 1. 删除数据库记录

userRepository.delete(userId);

// 2. 从缓存中移除

userCache.remove(userId);

}

/**

* 批量操作使用 EntryProcessor

*/

public void bulkUpdateUserStatus(ListuserIds, String newStatus) {

for (String userId : userIds) {

userCache.invoke(userId, (entry, args) ->{

User user = entry.getValue();

if (user != null) {

user.setStatus(newStatus);

entry.setValue(user);

}

return null;

});

}

}

/**

* 获取缓存统计信息

*/

public CacheStatistics getCacheStatistics() {

// 获取底层实现以访问统计信息

if (userCache instanceof javax.cache.CacheMXBean) {

javax.cache.CacheMXBean mxBean = (javax.cache.CacheMXBean) userCache;

// 访问统计信息

}

// 或者通过 JMX 访问

return new CacheStatistics(

userCache.iterator().getSize(),

getHitRate(),

getMissRate()

);

}

}

1.5 Servlet 中使用 JCache

import javax.cache.Cache;

import javax.inject.Inject;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import java.io.IOException;

/**

* Servlet 中使用 JCache

*/

@WebServlet("/users/*")

public class UserServlet extends HttpServlet {

@Inject

@Named("userCache")

private CacheuserCache;

@Inject

private UserService userService;

@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

String userId = extractUserId(req);

// 使用带缓存的服务

User user = userService.findUserById(userId);

if (user != null) {

resp.setContentType("application/json");

resp.getWriter().write(toJson(user));

} else {

resp.sendError(HttpServletResponse.SC_NOT_FOUND);

}

}

@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

User user = parseUserFromRequest(req);

// 更新用户(自动更新缓存)

User updated = userService.updateUser(user);

resp.setContentType("application/json");

resp.setStatus(HttpServletResponse.SC_CREATED);

resp.getWriter().write(toJson(updated));

}

/**

* 监控端点:显示缓存统计

*/

@WebServlet("/cache/stats")

public static class CacheStatsServlet extends HttpServlet {

@Inject

private CacheManager cacheManager;

@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

resp.setContentType("application/json");

JsonObject stats = Json.createObjectBuilder();

for (String cacheName : cacheManager.getCacheNames()) {

Cache cache = cacheManager.getCache(cacheName);

if (cache != null) {

// 获取统计信息

stats.add(cacheName, getCacheStats(cache));

}

}

resp.getWriter().write(stats.toString());

}

}

}

2. Spring Boot 环境中集成 JCache

2.1 Spring Boot Maven 依赖

org.springframework.boot

spring-boot-starter-parent

2.7.0

org.springframework.boot

spring-boot-starter-cache

org.springframework.boot

spring-boot-starter-web

javax.cache

cache-api

org.ehcache

ehcache

3.10.8

jakarta

com.github.ben-manes.caffeine

caffeine

3.1.5

com.github.ben-manes.caffeine

jcache

3.1.5

org.springframework.boot

spring-boot-starter-data-redis

org.redisson

redisson

3.18.0

org.springframework.boot

spring-boot-starter-actuator

2.2 Spring Boot 配置文件

# application.yml

spring:

cache:

# 指定使用 JCache

type: jcache

jcache:

# 配置文件位置

config: classpath:ehcache.xml

# 或直接使用 provider

provider: org.ehcache.jsr107.EhcacheCachingProvider

# 缓存名称列表

cache-names:

- userCache

- productCache

- orderCache

# Caffeine 特定配置(如果使用 Caffeine)

caffeine:

spec: maximumSize=10000,expireAfterWrite=600s

# Redis 配置(如果使用 Redis)

redis:

host: localhost

port: 6379

password:

timeout: 2000ms

lettuce:

pool:

max-active: 8

max-idle: 8

min-idle: 0

# Ehcache 配置

ehcache:

config: classpath:ehcache.xml

# 启用缓存统计和管理端点

management:

endpoints:

web:

exposure:

include: health,info,metrics,caches

endpoint:

caches:

enabled: true

metrics:

enabled: true

2.3 Spring Boot 配置类

import org.springframework.boot.autoconfigure.cache.JCacheManagerCustomizer;

import org.springframework.cache.annotation.EnableCaching;

import org.springframework.cache.interceptor.KeyGenerator;

import org.springframework.cache.jcache.JCacheCacheManager;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.context.annotation.Primary;

import javax.cache.CacheManager;

import javax.cache.Caching;

import javax.cache.configuration.MutableConfiguration;

import javax.cache.expiry.CreatedExpiryPolicy;

import javax.cache.expiry.Duration;

import java.lang.reflect.Method;

import java.util.concurrent.TimeUnit;

/**

* Spring Boot JCache 配置

*/

@Configuration

@EnableCaching // 启用 Spring 缓存注解支持

public class JCacheConfig {

/**

* 自定义 KeyGenerator

* 用于生成缓存键

*/

@Bean

public KeyGenerator customKeyGenerator() {

return new KeyGenerator() {

@Override

public Object generate(Object target, Method method, Object... params) {

StringBuilder key = new StringBuilder();

key.append(target.getClass().getSimpleName());

key.append(".");

key.append(method.getName());

key.append(":");

for (Object param : params) {

if (param != null) {

key.append(param.toString());

key.append(",");

}

}

return key.toString();

}

};

}

/**

* 创建 JCache CacheManager

*/

@Bean

@Primary

public CacheManager jCacheManager() {

// 使用默认的 CachingProvider

javax.cache.CacheManager cacheManager =

Caching.getCachingProvider().getCacheManager();

// 如果使用外部配置,Spring Boot 会自动配置

// 这里可以进行自定义配置

return cacheManager;

}

/**

* 包装为 Spring 的 CacheManager

*/

@Bean

public org.springframework.cache.CacheManager cacheManager(

javax.cache.CacheManager jCacheManager) {

return new JCacheCacheManager(jCacheManager);

}

/**

* JCache 管理器自定义配置

* 可以动态创建和配置缓存

*/

@Bean

public JCacheManagerCustomizer cacheManagerCustomizer() {

return cm ->{

// 配置 userCache

cm.createCache("userCache",

new MutableConfiguration<>()

.setTypes(String.class, User.class)

.setExpiryPolicyFactory(

CreatedExpiryPolicy.factoryOf(

new Duration(TimeUnit.MINUTES, 30)))

.setStatisticsEnabled(true)

.setManagementEnabled(true));

// 配置 productCache

cm.createCache("productCache",

new MutableConfiguration<>()

.setTypes(Long.class, Product.class)

.setExpiryPolicyFactory(

CreatedExpiryPolicy.factoryOf(

new Duration(TimeUnit.HOURS, 2)))

.setStoreByValue(false));

// 配置带有监听器的缓存

cm.createCache("auditCache",

new MutableConfiguration<>()

.setTypes(String.class, AuditLog.class)

.addCacheEntryListenerConfiguration(

new SimpleEntryListenerConfiguration<>(

new AuditCacheListener(),

true, // 是否旧值

true, // 是否新值

true // 是否异步

)));

};

}

/**

* 条件化配置:开发环境使用 Caffeine,生产环境使用 Redis

*/

@Configuration

@ConditionalOnProperty(name = "spring.cache.type", havingValue = "caffeine")

static class CaffeineCacheConfig {

@Bean

public CaffeineCacheManager caffeineCacheManager() {

CaffeineCacheManager cacheManager = new CaffeineCacheManager();

cacheManager.setCaffeine(Caffeine.newBuilder()

.maximumSize(10000)

.expireAfterWrite(10, TimeUnit.MINUTES)

.recordStats());

return cacheManager;

}

}

@Configuration

@ConditionalOnProperty(name = "spring.cache.type", havingValue = "redis")

static class RedisCacheConfig {

@Bean

public RedisCacheManager redisCacheManager(RedisConnectionFactory connectionFactory) {

RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()

.entryTtl(Duration.ofMinutes(30))

.serializeKeysWith(RedisSerializationContext.SerializationPair

.fromSerializer(new StringRedisSerializer()))

.serializeValuesWith(RedisSerializationContext.SerializationPair

.fromSerializer(new GenericJackson2JsonRedisSerializer()));

return RedisCacheManager.builder(connectionFactory)

.cacheDefaults(config)

.withInitialCacheConfigurations(getCacheConfigurations())

.transactionAware()

.build();

}

private MapgetCacheConfigurations() {

MapconfigMap = new HashMap<>();

configMap.put("userCache",

RedisCacheConfiguration.defaultCacheConfig()

.entryTtl(Duration.ofMinutes(15)));

configMap.put("productCache",

RedisCacheConfiguration.defaultCacheConfig()

.entryTtl(Duration.ofHours(1)));

return configMap;

}

}

}

2.4 Spring Boot Service 中使用缓存

import org.springframework.cache.annotation.*;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**

* Spring Boot 服务层使用 JCache 注解

*/

@Service

@CacheConfig(cacheNames = "userCache") // 指定默认缓存

public class UserService {

@Autowired

private UserRepository userRepository;

/**

* @Cacheable - 方法结果缓存

* 如果缓存存在,直接返回缓存值

* 如果缓存不存在,执行方法并将结果缓存

*/

@Cacheable(

key = "#id", // SpEL 表达式

unless = "#result == null", // 结果为空时不缓存

condition = "#id.length() > 3" // 条件:id长度大于3才缓存

)

public User findById(String id) {

return userRepository.findById(id)

.orElseThrow(() ->new UserNotFoundException(id));

}

/**

* 使用自定义 KeyGenerator

*/

@Cacheable(

value = "userCache",

keyGenerator = "customKeyGenerator"

)

public User findByEmailAndStatus(String email, String status) {

return userRepository.findByEmailAndStatus(email, status);

}

/**

* @CachePut - 更新缓存

* 总是执行方法,并用结果更新缓存

*/

@CachePut(key = "#user.id")

@Transactional

public User save(User user) {

return userRepository.save(user);

}

/**

* @CacheEvict - 清除缓存

* 方法执行后清除指定缓存

*/

@CacheEvict(key = "#id")

@Transactional

public void delete(String id) {

userRepository.deleteById(id);

}

/**

* 清除所有缓存条目

*/

@CacheEvict(allEntries = true)

public void clearCache() {

// 只需要注解,不需要实现

}

/**

* @Caching - 组合多个缓存操作

*/

@Caching(

put = {

@CachePut(key = "#user.id"),

@CachePut(key = "#user.email", condition = "#user.email != null")

},

evict = {

@CacheEvict(value = "userListCache", allEntries = true)

}

)

@Transactional

public User update(User user) {

return userRepository.save(user);

}

/**

* 多层缓存配置

*/

@Cacheable(

value = {"userCache", "userStatistics"},

key = "#id"

)

public UserStatistics getUserStatistics(String id) {

// 计算用户统计信息

return calculateStatistics(id);

}

}

2.5 Spring Boot Repository 层缓存

import org.springframework.cache.annotation.Cacheable;

import org.springframework.data.jpa.repository.JpaRepository;

import org.springframework.data.jpa.repository.Query;

import org.springframework.data.repository.query.Param;

/**

* Spring Data JPA 仓库层使用缓存

*/

public interface UserRepository extends JpaRepository{

/**

* 方法名派生查询 + 缓存

*/

@Cacheable(value = "userCache", key = "#email")

OptionalfindByEmail(String email);

/**

* 自定义查询 + 缓存

*/

@Cacheable(

value = "userCache",

key = "'status:' + #status"

)

@Query("SELECT u FROM User u WHERE u.status = :status")

ListfindByStatus(@Param("status") String status);

/**

* 分页查询缓存

* 注意:分页查询缓存需要特殊处理

*/

@Cacheable(

value = "userPageCache",

key = "#pageable.pageNumber + '-' + #pageable.pageSize + '-' + #status"

)

PagefindByStatus(String status, Pageable pageable);

}

/**

* 自定义 Repository 实现

*/

@Repository

class UserRepositoryImpl implements CustomUserRepository {

@PersistenceContext

private EntityManager entityManager;

@Override

@Cacheable(value = "complexUserCache", key = "#criteria.hashCode()")

public ListfindByComplexCriteria(UserSearchCriteria criteria) {

// 复杂查询逻辑

CriteriaBuilder cb = entityManager.getCriteriaBuilder();

CriteriaQueryquery = cb.createQuery(User.class);

Rootroot = query.from(User.class);

// 构建查询条件...

return entityManager.createQuery(query).getResultList();

}

}

2.6 Spring Boot 缓存监听器

import org.springframework.cache.annotation.CacheEvict;

import org.springframework.cache.annotation.CachePut;

import org.springframework.cache.annotation.Cacheable;

import org.springframework.context.event.EventListener;

import org.springframework.scheduling.annotation.Async;

import org.springframework.stereotype.Component;

import org.springframework.transaction.event.TransactionPhase;

import org.springframework.transaction.event.TransactionalEventListener;

import javax.cache.event.*;

/**

* 缓存事件监听器

*/

@Component

public class CacheEventListener {

/**

* 监听缓存创建事件

*/

@EventListener

@Async // 异步处理

public void handleCacheCreated(CacheEntryCreatedEventevent) {

log.info("缓存创建 - Key: {}, Value: {}",

event.getKey(), event.getValue());

// 发送通知或记录审计日志

auditService.logCacheOperation("CREATE", event.getKey());

}

/**

* 监听缓存更新事件

*/

@EventListener

public void handleCacheUpdated(CacheEntryUpdatedEventevent) {

User oldValue = event.getOldValue();

User newValue = event.getValue();

log.info("缓存更新 - Key: {}, Old: {}, New: {}",

event.getKey(), oldValue, newValue);

// 触发业务逻辑

if (oldValue != null && newValue != null &&

!oldValue.getStatus().equals(newValue.getStatus())) {

statusChangeService.onUserStatusChanged(

event.getKey(), oldValue.getStatus(), newValue.getStatus());

}

}

/**

* 事务提交后清除缓存

*/

@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)

public void handleAfterCommit(UserUpdatedEvent event) {

// 事务提交后清除相关缓存

cacheManager.getCache("userCache").evict(event.getUserId());

cacheManager.getCache("userListCache").clear();

}

/**

* 自定义缓存拦截器

*/

@Component

public static class CustomCacheInterceptor extends CacheInterceptor {

@Override

protected Object execute(CacheOperationInvoker invoker,

CacheOperationContexts contexts) {

long startTime = System.currentTimeMillis();

try {

Object result = super.execute(invoker, contexts);

long duration = System.currentTimeMillis() - startTime;

// 记录缓存操作性能

metricsService.recordCacheOperation(

contexts.getOperation().getName(),

duration,

contexts.getOperation().getCacheNames()

);

return result;

} catch (CacheOperationInvoker.ThrowableWrapper e) {

// 缓存操作异常处理

cacheErrorHandler.handleCacheError(e);

throw e;

}

}

}

}

2.7 Spring Boot 缓存健康检查

import org.springframework.boot.actuate.cache.CachesEndpoint;

import org.springframework.boot.actuate.health.Health;

import org.springframework.boot.actuate.health.HealthIndicator;

import org.springframework.cache.CacheManager;

import org.springframework.stereotype.Component;

import java.util.HashMap;

import java.util.Map;

/**

* 缓存健康检查

*/

@Component

public class CacheHealthIndicator implements HealthIndicator {

@Autowired

private CacheManager cacheManager;

@Override

public Health health() {

Mapdetails = new HashMap<>();

try {

// 检查每个缓存

for (String cacheName : cacheManager.getCacheNames()) {

org.springframework.cache.Cache cache = cacheManager.getCache(cacheName);

if (cache != null) {

// 尝试简单的缓存操作来检查可用性

String testKey = "health-check-" + System.currentTimeMillis();

cache.put(testKey, "test");

Object value = cache.get(testKey);

cache.evict(testKey);

details.put(cacheName,

value != null ? "HEALTHY" : "UNHEALTHY");

} else {

details.put(cacheName, "NOT_FOUND");

}

}

return Health.up()

.withDetails(details)

.build();

} catch (Exception e) {

return Health.down(e)

.withDetails(details)

.build();

}

}

}

/**

* 缓存指标

*/

@Component

public class CacheMetrics {

@Autowired

private MeterRegistry meterRegistry;

@Autowired

private CacheManager cacheManager;

@PostConstruct

public void bindCacheMetrics() {

// 为每个缓存绑定指标

for (String cacheName : cacheManager.getCacheNames()) {

org.springframework.cache.Cache cache = cacheManager.getCache(cacheName);

if (cache.getNativeCache() instanceof com.github.benmanes.caffeine.cache.Cache) {

// Caffeine 缓存指标

bindCaffeineMetrics(cacheName,

(com.github.benmanes.caffeine.cache.Cache) cache.getNativeCache());

} else if (cache.getNativeCache() instanceof javax.cache.Cache) {

// JCache 指标

bindJCacheMetrics(cacheName,

(javax.cache.Cache) cache.getNativeCache());

}

}

}

private void bindCaffeineMetrics(String cacheName,

com.github.benmanes.caffeine.cache.Cache cache) {

CaffeineCacheStats stats = cache.stats();

Gauge.builder("cache.size", cache, c ->c.estimatedSize())

.tag("cache", cacheName)

.register(meterRegistry);

Gauge.builder("cache.hit.ratio", () ->stats.hitRate())

.tag("cache", cacheName)

.register(meterRegistry);

}

}

2.8 Spring Boot 多级缓存配置

import org.springframework.cache.Cache;

import org.springframework.cache.CacheManager;

import org.springframework.cache.support.AbstractCacheManager;

import org.springframework.cache.support.CompositeCacheManager;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.data.redis.cache.RedisCacheManager;

import org.springframework.data.redis.connection.RedisConnectionFactory;

import java.util.Arrays;

import java.util.List;

/**

* 多级缓存配置

* L1: Caffeine(本地内存,快速)

* L2: Redis(分布式,共享)

*/

@Configuration

public class MultiLevelCacheConfig {

/**

* 组合缓存管理器

*/

@Bean

public CacheManager cacheManager(

CaffeineCacheManager caffeineCacheManager,

RedisCacheManager redisCacheManager) {

CompositeCacheManager compositeCacheManager = new CompositeCacheManager();

compositeCacheManager.setCacheManagers(

Arrays.asList(caffeineCacheManager, redisCacheManager));

// 设置回退策略:先在 L1 查找,找不到再到 L2

compositeCacheManager.setFallbackToNoOpCache(false);

return new MultiLevelCacheManager(

caffeineCacheManager,

redisCacheManager);

}

/**

* 自定义多级缓存管理器

*/

static class MultiLevelCacheManager implements CacheManager {

private final CacheManager l1CacheManager; // Caffeine

private final CacheManager l2CacheManager; // Redis

public MultiLevelCacheManager(CacheManager l1, CacheManager l2) {

this.l1CacheManager = l1;

this.l2CacheManager = l2;

}

@Override

public Cache getCache(String name) {

Cache l1Cache = l1CacheManager.getCache(name);

Cache l2Cache = l2CacheManager.getCache(name);

return new MultiLevelCache(name, l1Cache, l2Cache);

}

@Override

public CollectiongetCacheNames() {

// 返回两个管理器共有的缓存名称

Setnames = new HashSet<>();

names.addAll(l1CacheManager.getCacheNames());

names.addAll(l2CacheManager.getCacheNames());

return names;

}

}

/**

* 多级缓存实现

*/

static class MultiLevelCache implements Cache {

private final String name;

private final Cache l1Cache;

private final Cache l2Cache;

public MultiLevelCache(String name, Cache l1Cache, Cache l2Cache) {

this.name = name;

this.l1Cache = l1Cache;

this.l2Cache = l2Cache;

}

@Override

public String getName() {

return name;

}

@Override

public Object getNativeCache() {

return Arrays.asList(l1Cache.getNativeCache(), l2Cache.getNativeCache());

}

@Override

public ValueWrapper get(Object key) {

// 1. 首先从 L1 获取

ValueWrapper value = l1Cache.get(key);

if (value != null) {

metrics.recordL1Hit();

return value;

}

// 2. L1 未命中,从 L2 获取

value = l2Cache.get(key);

if (value != null) {

metrics.recordL2Hit();

// 回填到 L1

l1Cache.put(key, value.get());

return value;

}

metrics.recordMiss();

return null;

}

@Override

publicT get(Object key, Classtype) {

// 类似逻辑...

return null;

}

@Override

publicT get(Object key, CallablevalueLoader) {

// 带加载器的获取

return null;

}

@Override

public void put(Object key, Object value) {

// 同时写入 L1 和 L2

l1Cache.put(key, value);

l2Cache.put(key, value);

}

@Override

public void evict(Object key) {

// 从两级缓存中同时清除

l1Cache.evict(key);

l2Cache.evict(key);

}

@Override

public void clear() {

l1Cache.clear();

l2Cache.clear();

}

}

}

3. 性能优化和最佳实践

3.1 缓存配置优化

# application-optimized.yml

spring:

cache:

# 使用 Caffeine 作为一级缓存

caffeine:

spec: >

initialCapacity=100,

maximumSize=10000,

expireAfterAccess=600s,

recordStats=true,

weakKeys=false,

weakValues=false

# Redis 作为二级缓存

redis:

key-prefix: "cache:"

time-to-live: 3600s

use-key-prefix: true

cache-null-values: false # 不缓存 null 值

# 连接池配置

datasource:

hikari:

maximum-pool-size: 20

connection-timeout: 30000

idle-timeout: 600000

max-lifetime: 1800000

# 监控配置

management:

metrics:

export:

prometheus:

enabled: true

tracing:

sampling:

probability: 0.1

3.2 缓存使用模式

/**

* 缓存使用的最佳实践

*/

@Service

public class CacheBestPracticesService {

/**

* 1. 缓存穿透保护

*/

@Cacheable(

value = "userCache",

key = "#id",

unless = "#result == null"

)

public User getUserWithPenetrationProtection(String id) {

User user = userRepository.findById(id).orElse(null);

// 如果用户不存在,缓存一个特殊标记

if (user == null) {

// 可以缓存空对象,但设置较短过期时间

cacheNullValue(id);

return null;

}

return user;

}

private void cacheNullValue(String id) {

// 缓存空对象,防止缓存穿透

cacheManager.getCache("userCache").put(id, NullObject.INSTANCE);

}

/**

* 2. 缓存雪崩防护 - 随机过期时间

*/

@Cacheable(

value = "productCache",

key = "#id"

)

public Product getProductWithAvalancheProtection(Long id) {

Product product = productRepository.findById(id).orElse(null);

if (product != null) {

// 为缓存设置随机的过期时间

int randomTtl = 1800 + (int)(Math.random() * 1800); // 30-60分钟

setCustomTtl("productCache", id, randomTtl);

}

return product;

}

/**

* 3. 缓存击穿防护 - 互斥锁

*/

@Cacheable(

value = "hotProductCache",

key = "#id",

sync = true // Spring 4.3+ 支持,使用 synchronized

)

public Product getHotProduct(Long id) {

// 高并发下,只有一个线程会执行数据库查询

return productRepository.findById(id).orElse(null);

}

/**

* 4. 批量操作优化

*/

public MapbatchGetUsers(Listids) {

Mapresult = new HashMap<>();

ListmissingIds = new ArrayList<>();

// 批量从缓存获取

for (String id : ids) {

User cached = cacheManager.getCache("userCache").get(id, User.class);

if (cached != null) {

result.put(id, cached);

} else {

missingIds.add(id);

}

}

// 批量查询缺失的数据

if (!missingIds.isEmpty()) {

ListdbUsers = userRepository.findByIdIn(missingIds);

for (User user : dbUsers) {

result.put(user.getId(), user);

// 批量更新缓存

cacheManager.getCache("userCache").put(user.getId(), user);

}

}

return result;

}

/**

* 5. 读写分离缓存策略

*/

@Cacheable(

value = "readCache",

key = "#id",

cacheManager = "readCacheManager"

)

@CachePut(

value = "writeCache",

key = "#result.id",

cacheManager = "writeCacheManager",

condition = "#result != null"

)

public User getUserWithReadWriteSeparation(String id) {

return userRepository.findById(id).orElse(null);

}

/**

* 6. 缓存预热

*/

@PostConstruct

@Scheduled(cron = "0 0 3 * * ?") // 每天凌晨3点执行

public void warmUpCache() {

// 预热热门数据

ListhotUsers = userRepository.findHotUsers(100);

for (User user : hotUsers) {

cacheManager.getCache("userCache").put(user.getId(), user);

}

// 预热统计信息

Statistics stats = calculateDailyStatistics();

cacheManager.getCache("statisticsCache").put("daily", stats);

}

}

4. 常见问题解决方案

4.1 事务与缓存一致性

/**

* 事务性缓存操作

*/

@Service

@Transactional

public class TransactionalCacheService {

/**

* 事务提交后更新缓存

*/

@CacheEvict(value = "userCache", key = "#user.id")

@Transactional

public User updateUserInTransaction(User user) {

// 数据库更新

User updated = userRepository.save(user);

// 注意:@CacheEvict 在事务提交后执行

// 如果需要立即更新缓存,使用编程式缓存

return updated;

}

/**

* 编程式缓存更新(事务内)

*/

@Transactional

public User updateUserWithProgrammaticCache(User user) {

// 1. 更新数据库

User updated = userRepository.save(user);

// 2. 立即更新缓存(事务内)

TransactionSynchronizationManager.registerSynchronization(

new TransactionSynchronization() {

@Override

public void afterCommit() {

// 事务提交后执行

cacheManager.getCache("userCache").put(user.getId(), updated);

cacheManager.getCache("userListCache").clear();

}

});

return updated;

}

/**

* 使用缓存事务管理器

*/

@Transactional(transactionManager = "cacheTransactionManager")

@CachePut(value = "userCache", key = "#user.id")

public User updateUserWithCacheTransaction(User user) {

return userRepository.save(user);

}

}

4.2 分布式缓存同步

/**

* 分布式缓存同步

*/

@Component

public class DistributedCacheSync {

@Autowired

private CacheMessagePublisher messagePublisher;

@Autowired

private CacheManager cacheManager;

/**

* 本地缓存更新后,通知其他节点

*/

@CacheEvict(value = "userCache", key = "#user.id")

public void updateUserWithBroadcast(User user) {

userRepository.save(user);

// 发布缓存更新消息

messagePublisher.publishCacheEvict("userCache", user.getId());

}

/**

* 监听缓存同步消息

*/

@EventListener

public void handleCacheSyncMessage(CacheSyncMessage message) {

if ("EVICT".equals(message.getOperation())) {

cacheManager.getCache(message.getCacheName())

.evict(message.getKey());

} else if ("CLEAR".equals(message.getOperation())) {

cacheManager.getCache(message.getCacheName())

.clear();

}

}

/**

* 使用 Redis Pub/Sub 进行缓存同步

*/

@Component

public static class RedisCacheSync {

@Autowired

private RedisTemplateredisTemplate;

@PostConstruct

public void init() {

redisTemplate.getConnectionFactory()

.getConnection()

.subscribe((message, pattern) ->{

// 处理缓存同步消息

handleRedisMessage(message);

}, "cache:sync".getBytes());

}

}

}

5. 面试回答要点总结

Java EE 集成要点:

添加依赖:javax.cache:cache-api + 具体实现(Ehcache/Hazelcast)配置方式:XML 配置文件 + @Produces CDI 生产者方法使用方式:通过 @Inject 注入 Cache 或 CacheManager最佳实践:在 EJB 或 CDI Bean 中使用,结合事务管理

Spring Boot 集成要点:

自动配置:spring-boot-starter-cache + 实现依赖启用缓存:@EnableCaching 注解配置方式:application.yml + @Configuration 类使用方式:@Cacheable, @CachePut, @CacheEvict 注解高级特性:条件缓存、键生成器、缓存解析器

关键区别:

特性Java EESpring Boot配置方式XML + CDI ProducersYAML/Properties + @Configuration依赖注入@Inject@Autowired事务集成JTA + @TransactionAttribute@Transactional监控JMXActuator + Metrics测试Arquillian@SpringBootTest最佳实践回答示例:

"在 Spring Boot 中集成 JCache 主要分为以下几步:

添加依赖:引入 spring-boot-starter-cache 和具体的 JCache 实现(如 Ehcache 或 Caffeine)

启用缓存:在主类或配置类上添加 @EnableCaching 注解

配置缓存:在 application.yml 中配置缓存属性和实现特定配置

使用缓存注解:在 Service 层使用 @Cacheable、@CachePut、@CacheEvict 等注解

高级配置:可以自定义 CacheManager、KeyGenerator 和 CacheResolver

这种方式的优势是 Spring Boot 提供了自动配置和开箱即用的功能,同时保持了与 JSR-107 标准的兼容性。"

性能优化要点:

选择合适的实现:本地缓存用 Caffeine,分布式用 Redis配置合理的过期策略:避免缓存雪崩使用多级缓存:L1(本地)+ L2(分布式)监控和指标:集成 Actuator 和 Micrometer异常处理:防止缓存穿透和击穿

这样你就可以在面试中全面、深入地回答关于 Java EE 和 Spring Boot 中集成 JCache 的问题了。

标签: 拼多多助力网站平台 赚钱项目 拼多多助力网 首码项目 手赚APP
拼多多助力营销技巧