Questions
Based on the requirements raised, I think there are mainly the following two questions:
Because there are Local cache, how to ensure data consistency. When the data of one node changes, how does the data of other nodes become invalid?
The data is incorrect and needs to be resynchronized. How to invalidate the cache?
Flow chart
The next step is to cooperate with the product and other developers to draw a flow chart, as follows:
Use a A configuration table records whether caching is needed and whether caching is enabled to achieve cache invalidation when notified.
Because the project requirements are general, even if the message is lost, there will not be much impact, so I finally chose the subscription and publishing functions in redis to notify other nodes of invalid local cache.
Development
The above questions are clear, and the flow chart is also clear. Then get ready to start writing bugs. The overall idea is to customize the annotation implementation aspects and try to reduce the coupling to the business code.
CacheConfig
Mainly explained in the code, defining a CacheManager to integrate with the business. Special attention needs to be paid to the maximum number of cacheable items to avoid occupying too much program memory and causing the memory to become full. Of course, it cannot be too small, because the hit rate issue also needs to be considered. Therefore, the final size must be determined based on the actual business.
@Bean(name = JKDDCX) @Primary public CacheManager cacheManager() { CaffeineCacheManager cacheManager = new CaffeineCacheManager(); cacheManager.setCaffeine(Caffeine.newBuilder() // 设置最后一次写入或访问后经过固定时间过期 .expireAfterAccess(EXPIRE, TIME_UNIT) //设置本地缓存写入后过期时间 .expireAfterWrite(EXPIRE, TIME_UNIT) // 初始的缓存空间大小 .initialCapacity(500) // 缓存的最大条数 .maximumSize(1000));// 使用人数 * 5 (每个人不同的入参 5 条)\ return cacheManager; }
@CaffeineCache
Customize annotations and add all available parameters.
@Target({ ElementType.METHOD ,ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface CaffeineCache { public String moudleId() default ""; //用于在数据库中配置参数 public String methodId() default ""; public String cachaName() default ""; //动态切换实际的 CacheManager public String cacheManager() default ""; }
CacheMessageListener
Cache listener is mainly responsible for ensuring the consistency of multi-node data. When a node cache is updated, other nodes are notified to handle it accordingly. Use the publish and subscribe function of Redis and implement the MessageListener interface to implement the main technology.
Of course, another detail below is that the Redis#keys command is disabled in general production environments, so you have to scan the corresponding keys in another way.
public class CacheMessageListener implements MessageListener { @Override public void onMessage(Message message, byte[] pattern) { CacheMessage cacheMessage = (CacheMessage) redisTemplate.getValueSerializer().deserialize(message.getBody()); logger.info("收到redis清除缓存消息, 开始清除本地缓存, the cacheName is {}, the key is {}", cacheMessage.getCacheName(), cacheMessage.getKey()); // redisCaffeineCacheManager.clearLocal(cacheMessage.getCacheName(), cacheMessage.getKey()); /** * 如果是一个类上使用了 注解 @CaffeineCache ,那么所有接口都会缓存。 * 下面的逻辑是:除了当前模块的接口访问的入参 key,其他的 redis 缓存都会被清除 * (比如此模块的表更新了,但是当前调用此接口只是缓存了当前这个入参的redis,其他的数据删除) */ String prefixKey = RedisConstant.WXYMG_DATA_CACHE + cacheMessage.getCacheName(); Set<String> keys = redisTemplate.execute((RedisCallback<Set<String>>) connection -> { Set<String> keysTmp = new HashSet<>(); Cursor<byte[]> cursor = connection.scan(new ScanOptions.ScanOptionsBuilder(). match(prefixKey + "*"). count(50).build()); while (cursor.hasNext()) { keysTmp.add(new String(cursor.next())); } return keysTmp; }); Iterator iterator = keys.iterator(); while (iterator.hasNext()) { if (iterator.next().toString().equals(cacheMessage.getKey())) { iterator.remove(); } } redisTemplate.delete(keys); cacheConfig.cacheManager().getCache(cacheMessage.getCacheName()).clear(); //cacheName 下的都删除 } }
CaffeineCacheAspect
Then there is the logical processing of the aspect. The content inside is exactly the same as the flow chart, except that the code is used to implement the requirements.
Among them: The following code is Redis publishing messages.
redisTemplate.convertAndSend(CacheConfig.TOPIC, new CacheMessage(caffeineCache.cachaName(), redisKey));
CacheMessage
This is a message body when Redis publishes a message. It is also customized. You can add more parameter attributes
public class CacheMessage implements Serializable { private static final long serialVersionUID = -1L; private String cacheName; private Object key; public CacheMessage(String cacheName, Object key) { super(); this.cacheName = cacheName; this.key = key; } }
The above is the detailed content of How to use caffeine_redis to customize the second level cache. For more information, please follow other related articles on the PHP Chinese website!

Redis plays a key role in data storage and management, and has become the core of modern applications through its multiple data structures and persistence mechanisms. 1) Redis supports data structures such as strings, lists, collections, ordered collections and hash tables, and is suitable for cache and complex business logic. 2) Through two persistence methods, RDB and AOF, Redis ensures reliable storage and rapid recovery of data.

Redis is a NoSQL database suitable for efficient storage and access of large-scale data. 1.Redis is an open source memory data structure storage system that supports multiple data structures. 2. It provides extremely fast read and write speeds, suitable for caching, session management, etc. 3.Redis supports persistence and ensures data security through RDB and AOF. 4. Usage examples include basic key-value pair operations and advanced collection deduplication functions. 5. Common errors include connection problems, data type mismatch and memory overflow, so you need to pay attention to debugging. 6. Performance optimization suggestions include selecting the appropriate data structure and setting up memory elimination strategies.

The applications of Redis in the real world include: 1. As a cache system, accelerate database query, 2. To store the session data of web applications, 3. To implement real-time rankings, 4. To simplify message delivery as a message queue. Redis's versatility and high performance make it shine in these scenarios.

Redis stands out because of its high speed, versatility and rich data structure. 1) Redis supports data structures such as strings, lists, collections, hashs and ordered collections. 2) It stores data through memory and supports RDB and AOF persistence. 3) Starting from Redis 6.0, multi-threaded I/O operations have been introduced, which has improved performance in high concurrency scenarios.

RedisisclassifiedasaNoSQLdatabasebecauseitusesakey-valuedatamodelinsteadofthetraditionalrelationaldatabasemodel.Itoffersspeedandflexibility,makingitidealforreal-timeapplicationsandcaching,butitmaynotbesuitableforscenariosrequiringstrictdataintegrityo

Redis improves application performance and scalability by caching data, implementing distributed locking and data persistence. 1) Cache data: Use Redis to cache frequently accessed data to improve data access speed. 2) Distributed lock: Use Redis to implement distributed locks to ensure the security of operation in a distributed environment. 3) Data persistence: Ensure data security through RDB and AOF mechanisms to prevent data loss.

Redis's data model and structure include five main types: 1. String: used to store text or binary data, and supports atomic operations. 2. List: Ordered elements collection, suitable for queues and stacks. 3. Set: Unordered unique elements set, supporting set operation. 4. Ordered Set (SortedSet): A unique set of elements with scores, suitable for rankings. 5. Hash table (Hash): a collection of key-value pairs, suitable for storing objects.

Redis's database methods include in-memory databases and key-value storage. 1) Redis stores data in memory, and reads and writes fast. 2) It uses key-value pairs to store data, supports complex data structures such as lists, collections, hash tables and ordered collections, suitable for caches and NoSQL databases.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools