Nhib.pdf beginner's Guide (10): level 1 and level 2 Cache

Source: Internet
Author: User
Level 1 Cache

Nhibernate intelligently caches data for better performance. Nhibernate has different caching mechanisms. The most important thing is the level-1 cache. Each session object maintains a level-1 cache. When a session object is created, the cache is created, and when the session object is released, the cache is destroyed.

The cache is just a hash table. Hash Tables store values based on unique keys. values can be retrieved based on unique keys.

An object is uniquely identified by its ID. If the two entities have the same type and the IDs are equal, the two entities are equal. Nhib.pdf requires that two objects of the same type cannot have the same ID. The reason is that if two instances with the same ID are allowed, the system will be placed in an inconsistent state. With this condition, nhib.pdf can perform the following operations:

The Nhibernate Session Object loads the object with the specified ID from the database and then stores it in the first-level cache. The key used to access the object is its id value. When the system loads the same object from the database again, the session object first checks its cache. If the object already exists in the cache, Nhibernate returns the cached instance. Only when the object is not cached does the nhib1_session object load the object from the database. Take a look at the following process:

    • ProgramProduct with a request session ID of 1
    • Session asks the level-1 cache: "Is there a product with ID 1 ?"
    • Level 1 cache replied: "no"
    • The session loads the product with ID 1 from the database.
    • Session puts the product into the first-level cache, and the key is the ID value of the product.
    • The session is returned to the program product instance.
    • The program executes more operations.
    • The program requests the product with the session ID 1 again.
    • Session: "Is there a product with ID 1"
    • Level 1 cache replied: "Yes"
    • The session uses the ID as the key to load the product with ID 1 from the cache and return it to the program.

We use the followingCodeLoad the object from the database and implicitly store it in the first-level cache:

 
VaR Product = sesson. Get <product> (1 );

Subsequent get operations will not cause nhib.pdf to query the database, but retrieve objects from the first-level cache.

Clear Cache

We use the following statement to request the session to remove an entity from the first-level cache:

 
Session. evict (product );

To completely clear the cache, you can use the following code:

Session. Clear ();

The preceding statement should only be used in special cases, because improper use may cause significant performance degradation. We recommend that you use these operations only when writing test code.

Refresh the cached entity

To refresh a single object in the first-level cache, use the following statement:

 
Session. Refresh (product );

The above code re-loads the status of the product entity from the database, which makes sense when the entity in the database is changed by other programs while the session is opened.

Level 2 Cache

