4

我正在@Cacheable使用 EHCache 测试 Spring 的功能,但我找不到任何关于这是否适用于 Spring 的@Transactional注释的信息。

我在服务方法上@Cacheable放置@CacheEvictDAO方法。@Transactional

假设我的用户 DAO 看起来像这样:

@Cacheable(value="users", key="#id")
User find(BigInteger id);

@CacheEvict(value="users", key="#user.id")
void update(User user);

@CacheEvict(value="users", key="#id")
void delete(BigInteger id);

例如,当在 removeFriend() 过程中调用 getUser() 时可能会出现问题,因为具有过时好友计数的用户将被重新缓存(或者会吗?):

public User getUser(userId) {
    return userDao.find(userId);
}

@Transactional
public void removeFriend(userId, friendId) {
    friendDao.remove(friendId);
    user.setFriendCount(--numFriends);
    userDao.update(user);
    // do some other stuff
}

如何确保在数据库事务完成之前不会更新缓存?@CacheEvict除了 DAO 方法之外,我还放置服务方法吗?或者,我是否向服务方法添加读/写锁定?如果是这样锁定,是否有任何库可以基于 id 锁定,因为我只想锁定每个用户而不是全局锁定,例如@GuardedBy("userLocks.getReadLock(#userId)")?是否有一种普遍接受的方式来处理缓存和事务?

非常感谢!

4

2 回答 2

4

我应该多看看 EHCache 文档,因为答案就在这里

EHCache 2.4+ 使用 Spring 的 @Transactional 注释。只需要配置一个事务管理器查找。

于 2012-06-06T20:59:35.510 回答
1

文档没有提到缓存抽象与其他注释驱动的 Spring 特性有任何交互。

http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/cache.html

缓存抽象是相当新的,目前范围似乎相当小。

您很可能需要重新构建代码,以便以更符合您的操作顺序的方式使用缓存。

于 2012-06-06T02:03:25.897 回答