spring boot advanced - cache, message

Posted by scnov on Sat, 18 Dec 2021 23:13:58 +0100

1. Cache

1.1JSR-107

Original quotation: Profiling cache series - familiar with JSR-107 JAVA cache specification

What is JSR-107?

JSR is the abbreviation of Java Specification Requests, which means Java specification proposal. On October 26, 2012, the JSR specification committee released the first early draft of JSR 107 (JCache API).
JCache specification defines a method to temporarily cache Java objects in memory, including object creation, shared access, spooling, invalidation, consistency of JVM s, etc. it can be used to cache the most frequently read data in JSP.

Java Caching defines five core interfaces: cacheingprovider, CacheManager, cache and entry
And Expiry.
• CachingProvider defines the creation, configuration, acquisition, management and control of multiple cachemanagers. An application can
To access multiple cacheingproviders at run time.
• Cache Manager defines the creation, configuration, acquisition, management and control of multiple uniquely named caches
Exists in the context of the CacheManager. A CacheManager is owned by only one cacheingprovider.
• Cache is a Map like data structure and temporarily stores values indexed by Key. A Cache is only used by one
Owned by CacheManager.
• Entry is a key value pair stored in the Cache.
• Expiry each entry stored in the Cache has a defined validity period. Once this time is exceeded, the entry is expired
Status of the. Once expired, entries will not be accessible, updated, or deleted. Cache validity can be set through ExpiryPolicy.

1.2Spring cache abstraction

Spring has defined org. Net since 3.1 springframework. cache. Cache
And org springframework. cache. CacheManager interface to unify different caching technologies;
It also supports the use of JCache(JSR-107) annotations to simplify our development;
• the Cache interface defines the component specification of the Cache, including various operation sets of the Cache;
• Spring provides various Xcache implementations under the Cache interface; Such as RedisCache, ehcachecache, concurrentmapcache, etc;
• every time a method requiring caching function is called, Spring will check whether the specified target method of the specified parameter has been called; If yes, get the result of the method call directly from the cache. If not, call the method and cache the result and return it to the user. The next call is taken directly from the cache.
• when using Spring cache abstraction, we need to pay attention to the following two points;
1. Determine the methods that need to be cached and their caching policies
2. Read the data stored in the previous cache from the cache

1.2. 1. Build a basic environment & an introduction to caching

/*
*1, Build basic environment
* 1,Import database files and create department and employee tables
* 2,Create javaBean to encapsulate data
* 3,Integrate MyBatis operation database
*       1.Configure data source information
*       2.Use the annotated version of MyBatis
*           1),@MappingScan Specify the packages to scan
* 2, Quick experience cache
*       Steps:
*           1,Enable annotation based caching
*           2,Just cache the annotation
*               @Cacheable
* Mainly for method configuration, the results can be cached according to the request parameters of the method
*               @CacheEvict
*                 wipe cache 
*                @CachePut
*         Ensure that the method is called and that the result is cached.
 */

1.2. 2. Working principle & operation process of cache

  /*
     *Cache the running results of the method. In the future, you need the same data and get it directly from the cache without calling the method
     * Principle:
     *      1,Automatic configuration class: CacheAutoConfiguration
     *      2.Cached configuration class
     *          org. springframework.boot.autoconfigure.cache.GenericCacheConfigurqtion
     *          org. springframework.boot.autoconfigure.cache.ICacheCacheConfiguration
     *          org. springframework.boot.autoconfigure.cache.EhCacheCacheConfiguration
     *          org. springframework.boot.autoconfigure.cache.HazelcastCacheConfiguration
     *          org. springframework.boot.autoconfigure.cache.InfinispanCacheConfiguration
     *          org. springframework.boot.autoconfigure.cache.CouchbaseCacheConfiguration
     *          org. springframework.boot.autoconfigure.cache.RedisCacheConfiguration
     *          org. springframework.boot.autoconfigure.cache.CaffeineCacheConfiguration
     *          org. springframework.boot.autoconfigure.cache.GuavaCacheConfiguration
     *          org. springframework.boot.autoconfigure.cache.SimpleCacheConfiguration
     *          org. springframework.boot.autoconfigure.cache.NoOpCacheConfiguration
     *      3,Which configuration class is effective by default:
     *                  SimpleCacheConfiguration
     *      4,A CacheManager is registered in the container; ConcurrentMapCacheManager
     *      5,You can obtain and create cache components of ConcurrentMapCache type; Its function is to save data in ConcurrentMap;
     *
     *      Operation process:
     *      @Cacheable
     *      1,Query the Cache (Cache component) before running the method
     *          (CacheManager Get the corresponding cache first). If you get the cache for the first time, the cache component will be created automatically
     *      2,Go to the Cache to find the contents of the Cache, and use the first key, which is the method parameter by default;
     *          key It is generated according to a certain policy. By default, it is generated using the keyGenerator. By default, it is generated using the SimpleKeyGenerator
     *              SimpleKeyGenerator Default policy for generating key s:
     *                  If there are no parameters; key = new SimpleKey();
     *                  If there is a parameter: key = the value of the parameter
     *                  If there are multiple parameters: key = new SimpleKey(params);
     *      3,If no cache is found, the target method is called
     *      4,Put the result returned by the target method into the cache
     *
     *      @Cacheable Before executing the marked method, check whether there is this data in the cache. By default, query the cache according to the value of the parameter as the key
     *      If not, run the method and put the result into the cache
     *
     *  core
     *      1),Use the CacheManager [ConcurrentMapCacheManager] to get the Cache [ConcurrentMapCache] component by name
     *      2),key Generated using keyGenerator. The default is SimpleKeyGenerator
     */

