In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
This article introduces the knowledge of "how to achieve caching in mybatis and ehcache". Many people will encounter such a dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Concept of caching
Caching in java can be divided into two cases, one is JVM cache, which is used by JVM to deal with the operating system, and is generally not needed when developing in Java language.
One is the java language cache, where caching is a mechanism that is not related to any hardware. For example, for a variable of static, when we visit him for the first time, we read his value in the file, and when we visit it later, we directly return this value, which saves IO time and improves efficiency. This is a simple caching mechanism.
First-level cache
First-level cache is a SqlSession-level cache. When manipulating the database, you need to construct a sqlSession object, in which there is a data structure for storing cached data. The cached data regions between different sqlSession do not affect each other. That is, it can only work in the same sqlSession, and caches in different sqlSession cannot be read from each other.
Processing flow:
The user initiates a query request to find a certain piece of data. SqlSession first goes to the cache to find the data. If so, read the data.
If not, query from the database and put the queried data into the first-level cache area for the next search.
However, sqlSession performs commit, that is, the cache is cleared when the add, delete and modify operation is performed. The purpose of this is to avoid dirty reading.
If commit does not empty the cache, there will be the following scenario: a queries the inventory of 10 items and stores the data of 10 items in the cache, then the customer buys 10 items and the data is delete. But the next time you query this item, it will not query from the database, but will query from the cache, and an error will occur.
Second-level cache
Second-level cache is mapper-level cache, multiple SqlSession to operate the same Mapper sql statements, multiple SqlSession can share secondary cache, secondary cache is cross-SqlSession.
UserMapper has a second-tier cache area (by namespace), and other mapper has its own second-level cache area (by namespace). The mapper of each namespace has a secondary cache area. If the namespace of the two mapper is the same, the two mapper performing sql queries to the data will exist in the same secondary cache area.
Processing flow:
There is a problem here, since there is a first-level cache, why provide a second-level cache?
Second-level cache is mapper-level cache, multiple SqlSession to operate the same Mapper sql statements, multiple SqlSession can share secondary cache, secondary cache is cross-SqlSession. Secondary caching has a wider range of functions.
Another reason is that in actual development, MyBatis is usually integrated with Spring. Spring manages transactions in Service, which is different for each sqlsession in service, which is automatically injected into service through org.mybatis.spring.mapper.MapperScannerConfigurer creation sqlsession in mybatis-spring. The sqlSession is closed after each query, and the data is emptied after it is closed. So after spring integration, first-level caching is meaningless if there are no transactions.
Use of second-tier cache:
1, turn on the main switch
Add the following to the configuration file of MyBatis:
2. Add the caceh tag to the mapper.xml where secondary cache needs to be enabled
3. Let the POJO class that uses the second-level cache implement the Serializable interface
Public class User implements Serializable {}
Integrate ehcache
Distributed cache can read data with high performance, dynamically expand cache nodes, automatically find and switch failed nodes, automatically balance data partitions, and provide users with a graphical management interface. deployment and maintenance are very convenient.
However, mybatis can not implement distributed cache, so it needs to be integrated with other distributed cache frameworks. Here is a brief introduction to integration with ehcache.
Integration process:
Mybatis provides a cache interface. If you want to implement your own cache logic, you can implement cache interface development.
Mybatis and ehcache integration, mybatis and ehcache integration package provides an implementation class of the cache interface.
Package org.apache.ibatis.cache.impl
Import java.util.HashMap
Import java.util.Map
Import java.util.concurrent.locks.ReadWriteLock
Import org.apache.ibatis.cache.Cache
Import org.apache.ibatis.cache.CacheException
/ * * @ author Clinton Begin * /
Public class PerpetualCache implements Cache {
Private String id
Private Map cache = new HashMap ()
Public PerpetualCache (String id) {
This.id = id;}
Public String getId () {
Return id;}
Public int getSize () {
Return cache.size ();}
Public void putObject (Object key, Object value) {cache.put (key, value);}
Public Object getObject (Object key) {
Return cache.get (key);}
Public Object removeObject (Object key) {
Return cache.remove (key);}
Public void clear () {cache.clear ();}
Public ReadWriteLock getReadWriteLock () {
Return null;}
Public boolean equals (Object o) {
If (getId () = = null) throw new CacheException ("Cache instances require an ID.")
If (this = = o)
Return true
If (! (o instanceof Cache))
Return false; Cache otherCache = (Cache) o
Return getId () .equals (otherCache.getId ();}
Public int hashCode () {
If (getId () = = null) throw new CacheException ("Cache instances require an ID.")
Return getId (). HashCode ()
Configuration steps:
1. Configure type in cache in mapper to be the implementation type of ehcache to cache interface
Indicates that the secondary cache under the namespace of this mapper is enabled
Type represents the type of implementation class that specifies the cache interface, and mybatis uses PerpetualCache by default.
To integrate with ehcache, you need to configure type to implement the type of cache interface for ehcache.
2. Add the configuration file of ehcache
Configure ehcache.xml under classpath
3Dependencies related to ehcache in 3Magi Maven
Org.ehcache ehcache 3.1.3 org.mybatis mybatis-ehcache 1.0.0
Finally, briefly compare the three more popular caching tools.
Ehcache is a pure Java in-process caching framework, which is used by hibernate for secondary caching. At the same time, ehcache can cluster through multicast.
Memcache is a distributed cache system that provides simple data storage such as key-value, which can make full use of CPU multi-core and no persistence function.
Redis high-performance key-value system, provides a wealth of data types, single-core CPU has anti-concurrency ability, persistence and master-slave replication functions.
This is the end of the content of "how to cache mybatis and ehcache". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.