How to write caching code elegantly





In daily coding practice, caching is often used to solve high concurrency problems. Caching can be said to be the best tool to solve traffic peaks. Although the group's middleware team has built a caching infrastructure and has helped us solve most of the problems, in the actual coding process, the following problems still exist when the application calls the cache API:
  1. The logic of using the cache is very general. Basically, the cache is checked first, and if there is any, it is returned directly without checking the DB, and then placed in the cache. This general logic is scattered throughout the system, violating the principle of high cohesion and low coupling.
  2. Caching code and business logic code are deeply coupled together, which not only reduces the readability of the code, but also increases the complexity of the system.
  3. If you want to switch the cache (MDB->LDB) or upgrade the API, all involved codes need to be changed.
  4. If you want to solve common problems such as cache penetration, cache penetration, cascading cache, etc., you need to solve them through the framework.
Therefore, what cache is and how to choose a certain kind of cache are not the focus of this article. Today I will write about how to separate the cache code from the business code during the actual coding process to make the code more concise and easier to read.

Practical analysis


Read the cache data first, and return directly if there is data. If no data is read, read the DB data, and then update the cache after the data is returned.

This scenario is very common in daily coding and is too simple, but the actual code is indeed very different. Here are some examples:


▐Traditional writing  


Whatever cache is used, use it directly and embed it into the business code. This kind of code is something I don’t want to see whether it’s for code review or when future generations learn business code. The reason is very simple and has nothing to do with actual business functions. I don’t want to know what cache you use or how you code the cache code.



▐A more advanced way of writing  


Compared with the traditional writing method, in order to solve the problem of caching various data formats (List, Map, etc.) and various object serialization (java, json), the team can encapsulate the caching into a simple API for everyone to use. It is easier to use, but the code is still embedded in the business code and has not been stripped out.



▐How to write annotations  


The last is the annotation writing method. Compared with the first two writing methods, the code has been separated from the business code. People who read the code will only care about how the business function is implemented, which cache is used, and how it is implemented, which can be completely ignored.


spring cache solution analysis


Spring cache uses dynamic proxy to process cache-related operations in the proxy class, and at the same time calls methods in the proxy class, so that the code that operates the cache and the business code can be separated, and when the cache capability needs to be strengthened later, only Just modify the method in the proxy class.

The above is the principle of Spring Cache. Spring Cache is a general caching framework provided by Spring. It uses AOP to implement annotation-based caching functions, so that developers do not need to care about what caching framework is used at the bottom. They only need to simply add an annotation to the method to implement the caching function. Using Spring Cache, users can quickly develop a very good caching function.

▐Code directory  



▐Annotation Map  



▐Annotation usage example  


@Cacheable(value = "user_cache", unless = "#result == null")public User getUserById(Long id) { return userMapper.getUserById(id);}@CachePut(value = "user_cache", key = "#user.id", unless = "#result == null")public User updateUser(User user) { userMapper.updateUser(user); return user;}@CacheEvict(value = "user_cache", key = "#id")public void deleteUserById(Long id) { userMapper.deleteUserById(id);}


▐Program analysis  


Spring Cache is very powerful and its design is very elegant. It is especially suitable for scenarios where cache control is not so detailed, such as static display pages, number of likes, rankings, etc. The characteristic of these scenarios is that they do not have such strict requirements on real-time data. They only need to cache the data source and automatically cache it after expiration. Just refresh. In these scenarios, Spring Cache is an artifact that can greatly improve research and development efficiency.

However, in scenarios with high concurrency and large data volume, functional expansion is still required for fine cache granularity control.
  1. Multi-level cache;
  2. The cache is refreshed regularly;
  3. list cache;
  4. Cache cpp protection mechanism;
  5. Cache count.

For example: Spring Cache does not have a second-level cache implementation


Custom cache scheme


Learn the spring cache framework solution and implement a custom cache framework, which not only retains the advantages of the spring cache framework, but also realizes many missing capabilities of spring cache, such as cache breakdown, cache penetration protection, multi-level cache, etc.


▐Annotation   code example



▐Project   structure



write at the end

With the help of spring cache implementation, we build a custom cache framework and extend many annotations, such as counting, cache refresh, list cache, distributed lock, multi-level cache, etc., which not only realizes the separation of cache code and business code, but also expands the spring The ability to cache greatly improves the readability of the code and reduces the efficiency of cached code maintenance.


team introduction


The mission of Tmall Automotive Technology Team is to experience the ultimate life of people and cars, reshape the automotive industry, and be a caring car steward around you. They are all building consumers' minds for online car viewing, buying and maintaining cars, digitizing and vertically integrating the automotive industry, and through Model breakthroughs leverage the integration of product and effect, improve industry efficiency, and create industry dividends.


¤Expand  reading¤ 

3DXR technology  |  terminal technology  |  audio and video technology

Server-side technology  |  Technical quality  |  Data algorithm


This article is shared from the WeChat public account - Big Taobao Technology (AlibabaMTT).
If there is any infringement, please contact [email protected] for deletion.
This article participates in the " OSC Source Creation Plan ". You who are reading are welcome to join and share together.

A programmer born in the 1990s developed a video porting software and made over 7 million in less than a year. The ending was very punishing! High school students create their own open source programming language as a coming-of-age ceremony - sharp comments from netizens: Relying on RustDesk due to rampant fraud, domestic service Taobao (taobao.com) suspended domestic services and restarted web version optimization work Java 17 is the most commonly used Java LTS version Windows 10 market share Reaching 70%, Windows 11 continues to decline Open Source Daily | Google supports Hongmeng to take over; open source Rabbit R1; Android phones supported by Docker; Microsoft's anxiety and ambition; Haier Electric shuts down the open platform Apple releases M4 chip Google deletes Android universal kernel (ACK ) Support for RISC-V architecture Yunfeng resigned from Alibaba and plans to produce independent games on the Windows platform in the future
{{o.name}}
{{m.name}}

Guess you like

Origin my.oschina.net/u/4662964/blog/11104135