Using spring Data redis operations Redis (i)

Source: Internet
Author: User

The Spring-data-redis Project (SDR) provides a higher level of abstraction for Redis's Key-value data store operations, similar to the spring framework for JDBC support.

Project home: http://projects.spring.io/spring-data-redis/

Project Document: http://docs.spring.io/spring-data/redis/docs/1.5.0.RELEASE/reference/html/

This article mainly introduces the actual use of spring Data Redis.

New features of 1.Spring Data Redis 1.5

Added the Redis hyperloglog command pfadd,pfcount,pfmerge

You can use Jackson to serialize Java types based on Redisserializer

Configuring a Redis Sentinel connection using Propertysource, currently only Jedis client support


2.Spring Data Redis?

Spring Data Redis makes it easier to read and write Redis databases in spring applications.

Spring Data Redis provides the integration of four Redis service Java client packages, namely Jedis, Jredis, SRP and lettuce


3. Version requirements

Spring Data redis1.2.x requires jdk1.6+,spring framwork3.2.8+

Key-value Storage Services Redis 2.6.x+


4. Build the Environment

This article assumes that the Redis service has been installed and is running successfully.

To create a MAVEN project and add dependent jars, this article mainly uses the Jedis

<dependency><groupid>org.springframework.data</groupid><artifactid>spring-data-redis </artifactId><version>1.5.0.RELEASE</version></dependency>
<dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId>< Version>2.6.2</version></dependency>


5. Connect to Redis Service


In spring Data Redis connections are obtained through the redisconnection and Redisconnectionfactory classes in the Org.springframework.data.redis.connection package.

5.1 Configuring Jedisconnectionfactory

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:p= "http://www.springframework.org/schema/p" xsi: schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans.xsd "> <bean id=" jedisconnectionfactory "class=" Org.springframework.data.redis.connection.jedis.JedisConnectionFactory "p:host-name=" Server "p:port=" 6379 "/> </beans>


5.2 Configuration Jredis,srp,lettuce configuration is similar to the above configuration, only need to configure the corresponding Redisconnectionfactory interface implementation interface, it is located in the following package:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/5C/25/wKioL1Ubt1_QGYshAACQYxKlF9c690.jpg "title=" Connection-factory.png "alt=" Wkiol1ubt1_qgyshaacqyxklf9c690.jpg "/>


5.3 About Redisconnectionfactory attention issues

The above four connectors do not all support all of Redis's features, they are different, if the calling method is not supported in the connection API, then throws "Unsupportedoperationexception" exception, the specific need to understand the corresponding Redis Implementation of the Java client jar.


5.4 About Redis Sentinel (temporarily known as Sentinel) support

The Redis Sentinel Monitoring Master Service, when the primary service fails, is able to switch to the slave service, which will be upgraded from the service to the primary service to ensure failure recovery. Using this feature requires setting the Redissentinelconfiguration property in Jedisconnectionfactory, which is currently supported by Jedis for Redis Sentinel.


The encoding is as follows:

Public Redisconnectionfactory jedisconnectionfactory () {redissentinelconfiguration sentinelconfig = new  Redissentinelconfiguration (). Master ("MyMaster"). Sentinel ("127.0.0.1", 26379). Sentinel ("127.0.0.1", 26380); return new Jedisconnectionfactory (sentinelconfig);}


Configure in the Spring container:

<bean id= "Sentinelconfig" class= "Org.springframework.data.redis.connection.RedisSentinelConfiguration" > <constructor-arg name= "Master" value= "MyMaster"/><constructor-arg name= "Sentinelhostandports" ><set ><value>192.168.88.153:26379</value><value>192.168.88.153:26380</value><value >192.168.88.153:26382</value></set></constructor-arg></bean><bean id= " Jedisconnectionfactory "class=" Org.springframework.data.redis.connection.jedis.JedisConnectionFactory ">< Constructor-arg ref= "Sentinelconfig"/></bean>


Note : Be aware of using externally accessible IP addresses when configuring Redis's sentinel.conf files because when the Redis-sentinel service and Redis-server are on the same machine, the primary service IP becomes 127.0 in the configuration file when the primary service changes. 0.1 so that the external is not Access to the law. If the application, the Redis service on the same machine does not exist such a hidden danger, the situation is more practical network environment.


Once configured, after instantiating jedisconnectionfactory, the following log is visible:

2015-4-1 17:29:30 redis.clients.jedis.JedisSentinelPool initsentinels Info: Trying to find master from available Sentinels. .2015-4-1 17:29:30 Redis.clients.jedis.JedisSentinelPool initsentinels info: Redis Master running at 192.168.88.153:6384, Starting Sentinel listeners ... 2015-4-1 17:29:30 redis.clients.jedis.JedisSentinelPool initpool info: Created jedispool to master at 192.168.88.153:6384

