Spring Data Redis Understanding

Source: Internet
Author: User
Tags serialization value store

Preface Spring Data Redis Project,the spring concept was applied to develop a solution for data storage using key-value forms。 We (officially) provide a "Template", this is a high-level abstraction to send and receive messages. You're going to notice it.support for JDBC with the spring framework is somewhat similar。 Why choose Spring Data Redis? Spring Framework is the all-stack Java/jee application framework that leads the trend. It provides a lightweight container, a non-intrusive programming model that is opened by dependency injection, AOP, and portable service abstraction.SDR framework makes it easy to store with Redis key values,eliminates cumbersome and redundant tasks and rigid code(refers to getting connections, freeing resources). Requirements
    • The SDR 1.x requires JDK 6.0 and above , requiring the spring frame to be 4.3.9.RELEASE and above .
    • Redis 2.6.x and above . On the connectors side, Spring Redis integrates the Jedis
Connect to Redis

The first step in using Redis and spring is to connect to the storage through the IOC container. To implement a connection, a Java connector (or binding) is required. Whatever library you choose, there is only one set of SDR APIs called the Org.springframework.data.redis.connection package, and redisconnection and Redisconnectionfactory interface to obtain an active connection to Redis.

Redisconnection and RedisconnectionfactoryredisconnectionProvides a building block for redis communication that willhandling communication with the Redis backend。 will alsoautomatically translates exceptions from the underlying connection library into spring's consistent DAO exception level, so the user is free to switch connectors without having to modify the code.

Note: For cases where the native Library API is required, Redisconnection provides a proprietary method Getnativeconnection -Returns the native, underlying object used for communication.
the active redicconnection is created by Redisconnectionfactory . In addition, the factory has played a persistenceexceptiontranslator, which means that once declared, they allow the user to make a transparent exception translation. For example, by using @repository and AOP for exception translation. For more information, see the related sections of the spring framework.
Note: Depending on the underlying configuration, the factory returns a new connection or an existing connection (when using pool or shared native connection).
The simplest way to use redisconnectionfactory is to configure the appropriate connector through the IOC containerand inject it into the usage class.
Important: Unfortunately, not all connector are currently supported for all Redis features. Unsupportedoperationexception is thrown when an API that is not supported by the underlying library is called. This situation may be resolved in the future, depending on the maturity of the different connector.

Configuring Jedis connector1.xml Configuration
<id= "Jedisconnectionfactory"                class= " Org.springframework.data.redis.connection.jedis.JedisConnectionFactory "/>
2.java Code Configuration
@Bean  Public jedisconnectionfactory jedisconnectionfactory () {    returnnew  Jedisconnectionfactory ();}
Redis Sentinel support to work with highly available redis, you can use Redissentinelconfiguration to support Redis Sentinel.

Note: Currently, only Jedis and lettuce support Redis Sentinel.

/*** Jedis*/@Bean Publicredisconnectionfactory jedisconnectionfactory () {redissentinelconfiguration sentinelconfig=NewRedissentinelconfiguration (). Master ("MyMaster"). Sentinel ("127.0.0.1", 26379). Sentinel ("127.0.0.1", 26380); return Newjedisconnectionfactory (sentinelconfig);}/*** Lettuce*/@Bean Publicredisconnectionfactory lettuceconnectionfactory () {redissentinelconfiguration sentinelconfig=NewRedissentinelconfiguration (). Master ("MyMaster"). Sentinel ("127.0.0.1", 26379). Sentinel ("127.0.0.1", 26380); return Newlettuceconnectionfactory (sentinelconfig);}
Redissentinelconfiguration can also be defined by Propertysource.
    • spring.redis.sentinel.master: The name of the master node
    • spring.redis.sentinel.nodes: comma-separated list of Host:port

Sometimes, you need to interact directly with one of the Sentinels. Using redisconnectionfactory.getsentinelconnection () or redisconnection.getsentinelcommands (), Allows you to access Sentinel for the first activity.

Using the Redistemplate operation objects most users will prefer to useredistemplateand the corresponding package Org.springframework.data.redis.core, the template is the central class of the Redis module--Due to the rich feature set. The template provides a high level of abstraction for redis interactions. When Redisconnection provides a low-level way to accept and return binary values (byte arrays), the template is responsible for serialization and connection management, freeing the user from the details here. More, the template provides an operation view (following the grouping from Redis commandReference)--provides a rich interface to manipulate specific types or specific keys (via the Keybound Interface), as follows:
Table 1. Operational views
Interface Description

Key Type Operations

Valueoperations

Redis string (or value) operations

Listoperations

Redis list operations

Setoperations

Redis Set operations

Zsetoperations

Redis zset (or sorted set) operations

