JAVA Framework Spring Cache for Redis.

Source: Internet
Author: User
Tags value store

I. Overview

The cache (Caching) can store information that is often used so that it is immediately available every time it is needed.

Common Cache Database:

Redis uses memory storage (in-memory) for non-relational databases, strings, lists, collections, hash lists, ordered collections, and each data type has its own exclusive commands. There are also bulk operations (bulk operation) and incomplete (partial) transactional support, publishing and subscriptions, master-slave Replication (master/slave replication), persistence, scripting (stored procedures, stored procedure). Efficiency is lower than ehcache, much faster than database, processing cluster and distributed cache is convenient, has mature scheme. Redis is recommended for large systems where cache sharing, distributed deployment, and cache content are large.
memcached uses memory-stored key-value caches, mappings between key values, create commands, read commands, update commands, delete commands, and several other commands. Multi-threaded server for performance improvement. Memcache implements distributed caching in the client, specifying the node of the target data through the distributed algorithm.

Ehcache Pure Java implementation, slow in memory, can be persisted to the hard disk, the efficiency is higher than memcache, but the cache sharing trouble, the cluster distributed application is inconvenient. If it is a single application or a high-demand application for cache access, use Ehcache. Ehcache also has a cache sharing scheme, but the broadcast cache notification update through RMI or Jgroup multicast, the cache sharing is complex, the maintenance is inconvenient; simple sharing is possible, but it involves cache recovery, big data caching is not appropriate.

Second, Spring Cache

The implementation of the spring cache is done by creating a facet (aspect) and triggering a pointcut (pointcut) of the spring cache annotations. Depending on the annotations used and the state of the cache, this slice fetches the data from the cache, adds the data to the cache, or removes a value from the cache. Spring can be integrated with several popular cache implementations, with the following steps:

1. Enable support for caching
    • Java Configuration Note Driver cache

[Email protected]

    • Caching of XML declarations

----<cache:annotation-driven>

2. Cache Manager

The cache Manager is the core of spring cache abstraction, which integrates with several popular cache implementations. Spring3.1 is configured with five cache manager implementations:

    • Simplecachemanager
    • Noopcachemanager
    • Concurrentmapcachemanager (its cache storage is memory-based, so its lifecycle is associated with the application, which may not be the ideal choice for enterprise-class applications at the production level)
    • Compositecachemanager (System integrates with multiple cache managers simultaneously)
    • Ehcachecachemanager

In addition to the core spring framework, spring data provides two cache managers:

    • Rediscachemanager
    • Gemfirecachemanager
3. Add annotations to the method to support caching

Spring provides four annotations to declare a cache rule:

The @Cacheable will conditionally trigger a call to the method, depending on whether the desired value is already in the cache.
@CachePut has adopted a more straightforward process. A method with @cacheput annotations is always called, and its return value is placed in the cache.

@Cacheable and @CachePut Some common attributes:

The Value:value property must be specified, which means that the return value of the current method is cached on which cache, corresponding to the name of the cache. The main function is to give the cache a name! Personally, the main purpose of the spring container is to better manage the cache object.

Condition: Before calling the method: if the value of the Spel expression is false, the cache will not go away.

After calling the method: if the value of the Spel expression is false, the return value will not be placed in the cache.

Unless: Before calling the method: regardless of whether the value of Spel is true or FALSE, the cache is searched for the corresponding value, and the corresponding value is returned if found. Execute the method if it is not found.

After calling the method: if the value of the Spel expression is true, the return value will not be placed in the cache.

Key: The value of the specified key is the value of the key we want to save to the cache database, but the key designation has its own set of methods, as follows:

Also, it should be noted that #result cannot be used on @cacheable because #result represents the cached value of a method call. However, @cacheable may not take the method and may not have a return value. So it's not very useful. But! But! #result can be used on the unless property of @cacheable, because unless is judged when the method returns, so there must be a return value!

@CacheEvict Some properties that specify which cache number should be removed:

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

@Cacheing

@Caching annotations Let us specify multiple spring cache related annotations on a method or class, with attributes: cacheable, put, evict.

@Caching ([Email protected]acheable ("users"), evict={@CacheEvict ("Cache2"), @CacheEvict (value= "Cache3", allentries= True)})
Third, Spring Data Redis