We have seen that nhib.pdf provides a very effective way to cache data. Unfortunately, the first-level cache is bound to the Session object. That is to say, every time the session is released, all the cached data will be lost. The second-level cache is defined at the session factory level. As long as the session factory is not released, the cache will always exist. Once an object is loaded, the second-level cache is activated and the object is available to all sessions (in the same session factory. In this way, as long as the object is in the second-level cache, Nhibernate will not load the object from the database until it is removed from the cache.

To start the second-level cache, we need to define which cache provider to use. The second-level cache has various implementations. In our example, the hash table-based Cache is used, which is included in the core nhib.pdf assembly. Please note that this cache provider should not be used in production-level code, but only for testing. Refer to the "second-level cache implementation" section to select which implementation is best for you. However, if you change the cache provider, you do not need to modify your code.

Using the following code will only cause nhib.pdf to access the database once to retrieve the product with the ID of 1, even if we use two different session instances:

Using (VAR session1 = sessionfactory. opensession () {var Product = session1.get <product> (1);} using (VAR session2 = sessionfactory. opensession () {var Product = session2.get <product> (1 );}

The second get operation retrieves the product entity from the second-level cache. However, if the second-level cache is not enabled, the above Code will access the database twice.

In addition, to start the second-level cache, you must configure nhib.pdf accordingly. The configuration details will be described later. We must also map objects to cache. If you use FLUENT to map objects, the necessary statements to add to ing are:

 
Cache. readwrite ();

Only the entities that display the configuration are cached in the second-level cache.

Cache area

If the cache area is not used, the second-level cache can only be cleared as a whole. If you want to clear part of the second-level cache, you must use the cache area. The cache regions are differentiated by their names. We can place any number of different queries in the named cache region. The command to clear a cache region is as follows:

 
Sessionfactory. evictqueries ("My region ");

The sessionfactory currently used is an instance of the session factory, and my region is the name of the cache region.

Implementation of level 2 Cache

All level-2 cache providers are part of the nhib?contributions project. The following list provides a brief description of supported providers.

    • Syscache: Uses system. Web. caching. cache as the cache provider. That is to say, you can rely on the cache function of ASP. NET to understand how it works.
    • Syscache2: use ASP. NET cache like nhib.pdf. Caches. syscache. This provider also supports SQL dependency expiration, which means that when the data in the database changes, it is impossible to automatically configure some cache regions.
    • Velocity: As part of Microsoft Windows Server app fabric, velocity is a comprehensive service that builds, extends, and manages IIS-based Web applications.
    • Prevalence: Uses bamboo. prevalence as the cache provider. Bamboo. Prevalence is A. Net implementation of the popular Object concept proposed by Klaus wuestefeld in prevayler. Bamboo. Prevalence provides transparent object persistence for CLR deterministic systems. It provides persistent caching for Smart Client Applications.
    • Memcache: memcached. memcahed is a high-performance, distributed memory object cache system designed to accelerate Dynamic Web applications by reducing database load. Basically, it is a distributed Hash table.
Instance-use level-2 Cache

In this example, we use the second-level cache of nhib.pdf to implement a very simple example. We use the hash table cache provider in the example, but do not use this provider in the production-level code!

1. Create a database in SSMs: secondlevelcachesample.

2. Open Visual Studio and create a console application: secondlevelcachesample.

3. Add references to the nhib.pdf. dll, fluentnhib.pdf. dll, and nhib.pdf. bytecode. Castle. dll assembly.

4. Create a domain folder in the project.

5. Create a class file product. CS in the domain folder and add the following code:

Public classProduct{Public Virtual intId {Get;Set;}Public Virtual stringName {Get;Set;}Public Virtual decimalUnitprice {Get;Set;}Public Virtual intReorderlevel {Get;Set;}Public Virtual boolDiscontinued {Get;Set;}}

6. Add a productmap. CS class file to the domain folder to map the product object. The Code is as follows:

Public classProductmap:Classmap<Product> {PublicProductmap () {cache. readwrite (); Id (x => X. ID). generatedby. HiLo ("1000"); Map (x => X. name); Map (x => X. unitprice); Map (x => X. reorderlevel); Map (x => X. discontinued );}}

Note that the cache. readwrite () Statement is added to the ing to instruct Nhibernate to use the second-level cache for the product entity.

7. Add a static isessionfactory field in the program class, as shown below:

 
Private StaticIsessionfactorySessionfactory;

8. Add a static method in the program class: configuresystem. This method includes the general code for configuring Nhibernate and the Code for second-level cache. The following code is used:

Private Static void Configuresystem (){ Const string Connstring = "Server =.; database = secondlevelcachesample ;" + "User ID = sa; Password = Sasa ;" ; VaR Configuration = Fluently . Configure (). Database ( Mssqlconfiguration . Mssql2008. connectionstring (connstring). showsql). mappings (M => M. fluentmappings. addfromassemblyof < Product > (). Buildconfiguration (); configuration. properties [ "Cache. provider_class" ] = "Nhib.pdf. cache. hashtablecacheprovider" ; Configuration. properties [ "Cache. use_second_level_cache" ] = "True" ; VaR Exporter = New  Schemaexport (Configuration); exporter. Execute ( True , True , False ); Sessionfactory = configuration. buildsessionfactory ();}

In the code for configuring the second-level cache, the first one is to tell Nhibernate which second-level cache provider to use. It is a key-value pair. The value is the full path of the second-level cache provider class. In our example, no Assembly needs to be defined because the provider is in the nhib.pdf assembly. The second is to enable or disable the use of level 2 cache. Note: Technically, the second configuration is not required because its default value is true.

9. Create a static testloadentity method in the program class. The Code is as follows:

 Private Static void Testloadentity (){ Int Productid; VaR Product = New  Product {Name = "Apple" , Unitprice = 1.55 m, reorderlevel = 100, discontinued = False }; Using ( VaR Session = sessionfactory. opensession ()){ Using ( VaR Tx = session. begintransaction () {productid = ( Int ) Session. Save (product); Tx. Commit ();}} Using ( VaR Session1 = sessionfactory. opensession ()){ VaR Product1 = session1.get < Product > (Productid );} Using ( VaR Session2 = sessionfactory. opensession ()){ VaR Product2 = session2.get < Product > (Productid );}}

10. Call the configuresystem and testloadentity methods in the main method:

 
Static voidMain (String[] ARGs) {configuresystem (); testloadentity ();Console. Write ("\ R \ nhit enter to exit :");Console. Readline ();}

11. Run the program to verify that no SELECT statement is generated. This indicates that the second-level cache takes effect.

12. Change cache. use_second_level_cache to false and run the program again. This time, two select statements are sent to the database, as shown in:

Obviously, apart from the insert statement, there are two select statements: one session object for loading the product entity.

in this example, we learned how to configure programs so that Nhibernate can use the second-level cache, and how to configure entity ing so that they can be cached in the second-level cache.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.