Spring Cache For Redis and springredis

Source: Internet
Author: User

Spring Cache For Redis and springredis
I. Overview

Cache(Caching) can store frequently used information, so that the information is available immediately whenever necessary.

Common cache databases:

RedisNon-relational databases that use in-memory storage (in-memory), including strings, lists, sets, HASH lists, and ordered sets. Each data type has its own exclusive command. In addition, there are bulk operation and incomplete (partial) transaction support, publishing and subscription, master/slave replication, persistence, scripts (stored procedures, stored procedure ). The efficiency is lower than ehcache, which is much faster than the database. It is convenient to process clusters and distributed cache, and there are mature solutions. For large systems, such as cache sharing, distributed deployment, and large cache content, redis is recommended.
MemcachedUse the key-value cache stored in the memory, the ing between key-values, the creation command, the READ command, the update command, the DELETE command, and several other commands. A multi-threaded server designed to improve performance. Memcache implements distributed caching on the client and uses distributed algorithms to specify the target data node.

EhcachePure java implementation, cache in the memory, can be persisted to the hard disk, the efficiency is higher than memcache; but the cache sharing is troublesome, and the cluster distributed application is not convenient. If it is a single application or an application with high cache access requirements, use ehcache. Ehcache also has a cache sharing solution, but it only broadcasts cache notification updates through RMI or Jgroup multicast. cache sharing is complex and inconvenient to maintain. Simple sharing is acceptable, but cache recovery is involved, big data cache is not suitable.

Ii. Spring Cache

Spring cache is implemented by creating an aspect and triggering the pointcut of the Spring cache annotation ). Based on the annotations used and the cache status, this section retrieves data from the cache, adds the data to the cache, or removes a value from the cache. Spring can be integrated with multiple popular cache implementations. The implementation steps are as follows:

1. Enable cache support
  • Java configuration annotation-driven Cache

---- @ EnableCaching

  • XML declared Cache

---- <Cache: annotation-driven>

2. cache manager

Cache manager is the core of Spring cache abstraction. It can be integrated with multiple popular cache implementations. Spring3.1 configures five cache manager implementations:

  • SimpleCacheManager
  • NoOpCacheManager
  • ConcurrentMapCacheManager (its cache storage is memory-based, so its lifecycle is associated with the application. For large enterprise-level production applications, this may not be an ideal choice)
  • CompositeCacheManager (the system uses multiple cache managers for integration at the same time)
  • EhCacheCacheManager

In addition to the core Spring framework, Spring Data provides two cache managers:

  • RedisCacheManager
  • GemfireCacheManager
3. Add annotations for methods to support caching

Spring provides four annotations to declare cache rules:

@ Cacheable triggers a call to a method conditionally, depending on whether the required value is already in the cache.
@ CachePut adopts a more direct process. Methods With the @ CachePut annotation are always called, and their return values are also cached.

@ Cacheable and @ CachePut have some common attributes:

The value: value Attribute must be specified. It indicates the Cache on which the return value of the current method will be cached, corresponding to the Cache name. The main function is to give the cache a name! I personally think it is mainly to better manage cache objects in Spring containers.

Condition: Before calling a method: if the value of the SPEL expression is false, it will not be cached.

After the method is called: if the value of the SPEL expression is false, the return value is not cached ..

Unless: Before calling a method: no matter whether the SPEL value is true or false, the corresponding value will be searched in the cache. If it is found, the corresponding value will be returned. The method can only be executed if it is not found.

After the method is called: if the value of the SPEL expression is true, the return value is not cached.

Key: the value of the specified key is the value of the key to be saved to the cache database. However, this key has its own method, as shown below:

In addition, it must be noted that # result cannot be used on @ Cacheable because # result indicates the cache value of the method call. However, @ Cacheable may not go through the method and may not return values. So it is not suitable. But! But! # The result can be used in the unless attribute of @ Cacheable, because unless is determined when the method returns, so there must be a return value!

@ CacheEvict some attributes specify the cache quantity to be removed: 

@ CacheEvict is mainly used to remove a data entry and remove the key and value of the data entry in the cache.

@ Cacheing

@ Caching annotation allows us to specify multiple Spring Cache related annotations on a method or class at the same time, with attributes: cacheable, put, and evict.

@Caching(cacheable=@Cacheable("users"),evict={@CacheEvict("cache2"),@CacheEvict(value="cache3",allEntries=true)})
Iii. Spring Data Redis

Spring Data Redis contains multiple template implementations to complete the Data access function of the Redis database.