Spring Data Redis contains a number of template implementations to complete the data access capabilities of the Redis database.

1. Add dependencies
    <Dependency><GroupId>org.springframework.data</GroupId><Artifactid>spring-data-redis</Artifactid><Version>1.8.7.release</Version></Dependency><Dependency> <groupid< span data-filtered= "Filtered" >>redis.clients</ groupid> << span data-filtered= "Filtered" >artifactid>jedis </artifactid> <version> 2.9.0</version > </dependency >             
2.Redis Connection Factory

In order to create a template for spring Data Redis, we first need to have a Redis connection factory. Spring Data Redis provides four connection factories for our selection (these connection factories are the same for all applications):

    • Jedisconnectionfactory
    • Jredisconnectionfactory
    • Lettuceconnectionfactory
    • Srpconnectionfactory

3. redistemplate and stringredistemplate

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

    • Redistemplate
    • Stringredistemplate

Redistemplate supports the object type of key and value of type object. Stringredistemplate, however, takes a much simpler and more brutal approach, supporting only string-type keys and string-type value.

4. Cache Manager

As mentioned above, the cache manager is the core of spring cache. Spring Data Redis has its own cache manager Rediscachemanager, which gives the following two ways to configure spring data redis:

@Configuration @enablecaching@componentscan (basepackageclasses = {Rediscacheservice.Class, Cachedao.Class})PublicClassConfig {/*Redis Connection Factory*/@Bean (name = "Redisconnectionfactory")PublicJedisconnectionfactory jedisconnectionfactory () {Jedisconnectionfactory jedisconnectionfactory =NewJedisconnectionfactory (); Jedisconnectionfactory.sethostname ("127.0.0.1"); Jedisconnectionfactory.setport (6379); Jedisconnectionfactory.setpassword ("foobared"); Jedisconnectionfactory.afterpropertiesset ();ReturnJedisconnectionfactory; }/*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 */< span data-filtered= "filtered" > @Bean (name = "CacheManager" ) public CacheManager CacheManager (redistemplate redistemplate) {return new Rediscachemanager (redistemplate); }} 
    <!--Connection Factory-<BeanId= "Redisconnectionfactory"Class= "Org.springframework.data.redis.connection.jedis.JedisConnectionFactory"><PropertyName= "HostName"Value= "${redis.hostname}"/><PropertyName= "Port"Value= "${redis.port}"/><PropertyName= "Password"Value= "${redis.password}"/></Bean><!--Redistemplate-<BeanId= "Redistemplate"Class= "Org.springframework.data.redis.core.RedisTemplate"><PropertyName= "ConnectionFactory"Ref= "Redisconnectionfactory"/></bean> span data-filtered= "Filtered" ><!--cachemanager --<bean id< span data-filtered= "Filtered" >= "CacheManager"  class = "Org.springframework.data.redis.cache.RedisCacheManager"  > <constructor-arg ref= "Redistemplate" /> </bean< span data-filtered= "filtered" >>            
5. Serializer for key and value

When an entry is saved to the Redis Key-value store, both key and value are serialized using the Redis Serializer (serializer). Spring Data Redis provides a number of such serializers, including:

    • Generictostringserializer: Serialization using the Spring transformation service;
    • Jacksonjsonredisserializer: Using Jackson 1, serialize the object to JSON;
    • Jackson2jsonredisserializer: Using Jackson 2, serialize the object to JSON;
    • Jdkserializationredisserializer: Using Java serialization;
    • Oxmserializer: Serialization for XML Serialization using the Spring o/x mapped orchestration and (marshaler and Unmarshaler);
    • Stringredisserializer: Serializes a String type key and value.

Redistemplate uses Jdkserializationredisserializer, which means that both key and value are serialized through Java. Stringredistemplate will use Stringredisserializer by default.

Redistemplate's key and value are serialized storage and may make you feel strange, similar to the following:

This is normal, because the use of Java serialization, if you want to look more comfortable, you can use the Stringredisserializer sequence into a string look.

6. API

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

The operation of the Redis is not to say, the concrete can see I learn the content of the relevant exercises, but also includes some of the previous content of the supplement. Write it in detail! Https://github.com/JMCuixy/SpringRedisData

Iv. Conclusion

JAVA Framework Spring Cache for Redis.

Related Article

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.