Hashoperations

Redis Hash operations

Hyperloglogoperations

Redis Hyperloglog operations like (Pfadd, Pfcount,...)

Geooperations

Redis Geospatial Operations like GEOADD , GEORADIUS ,...)

Key Bound Operations

Boundvalueoperations

Redis string (or value) key bound operations

Boundlistoperations

Redis list key bound operations

Boundsetoperations

Redis Set key bound operations

Boundzsetoperations

Redis zset (or sorted set) key bound operations

Boundhashoperations

Redis Hash key bound operations

Boundgeooperations

Redis key bound geospatial Operations.

once configured, the template is thread-safe and can be reused by multiple instances. Out of the box, Redistemplate uses a Java-based serializer for most operations. This means thatany object read/written by the template is serialized/deserialized via Java。 The template's serialization mechanism can be easily modified, and the Redis module provides several implementations in the Org.springframework.data.redis.serializer package. You can also let redistemplate use a native byte array without using a serializer, simplyEnabledefaultserializerSet to False. Note that the template requires that all keys cannot be null, but value can be null-as long as the underlying serializer accepts it, and more, see the Javadoc of each serializer. When a specific template view is required, the view is declared as dependent and injected into the template: The container automatically performs the conversion:
<BeanID= "Jedisconnectionfactory"class= "Org.springframework.data.redis.connection.jedis.JedisConnectionFactory"P:use-pool= "true"/>    <!--redis Template Definition -    <BeanID= "Redistemplate"class= "Org.springframework.data.redis.core.RedisTemplate"P:connection-factory-ref= "Jedisconnectionfactory"/>
 Public classExample {//inject the actual template@AutowiredPrivate redistemplate<string, string> template; //inject the template as listoperations--automatic conversion    @Resource (name= "redistemplate")PrivateListoperations<string, string>Listops;  Public voidAddlink (String userid, url url) {listops.leftpush (userid, Url.toexternalform ()); }}
Convenient class for focusing on string

Given the common use of java.lang.String as a key/value store to Redis, the Redis module also provides two extensions for redisconnection and redistemplate: Stringredisconnection(as well as its defaultstringredisconnection implementations) and Stringredistemplate. In addition, the template and the connection, the bottom uses the stringredisserializer.

 <  bean  id  = "Jedisconnectionfactory"   class  = "Org.springframework.data.redis.connection.jedis.JedisConnectionFactory"  Span style= "COLOR: #ff0000" > P:use-pool  = "true"  />  <  bean  id  =" Stringredistemplate "  class  = "org.springframework.data.redis.core.StringRedisTemplate"   p:connection-factory-ref  =" Jedisconnectionfactory " 
   
    />  
   
 Public class Example {    @Autowired    private  stringredistemplate redistemplate;          Public void Addlink (String userId, url url) {        redistemplate.opsforlist (). Leftpush (UserID, Url.toexternalform ());}    } 

Like other spring template,redistemplate and stringredistemplate, developers are allowed to talk directly to Redis via the Rediscallback interface . This gives the developer complete control, because it is directly interacting with the Redisconnection . Note that when Stringredistemplate is used, the callback receives a stringredisconnection instance.

 Public void Usecallback () {    redistemplate.execute(new rediscallback<object>() {         publicthrows  dataaccessexception {            = connection.dbsize ();             // Can cast to Stringredisconnection if using a stringredistemplate            ((stringredisconnection) connection). Set ("Key", "value");        }    );
Serializer serializersFrom a framework perspective, the data stored in Redis is bytes. However, Redis natively supports different types, and more often these refer to the way data is stored, rather than its representation. The user determines whether the information needs to be turned into a string or other object. in SDR, the conversion between the user's type and the native type is done through the Redisserializer interface , which, as the name implies, is responsible for the serialization process. SDR provides multiple out-of-the-box implementations, of which two have been mentioned above:Stringredisserializer and jdkserializationredisserializer. However, users can also use Oxmserializer to process object/xml mappings-supported by spring 3OXM, or, using jacksonjsonredisserializer, Jackson2jsonredisserializer, or Genericjackson2jsonredisserializer to implement JSON-formatted storage.
Note that the storage format is not limited to values, it can be used for keys, values, hashes, and no restrictions . In a hash-mapped redis, data can be stored using a different structure. You already know Jackson2jsonredisserializer can turn objects into JSON format. JSON can be stored using strings. By using Redis hashes, you can implement a more complex mapping of structured objects. SDR provides different strategies for mapping data into hashes-depending on usage:
    1. Use Hashoperations and a serializer to map directly.
    2. Use Redis repositories.
    3. Use Hashmapper and hashoperations.

Spring Data Redis Understanding

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.