The Redis instance 192.168.88.153:6384 in the experimental environment is the primary service.

5.5 Following a set of code to show the specific use

@FixMethodOrder (methodsorters.name_ascending) public class testjedis {public static  Applicationcontext ctx;public static jedisconnectionfactory jedisconnetionfactory;public  JedisConnection jedisConnection; @SuppressWarnings ("unchecked") @BeforeClasspublic  static  Void setbeforeclass ()  {ctx = new classpathxmlapplicationcontext ("Spring-redis.xml"); jedisconnetionfactory =  (jedisconnectionfactory)  ctx.getbean ("Jedisconnectionfactory");} @Beforepublic  void setbefore ()  {jedisconnection = jedisconnetionfactory.getconnection ();} @Afterpublic  void setafter ()  {jedisconnection.close ();} Private void print (collection<redisserver> c)  {for  (iterator<redisserver>  iter = c.iterator ();  iter.hasnext ();)  {RedisServer rs =  (redisserver)  iter.next (); System.out.println (Rs.gethost ()  +&nbSP; ":"  + rs.getport ());}}   Simple test Jedisconnection@ignore@testpublic void test1 ()  {if  (!jedisconnection.exists ( New string ("zz"). GetBytes ()))  {jedisconnection.set (new string ("zz"). GetBytes (), new string ( "ZZ"). GetBytes ());}} @Ignore @testpublic void test2 ()  {set<byte[]> keys = jedisconnection.keys ( New string ("*"). GetBytes ());for  (Iterator<byte[]> iter = keys.iterator ();  Iter.hasnext ();)  {system.out.println (new string (Iter.next ()));}}   Test SENTINEL@IGNORE@TESTPUBLIC&NBSP;VOID&NBSP;TEST3 ()  throws interruptedexception {if   (Jedisconnetionfactory.getsentinelconnection (). IsOpen ())  {collection<redisserver> c  = jedisconnetionfactory.getsentinelconnection (). Masters ();p rint (c); Redisnode rn = new redisnode ("192.168.88.153",  6380); Rn.setname ("MyMaster"); c =  jedisconnetionfactory.getsentiNelconnection (). Slaves (RN);p rint (c);} for  (int i = 0; i < 1000; i++)  {jedisconnection.set (new  String ("K"  + i). GetBytes (),  new string ("V" + i). GetBytes ()); Thread.Sleep (1000);} Set<byte[]> keys = jedisconnection.keys (new string ("k*"). GetBytes ()); Assert.assertequals (1000, keys.size ());}}


6.RedisTemplate Support


Familiar with the spring JdbcTemplate object, should probably be able to guess the role of redistemplate, Redistemplate object to redisconnection encapsulation, it provides connection management, serialization and other functions, It provides a higher level of abstraction for redis interactions. The operation view of the Redis operation commands is also provided, which greatly facilitates and simplifies the operation of Redis.


The following table is an introduction to the specific Operation view interface classes:

Key type operation
Valueoperations Redis String/value Operations
Listoperations Redis List Operations
Setoperations Redis Set operation
Zsetoperations Redis Sort Set operation
Hashoperations Redis Hash Operations
Value constraint operation
Boundvalueoperations Redis string/value Key Constraint
Boundlistoperations Redis List Key Constraint
Boundsetoperations Redis Set Key Constraint
Boundzsetoperations Redis Sort Set Key constraint
Boundhashoperations Redis Hash Key Constraint

The corresponding default implementation of the interfaces in the table is provided in the Org.springframework.data.redis.core package.


6.1RedisSerializer

Spring Data Redis provides a serial number for Key-value, which is implemented by default using the Redistemplate object Jdkserializationredisserializer. Other serialization implementations are provided, such as: Jackson2jsonredisserializer,jacksonjsonredisserializer,generictostringserializer, Stringredisserializer,oxmserializer.

In addition, users can provide their own serialization implementation

6.2 Configuring Redistemplate

<bean id= "Redistemplate" class= "Org.springframework.data.redis.core.RedisTemplate" p:connection-factory-ref= " Jedisconnectionfactory "/><bean id=" stringredistemplate "class=" Org.springframework.data.redis.core.StringRedisTemplate "><property name=" ConnectionFactory "ref=" Jedisconnectionfactory "/></bean>


The Redistemplate and Stringredistemplate are configured here, except that the Key-value serialization of Stringredistemplate uses Stringredisserializer. The results after using Stringredistemplate to operate Redis are read-friendly.

In addition to the hash type, there is also a corresponding HashKey serialization (which corresponds to the field name of the hash type).


