NHibernate second-level caching - evicting regions

偶尔善良 提交于 2019-11-30 05:38:06

问题


We have a number of cache regions set up in our nHibernate implementation. In order to avoid trouble with load balanced web servers, I want to effectively disable the caching on the pages that edit the cached data. I can write a method that clears out all my query caches, my class caches and my entity caches easily enough.

But what I really want is to clear the cache by region. sessionFactory.EvictQueries() will take a region parameter, but Evict() and EvictCollection() does not. I don't really want to throw away the whole cache here, nor do I want to maintain some sort of clumsy dictionary associating types with their cache regions. Does nHibernate have a way to ask an entity or collection what its caching settings are?

thanks


回答1:


I've just done the same thing. For everyone's benefit, here is the method I constructed:

public void ClearCache(string regionName)
    {
        // Use your favourite IOC to get to the session factory
        var sessionFactory = ObjectFactory.GetInstance<ISessionFactory>();

        sessionFactory.EvictQueries(regionName);

        foreach (var collectionMetaData in sessionFactory.GetAllCollectionMetadata().Values)
        {
            var collectionPersister = collectionMetaData as NHibernate.Persister.Collection.ICollectionPersister;
            if (collectionPersister != null)
            {
                if ((collectionPersister.Cache != null) && (collectionPersister.Cache.RegionName == regionName))
                {
                    sessionFactory.EvictCollection(collectionPersister.Role);
                }
            }
        }

        foreach (var classMetaData in sessionFactory.GetAllClassMetadata().Values)
        {
            var entityPersister = classMetaData as NHibernate.Persister.Entity.IEntityPersister;
            if (entityPersister != null)
            {
                if ((entityPersister.Cache != null) && (entityPersister.Cache.RegionName == regionName))
                {
                    sessionFactory.EvictEntity(entityPersister.EntityName);
                }
            }
        }
    }



回答2:


OK, looks like i've answered my own question. The default interface that's returned when you pull out the nHibernate metadata doesn't provide information on caching, however if you dig around in the implementations of it, it does. A bit clumsy, but it does the job.



来源:https://stackoverflow.com/questions/9433514/nhibernate-second-level-caching-evicting-regions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!