【发布时间】:2015-03-22 08:00:40
【问题描述】:
我有一个 Spring Web 应用程序,它使用 EhCache 进行数据缓存。
Ehcache 包含很少的 Java.Util.Map,用于整个应用程序视图页面。当用户从前端屏幕创建一条记录(比如一些业务 JAVA POJO 对象)时,该记录将被插入到数据库中,随后,由 EhCache 保存的 Maps 被更新。
后来,我们在多个,即3个tomcat实例中部署了这个web应用。应用程序可通过 Apache HTTP 负载均衡器访问。
我们面临的问题是,当用户向数据库中插入一条记录时,EhCache 仅在收到请求的 tomcat 实例上运行的应用程序中更新。由于我们有 3 个 tomcat 实例,因此在其他 2 个 tomcat 实例上运行的应用程序没有更新的 EhCache 数据。这会影响用户立即从屏幕上查看更新的数据。
谁能告诉我如何解决这个问题。如何在多个 tomcat 实例上运行的 Spring Web 应用程序之间同步 EhCache 数据。
FYKI,这是我职业生涯中的第一个 Web 应用程序,也是数据缓存概念的初学者。
请告诉我解决此问题的方法?
让我分享一下我如何在我的 Spring Web 应用程序中简单地配置 EhCache,
下面是在spring-servlet.xml中配置的
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager" p:cache-manager-ref="ehcache" />
<bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
p:config-location="classpath:ehcache.xml" p:shared="true"/>
来自 Java 业务类
public class PortfolioUserDetailsServiceImpl implements PortfolioUserDetailsService {
private Logger logger = LoggerFactory
.getLogger(PortfolioUserDetailsServiceImpl.class);
private UserDao userDao;
@Autowired
private CacheManager cacheManager;
private Ehcache userRoleCache;
@PostConstruct
public void init() {
// Load our widgets cache:
userRoleCache = cacheManager.getEhcache("userRoleCache");
// Create an EHCache Element to hold the widget
Element element = new Element("getAllRoles", userDao.getAllRoles());
// Add the element to the cache
userRoleCache.put(element);
}
@PreDestroy
public void destory() {
logger.info("INVENTORYSERVICEIMPL destroy method called");
}
这是我的 ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache name="PortfolioCache" updateCheck="false">
<defaultCache maxElementsInMemory="10000" eternal="false"
timeToIdleSeconds="0" timeToLiveSeconds="0" overflowToDisk="true"
diskPersistent="false" diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU" />
<cache name="userRoleCache" maxElementsInMemory="100" eternal="false"
timeToIdleSeconds="0" timeToLiveSeconds="0" memoryStoreEvictionPolicy="LFU">
</cache>
<diskStore path="java.io.tmpdir" />
</ehcache>
【问题讨论】:
标签: java spring tomcat load-balancing ehcache