Use of 6.3RedisTemplate

  Test Redistemplate, handle the readability of key independently (String serial number) @Ignore @testpublic void test4 ()  {string key  =  "Spring"; Listoperations<string, string> lop = redistemplate.opsforlist (); Redisserializer<string> serializer = new stringredisserializer (); Redistemplate.setkeyserializer (serializer); Redistemplate.setvalueserializer (serializer);//  Rt.setdefaultserializer (serializer), Lop.leftpush (key,  "AAA"), Lop.leftpush (key,  "BBB"); long size  = lop.size (key);  // rt.boundlistops (key). Size (); Assert.assertequals (2, size);}   Test Convenience Object Stringredistemplate@ignore@testpublic void test5 ()  {valueoperations<string,  string> vop = stringredistemplate.opsforvalue (); string key =  "String_redis_template"; string v =  "Use stringredistemplate set k v"; Vop.set (KEY,&NBSP;V); String value = vop.get (key); TheErt.assertequals (V, value);} 

Using that serialization strategy is a tradeoff for more stored key-value content.


The Rediscallback callback interface is used to obtain the redisconnection through the parameters of the method in Redistemplate, and further operations on Redis, such as transaction control. It is important to note that if you use Stringredistemplate, the Stringredisconnection object is returned.


Test the Rediscallback code example:

Test callback@ignore@testpublic void test61 () {Long dbsize = (long) stringredistemplate.execute (new rediscallback< Object> () {@Overridepublic Long Doinredis (redisconnection connection) throws DataAccessException { Stringredisconnection stringredisconnection= (stringredisconnection) Connection;return Stringredisconnection.dbsize ();}}); System.out.println ("dbsize:" + dbsize);}

Test the Sessioncallback code example:

@Testpublic void test62 () {list<object> Txresult = Stringredistemplate.execute (New sessioncallback<list< Object>> () {@Overridepublic list<object> execute (redisoperations operations) throws DataAccessException { Operations.multi (); Operations.opsforhash (). Put ("Hkey", "Multikey4", "Multivalue4"), Operations.opsforhash (). Get (" Hkey "," K1 "); return operations.exec ();}}); for (Object O:txresult) {System.out.println (o);/** * 0. false/true * 1. V1/}}

Description

    • The operation returned in the transaction is NULL, so the result of the operation cannot be processed in execute. For example here get ("hkey", "K1") results.

    • The hash operation returns false if the field exists (0 in Redis), no return True (1 in Redis) and whether the value corresponding to the field is updated without association.

    • The Exec () method returns the return result of each command executed in the corresponding transaction for the object in list<object>.


7. Execute the LUA script

Implementing LUA script development ideas in Redis: http://aiilive.blog.51cto.com/1925756/1626372

The implementation of LUA scripts in Spring Data Redis is more convenient, and the following example shows the use of Redistemplate objects to execute LUA scripts.

  Test Lua Script @ignore@testpublic void test71 ()  {list<string> keys = new  ArrayList<String> (); Redisscript<long> script = new defaultredisscript<long> ("local size  = redis.call (' dbsize '); return size; ",  long.class); Long dbsize = stringredistemplate.execute (script, keys, new object[] {}); System.out.println ("SHA1:" &NBSP;+&NBSP;SCRIPT.GETSHA1 ()); System.out.println ("Lua:"  + script.getscriptasstring ()); System.out.println ("dbsize:"  + dbsize);} @Testpublic  void test72 ()  {DefaultRedisScript<Boolean> script = new  Defaultredisscript<boolean> ();/** * isexistskey.lua content is as follows: *  * return  Tonumber (Redis.call ("exists", Keys[1])  == 1; */script.setscriptsource (new  Resourcescriptsource (New classpathresource ("/isexistskey.lua")); Script.setresulTtype (Boolean.class);// must setsystem.out.println ("Script:"  + script.getscriptasstring ()) ; Boolean isexist = stringredistemplate.execute (Script,collections.singletonlist ("K2"),  new  object[] {}); Assert.asserttrue (isexist);}


8. Support class operation

A variety of reusable components are available in the Org.springframework.data.redis.support package that can be applied to redis storage, such as atomic Count, JDK collection, type collection of Redis (Redislist, Redisset, etc.)

<redis:collection id= "springlist" key= "springlist" template= "Stringredistemplate" type= "LIST"/>

@Ignore @testpublic void Test8 () {Redisatomicinteger rai = new Redisatomicinteger ("Redis:atomic", jedisconnetionfactory ); System.out.println (Rai.get ());} Test Redis collection@ignore@testpublic void Test9 () {@SuppressWarnings ("unchecked") redislist<string> Redislist = (redislist<string>) ctx.getbean ("Springlist"); Redislist.clear (); Redislist.addfirst ("China"); Redislist.add ("in"); Redislist.add ("Go"); Redislist.addlast ("made"); System.out.println (Redislist.getkey ());}

This article from "Mustang Red" blog, reproduced please contact the author!

Using spring Data redis operations Redis (i)

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.