1. Add dependency <dependency> <groupId> org. springframework. data </groupId> <artifactId> spring-data-redis </artifactId> <version> 1.8.7.RELEASE </version> </dependency> <groupId> redis. clients </groupId> <artifactId> jedis </artifactId> <version> 2.9.0 </version> </dependency>View Code 2, Redis connection Factory

To create a Spring Data Redis template, we first need a Redis connection factory. Spring Data Redis provides four connection factories for us to choose from (these connection factories are the same in terms of applicability ):

  • JedisConnectionFactory
  • JredisConnectionFactory
  • LettuceConnectionFactory
  • SrpConnectionFactory

3,RedisTemplate andStringRedisTemplate

Similar to other Spring Data projects, Spring Data Redis provides high-level Data access solutions in the form of templates. Spring Data Redis provides two templates:

  • RedisTemplate
  • StringRedisTemplate

RedisTemplate supports Object-type keys and Object-type values. StringRedisTemplate adopts a simpler and more crude method. It only supports key and value of the String type.

4. cache manager

As mentioned above, Cache manager is the core of Spring Cache. Spring Data Redis has its own cache manager RedisCacheManager. The following two Spring Data Redis configuration methods are provided:

@ Configuration @ EnableCaching @ ComponentScan (basePackageClasses = {RedisCacheService. class, CacheDao. class}) public class Config {/* Redis connection factory */@ Bean (name = "redisConnectionFactory") public region JedisConnectionFactory () {jedisConnectionFactory JedisConnectionFactory = new jedisConnectionFactory (); JedisConnectionFactory. setHostName ("127.0.0.1"); jedisConnectionFactory. setPort (6379); jedisConnectionFactory. setPassword ("foobared"); jedisConnectionFactory. response (); return response;}/* RedisTemplate */@ Bean (name = "redisTemplate") public RedisTemplate <String, Object> redisTemplate (RedisConnectionFactory redisConnectionFactory) {RedisTemplate <String, object> redisTemplate = new RedisTemplate <String, Object> (); redisTemplate. setConnectionFactory (redisConnectionFactory); redisTemplate. afterPropertiesSet (); redisTemplate. setKeySerializer (new StringRedisSerializer (); redisTemplate. setValueSerializer (new JdkSerializationRedisSerializer (); redisTemplate. setHashKeySerializer (new StringRedisSerializer (); return redisTemplate;}/* Redis cache manager */@ Bean (name = "cacheManager") public CacheManager cacheManager (RedisTemplate redisTemplate) {return new RedisCacheManager (redisTemplate );}}Java-based configuration class <! -- Connection factory --> <bean id = "redisConnectionFactory" class = "org. springframework. data. redis. connection. jedis. jedisConnectionFactory "> <property name =" hostName "value =" $ {redis. hostName} "/> <property name =" port "value =" $ {redis. port} "/> <property name =" password "value =" $ {redis. password} "/> </bean> <! -- RedisTemplate --> <bean id = "redisTemplate" class = "org. springframework. data. redis. core. redisTemplate "> <property name =" connectionFactory "ref =" redisConnectionFactory "/> </bean> <! -- CacheManager --> <bean id = "cacheManager" class = "org. springframework. data. redis. cache. redisCacheManager "> <constructor-arg ref =" redisTemplate "/> </bean>Serializer Based on applicationContext. xml5, key, and value

When an entry is stored in Redis key-value storage, both key and value are serialized using the Redis serializer. Spring Data Redis provides multiple such serializer, including:

  • GenericToStringSerializer: Use Spring conversion service for serialization;
  • JacksonJsonRedisSerializer: use Jackson 1 to serialize the object to JSON;
  • Jackson2JsonRedisSerializer: use Jackson 2 to serialize the object to JSON;
  • JdkSerializationRedisSerializer: use Java for serialization;
  • OxmSerializer: Use the Spring O/X ing orchestrator and unmarshaler to implement serialization for XML serialization;
  • StringRedisSerializer: serializes keys and values of the String type.

RedisTemplate uses JdkSerializationRedisSerializer, which means that both the key and value are serialized through Java. StringRedisTemplate uses StringRedisSerializer by default.

The serialized storage of keys and values of RedisTemplate may surprise you, as shown below:

This is normal, because java serialization is used. If you want to look comfortable, you can use the StringRedisSerializer sequence to look like a string.

6. API

Spring Data Redis provides a set of API-friendly operations for Redis, as shown below:

I will not elaborate on the operations on Redis. For details, refer to the exercises I have made when studying this aspect, as well as some supplements to the previous content. It is still detailed! Https://github.com/JMCuixy/SpringRedisData

Iv. Conclusion

It's so cold in winter! No heating ~~

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.