Three ways to implement caching in Java
1. HashMap implementation cache
It can implement simple local cache, but it is not recommended in actual development. We can simply simulate the implementation of cache.
Step-1: Implement a cache management class
public class LocalCache { public static HashMap<String,String> cache = new HashMap<>(); static { String name = ().toString(); ((1),name); ("Data with id 1 is added to cache"); } } // There are static code blocks modified by `static` in the class, which will be executed when the class is loaded. If you don't understand, you can follow the blog// /weixin_62636014/article/details/136851287
Tips
:We are herestatic
Initialization of the cache has been completed, and you can put the initial data into the cache.
Step-2: Leave the cache management class to Spring for management
@Component public class LocalCache { public static HashMap<String,String> cache = new HashMap<>(); static { String name = ().toString(); ((1),name); ("Data with id 1 is added to cache"); } @PostConstruct public void init() { String name = ().toString(); ((2),name); ("Data with id 2 is added to cache"); } }
Tips
: Handing over the cache management class toSpring
After the management is carried out, add it to the method@PostConstruct
, the method can be executed by default, note that the annotation is notSpring
The framework is provided byJava JDK
Provided mainly forServlet
The annotation of the life cycle is realized inBean
Customize the operation before initialization
@PostConstruct
Method inBean
Execution order in initialization
-
Constructor
(Construction method) -
@Autowired
(Dependency injection) -
@PostConstruct
(The initialization method of comments)
Step-3: Write interface test cache
@RequestMapping("test") public String test(Long id) { String name = ((id)); if (name != null) { ("Exist in cache, query cache"); (name); return name; } ("Do not exist in the cache, query the database"); // After querying the database operation, the queryDataName method is not written; // You can match Mybatis and JDBC to query the database yourself. The result is to find out the name from the library; name = queryDataName(id); (name); ((id),name); return name; } public String queryDataName(Long id) { String name = ().toString(); return name; }
Step-4: Results Display
This is the console output, everyone's randomUUID
Inconsistent, I'm just a sample
Data with id 1 is added to the cache
Data with id 2 is added to the cache
Exist in the cache, query the cache
e2eadabe-3c42-4732-b465-e085ea5faf96
Does not exist in the cache, query the database
942ffe92-454f-4046-87e5-53e8b951d2a1
2. Guava local cache implementation
Tips
:Guava
yesJava
Toolkit,Guava Cache
It is a very complete local cache mechanism (JVM
Cache), tool classes are commonly used methods for packaging, and you don't need to re-create wheels to save developers time. We generally need to know how to use them. Its design comes fromCurrentHashMap
, the cached values stored therein can be cleaned up according to various strategies and maintain high concurrent read and write performance.
Guava
Provide the following capabilities
- gather [
collections
]- cache [
caching
]- Native type support [
primitives support
]- Concurrency library [
concurrency libraries
]- General Annotations [
common annotations
]- String processing [
string processing
]I/O
etc.
Step-1: Importing guava dependencies
<dependency> <groupId></groupId> <artifactId>guava</artifactId> <version>32.1.3-jre</version> </dependency>
Step-2: Create a simple cache management class using guava
For the convenience of display, this is used5
Cache retention time in seconds.
import ; import ; import ; import ; @Component public class GuavaLocalCache{ private Cache<String,String> fiveSecondCache = () //Set the initial cache size, it should be set reasonably, and the capacity will be expanded in the future .initalCapacity(10) //Maximum value .maximumSize(100) //Concurrent number setting .concurrencyLevel(5) //Cached expiration time, expires 5 seconds after writing .expireAfterWrite(5,) //Statistics of cache hit rate .recordStats() .build() public Cache<String,String> getFiveSecondCache() { return fiveSecondCache; } // Here is to get the cache object. public void setFiveSecondCache(Cache<String,String> fiveSecondCache) { = fiveSecondCache; } }
Step-3: Use guava cache and try to count hits
public class test { @Autowired private GuavaLocalCache guavaLocalCache; @RequestMapping("guavaTest") public String guavaTest(Long id) { // Get cache Cache<String,String> fiveSecondCache = (); // Get object from cache String nameCache = ((id)); // Exist in the cache if (nameCache != null) { ("Cached Hit:"+ nameCache + "," + getCacheStats(fiveSecondCache)); return nameCache; } // Save data into cache ("Cached Miss," + getCacheStats(fiveSecondCache)); nameCache = id + "-" + ().toString(); ((id),nameCache); return nameCache; } public String getCacheStats(Cache<String,String> cahce) { CacheStats stats = (); return "Buffer hit rate:"+() +"Cleared buffer count:" + (); } }
3. Use redis to implement cache
Tips
:Redis
(Full name:Remote Dictionary Server
Remote Dictionary Service) is an open source usageANSI C
Language: Writing, supporting network, logging type that can be memory-based or persistent,Key-Value
database .Redis
It is generally used for caching, and it is actually a kind of database (Non-relational database), which can store frequently used data, which is what we call cache. The official data is,Redis
Can achieve10w+
ofQPS
(Query speed per second).
Tips
: WhyRedis
Speed ratioMysql
Wait for this kind of data to be fast?Because
Redis
What is stored iskey-values
The time complexity of the data in the format isO(1)
, that is, directlykey
Query the correspondingvalue
. AndMysql
The underlying implementation of the database isB+
The time complexity isO(logn)
。The most important point is that the data in the database is stored indiskin, and
Redis
It is stored inMemoryAmong them, their speed gap is self-evident. butRedis
Supports persistent storage
Step-1: Import Redis Dependencies
<dependency> <groupId></groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
existSpringBoot
Add settings to the configuration file, I'm usingyml
If you don't have a password, just don't fill it in
redis: # IP address host: # password password: XXXXXXXX # port, default is 6379 port: 6379 # Database Index database: 0 # Connection timeout timeout: 10s lettuce: pool: # Minimum idle connection in the connection pool min-idle: 1 # Maximum free connection in the connection pool max-idle: 8 # Maximum number of database connections to the connection pool max-active: 8 # #Maximum blocking waiting time for connection pools (using negative values means there is no limit) max-wait: -1ms
Step-2: Write a test interface
public class TestRedis{ // The following StringRedisTemplate is a class inherited from RedisTemplate @Autowired private StringRedisTemplate stringRedisTemplate; @RequestMapping("/redisTest") public String redisCacheTest(Long id){ String name = ().get((id)); if (name != null){ ("Exist in cache, query cache"); (name); return name; } ("Do not exist in the cache, query the database"); name = id + "-" + ().toString(); (name); ().set((id),name); return name; } }
Step-3: Perform interface testing and use Redis DeskTop Manager to view it
Reference article
- 【java cache, redis cache, guava cache】 Several ways to implement cache in java_java cache cache-CSDN blog
- One article to get the basics of Redis - Zhihu ()
- Selection of Java local cache technology (Guava Cache, Caffeine, Encache) - Nuggets ()
- Super detailed interpretation of MemCache principle (learning only) - Zhihu ()
- PostConstruct annotation details and understanding - CSDN Blog
- PostConstruct (Java Platform SE 8 ) ()
- The use of the Java development tool Guava Cache - Nuggets ()
- Introduction and use of Google guava tool classes - Nuggets ()
- Redis detailed introduction (lite version)_redis service Lite-CSDN blog
- First know Redis, it's enough to read this article
This is the article about the three ways to implement caching in Java. This is all about this article. For more related Java cache content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!