spring-Integrated Redis

Source: Internet
Author: User
Tags serialization

Redis is a non-relational database of Key-value storage. Spring Data Redis contains a number of template implementations to complete the data access capabilities of the Redis database

1. How do I connect to Redis?

Spring Data Redis provides a jedisconnectfactory connection factory (more than this one)

class= "Org.springframework.data.redis.connection.jedis.JedisConnectionFactory" >      <property Name= "HostName" value= "192.168.1.106" ></property></bean>

2. Using templates

Spring Data Redis provides redistemplate and stringredistemplate templates. The template encapsulates the Redis operations and provides a higher level of data access scenarios. As you can see from the name, the latter only focuses on string types, and it is recommended to use Stringredistemplate when Redis key and value are strings.

Many of the features of Redistemplate are provided in the form of sub-APIs that differentiate between a single value and a set value scenario.

 PackageCom.cn.util;Importorg.springframework.beans.factory.annotation.Autowired;Importorg.springframework.data.redis.core.RedisTemplate;Importorg.springframework.stereotype.Component;Importjava.util.List;ImportJava.util.Set; @Component Public classJedisutil {@Autowired private redistemplate<string, object>redistemplate; //string     Public voidsetstr (String key, Object value) {Redistemplate.opsforvalue (). Set (key, value); }     PublicObject getstr (String key) {returnRedistemplate.opsforvalue (). get (key); }    //List Collection     Public voidLpush (String key, Object value) {redistemplate.opsforlist (). Leftpush (key, value); }     PublicObject Lpop (String key) {returnredistemplate.opsforlist (). Leftpop (key); }     PublicList<object> Lrange (String key,LongStart,Longend) {        returnredistemplate.opsforlist (). Range (key, start, end); }    //Set Set     Public voidAddSet (string key, String value) {Redistemplate.opsforset (). Add (key, value); }     PublicSet<object>Getset (String key) {returnRedistemplate.opsforset (). Members (key); }    //Hash Set     Public voidHset (String key, String Key1, String value) {Redistemplate.opsforhash (). Put (key, key1, value); }     PublicObject hget (string key, String key1) {returnRedistemplate.opsforhash (). Get (key, key1); }     PublicSet<object>Getkeys (String key) {returnRedistemplate.opsforhash (). keys (key); }}

Test class

@RunWith (Springjunit4classrunner.class) @ContextConfiguration (Locations= {"Classpath:springMvc.xml", "Classpath:spring-source.xml"}) Public classjedisutiltest {@AutowiredPrivateJedisutil Jedisutil; @Test Public voidSetstr ()throwsException {jedisutil.setstr ("Shoudu", "Beijing"); } @Test Public voidGetstr ()throwsException {Object obj=jedisutil.getstr ("Shoudu");    System.out.println (obj); } @Test Public voidLpush ()throwsException {Jedisutil.lpush ("Testlist",NewUser ("II", "LL")); } @Test Public voidLpop ()throwsException {Object obj= Jedisutil.lpop ("Testlist");    System.out.println (obj); } @Test Public voidLrange ()throwsException {List<Object> List=jedisutil.lrange ("Testlist", 0,-1);    SYSTEM.OUT.PRINTLN (list); } @Test Public voidAddSet ()throwsException {jedisutil.addset ("Testset", "Jj2"); } @Test Public voidGetset ()throwsException {Object obj= Jedisutil.getset ("Testset");    System.out.println (obj); } @Test Public voidHset ()throwsException {jedisutil.hset ("Testhash", "name", "Liming"); } @Test Public voidHget ()throwsException {Object obj=jedisutil.hget ("Testhash", "name");    System.out.println (obj); } @Test Public voidGetkeys ()throwsException {Set<Object> Keys=jedisutil.getkeys ("Testhash");    System.out.println (keys); } @Test Public voidMuchops ()throwsexception{boundhashoperations<string, String, object> boundhashoperations=JedisUtil.redisTemplate.boundHashOps ("Testhash"); String Str=Boundhashoperations.getkey ();        System.out.println (str); Object obj=boundhashoperations.get ("name");        System.out.println (obj); boundvalueoperations. Put ("Age", 123); boundvalueoperations. Put ("School", "Beida"); Set<String> keys=Boundhashoperations.keys ();    System.out.println (keys); }}

The test method above tests only some of the methods of each Redis data type. Note that at the end of the Muchops () test method, Redistemplate provides a way to perform operations in the form of a binding key (which is a hash type key, a similar other type), and only one place in the entire method uses key, i.e. JedisUtil.redisTemplate.boundHashOps ("Testhash"), all operations performed on the returned boundvalueoperations will be applied to the key.

3. Serializer using key and value

When a key-value entry is saved to Redis storage, both key and value are serialized using the Redis serializer. Spring Date Redis provides a number of serializers:

1) Jdkserializationredisserializer:pojo object access scene, using the JDK itself serialization mechanism, the Pojo class through Objectinputstream/objectoutputstream to serialize operations , the byte sequence will be stored in the final redis-server. is currently the most commonly used serialization strategy.
2) Stringredisserializer:key or value is a string of scenes, according to the specified charset byte sequence of data encoded into string, is "new String (Bytes, CharSet)" and " String.getbytes (CharSet) "in the direct package. is the most lightweight and efficient strategy.
3) The Jacksonjsonredisserializer:jackson-json tool provides a conversion capability between JavaBean and JSON, which can be serialized into a JSON format in the Pojo instance and stored in Redis. You can also convert data in JSON format into Pojo instances. Because the Jackson tool needs to explicitly specify the class type when serializing and deserializing, this policy is a little more complex to encapsulate. "Requires JACKSON-MAPPER-ASL tool support"
4) Oxmserializer: Provides the ability to convert JavaBean to XML, and currently available three-party support including Jaxb,apache-xmlbeans;redis stored data will be XML tools. However, with this strategy, programming will be difficult and inefficient; not recommended. "Requires support for SPRING-OXM modules

    • The redistemplate needs to declare 4 kinds of serializer, the default is "Jdkserializationredisserializer":

A) Keyserializer: For normal k-v operation, Key takes a serialization strategy
b) Serialization strategy adopted by Valueserializer:value
c) Hashkeyserializer: In the hash data structure, Hash-key's serialization strategy
d) serialization strategy for Hashvalueserializer:hash-value

    • Stringredistemplate also need to declare 4 in the serializer, but the default is "Stringredisserializer", you can see the source of Stringredistemplate class:
 PackageOrg.springframework.data.redis.core;Importorg.springframework.data.redis.connection.DefaultStringRedisConnection;Importorg.springframework.data.redis.connection.RedisConnection;Importorg.springframework.data.redis.connection.RedisConnectionFactory;ImportOrg.springframework.data.redis.serializer.RedisSerializer;ImportOrg.springframework.data.redis.serializer.StringRedisSerializer; Public classStringredistemplateextendsRedistemplate<string, string> {     Publicstringredistemplate () {Redisserializer<String> Stringserializer =NewStringredisserializer (); Stringredisserializer Sequencer This. Setkeyserializer (Stringserializer);  This. Setvalueserializer (Stringserializer);  This. Sethashkeyserializer (Stringserializer);  This. Sethashvalueserializer (Stringserializer); }     Publicstringredistemplate (redisconnectionfactory connectionfactory) { This();  This. Setconnectionfactory (ConnectionFactory);  This. Afterpropertiesset (); }    protectedRedisconnection preprocessconnection (redisconnection connection,Booleanexistingconnection) {        return Newdefaultstringredisconnection (connection); }}

spring-Integrated 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.