1.2. 3 several important concepts cache annotation


Schematic diagram of cache function

1.2.4@Cacheable Several properties of

/*
 *       cacheNames/value:Specifies the name of the cache component
 *       key: Cache data usage key;You can use it to specify. The default is to use the value 1 of the method parameter-Method
 *                      to write SpEL: #id;parameter id Value of #a0 #p0 Mroot. args[0]
 *       keyGenerators key Generator for:You can specify it yourself key Components of the generator id
 *                       key/keyGenerator:Use one out of two
 *       cacheManager:Specify cache manager:perhaps cacheResol ver Specify get parser
 *       condition:Specifies that the cache is only cached if the conditions are met:
 *                       ,condition="#id>0"
 *       unless:Negative cache:When unless The specified condition is true,The return value of the method is not cached:The results can be obtained for judgment
 *                       unless = "#result = null "
 *                       unless = "#a0==2 "; if the value of the first parameter is 2, the result is not cached
 *       sync:Use asynchronous mode

1.3 integrating Redis

  1. Introduce spring boot starter data redis
  2. application.yml configure redis connection address
  3. redis using RestTemplate
  4. redisTemplate.opsForValue();// Operation string
  5. redisTemplate.opsForHash();// Operation hash
  6. redisTemplate.opsForList();// Operation list
  7. redisTemplate.opsForSet();// Operation set
  8. redisTemplate.opsForZSet();// Operation order set
  9. Configure cache, cachemanagercustomizators
  10. Test using cache, switching cache, CompositeCacheManager

2. Message

2.1 general

  1. In most applications, message service middleware can be used to improve the asynchronous communication and extended decoupling ability of the system
  2. Two important concepts in message service:
    message broker and destination
    After the message sender sends the message, it will be taken over by the message agent, which ensures that the message is delivered to the specified destination
    Land.
  3. Message queues have two main forms of destinations
  4. queue: point-to-point message communication
  5. topic: publish / subscribe message communication
  6. Point to point:
    – the message sender sends a message, the message agent puts it into a queue, and the message receiver obtains the message content from the queue,
    The message is removed from the queue after reading
    – a message has only one sender and receiver, but it does not mean that there can only be one receiver
  7. Publish subscribe:
    – if the sender (publisher) sends a message to the topic, and multiple recipients (subscribers) listen to (subscribe to) the topic, then
    The message will be received at the same time when the message arrives
  8. JMS (Java Message Service):
    – JVM based message broker specification. ActiveMQ and HornetMQ are JMS implementations
  9. AMQP(Advanced Message Queuing Protocol)
    – advanced message queuing protocol, which is also a specification of message broker and is compatible with JMS
    – RabbitMQ is an implementation of AMQP
  10. Spring support
    – spring JMS provides support for JMS
    – spring rabbit provides support for AMQP
    – the implementation of ConnectionFactory is required to connect to the message broker
    – provide JmsTemplate and RabbitTemplate to send messages
    - @ JmsListener (JMS), @ RabbitListener (AMQP) annotations listen for messages sent by the message broker on the method
    Cloth news
    – @ EnableJms, @ EnableRabbit enable support
  11. Spring Boot auto configuration
    – JmsAutoConfiguration
    – RabbitAutoConfiguration

2.2 asynchronous processing, application decoupling and flow peak clipping



2.4 comparison between JMS and AMQP

Topics: Java Spring Cache