java在缓存spring中存储值
我正在研究spring应用程序。我必须从数据库中获取字符串值,并将其存储在缓存中,这样它一整天都在使用同一个对象,而不会访问数据库。下面是示例代码
ehcache。xml
<cache name="attPriorityCache" maxElementsInMemory="6000"
eternal="true" overflowToDisk="false" />
java类:
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
//imports here..
class StoreData{
@Inject
private MyDAO myDAO;
private static CacheManager singletonManager = null;
private static CacheManager getInstance()
{
if (singletonManager == null)
{
singletonManager = CacheManager.create();
}
return singletonManager;
}
private Cache getCache()
{
//create a cache object
}
@PostConstruct
public void loadData()
{
//get the data from database and store in cache
final String attPriority = myDAO.getAttenderPriority(); //hits the database and get the value
//store in cache
if(!Strings.isNullOrEmpty(attPriority)){
//get the cache and remove using removeAll(), so that if value is changed in database it reflects
}
}
由于我不熟悉这个概念,请建议如何为我的上述代码创建缓存对象,以及如何在缓存中保留字符串值(attPriority),以便它在缓存中保留一整天。
在getCache()
方法中,我如何创建一个缓存对象,并在loadData()
方法中使用它来保存attPriority值,它是一个字符串。任何建议都会有帮助
共 (0) 个答案