Getting Started with spring Redis

Source: Internet
Author: User
Tags redis server

Waiter, serving!!!

1. Installing the Redis service on a virtual machine

Download the tar package, wget http://download.redis.io/releases/redis-2.8.19.tar.gz.

Decompression, TAR-ZXVF redis-2.8.19.tar.gz

Go to Folder, CD redis-2.8.19/, compile, make

Create an empty folder to hold the Redis program, Mkdir/usr/local/redis

Copy the compiled product to the Redis folder in turn

1) After compiling the SRC folder

The red part of the file is copied in the past

CP Redis-benchmark/usr/local/redis

CP Redis-cli/usr/local/redis

CP Redis-server/usr/local/redis

2) Compile the folder under the

CP Redis.conf/usr/local/redis

After the great diversion, let's look at what the Redis program's folder looks like.

Cd/usr/local/redis

OK, everything is ready, only owe startup, now let us gently enter the start command:

./redis-server./redis.conf

Want to run in the background? Think the order is too annoying? Want to set up boot from boot? Then nohup...&, add the command to path and write it into rc.local.

Own Baidu Bar, here is not detailed.

Just now we are using the default way to start the server side, the default hostname is Localhost,port is 6379, you can also edit redis.conf change them.

OK, after the Redis server starts, let's use the client connection. Enter REDIS-CLI (default is 6379 port connected to localhost)

The keys command here means looking at what's currently in the Redis database.

We can simply enter a few Redis commands to test.

More commands, please visit, three Tatsu don't slip point degree Niang point Hôtel Come Inn. There is no detail here.

Note: The second part of Java is played in Windows, and to access the Linux host on the Redis, but also need to "back door", you need to do is in the Iptables configuration add 6379 as the firewall exception port, and restart the Iptables service.

Vi/etc/sysconf/iptables

Add some seasoning.

Service Iptables Restart

2. Writing of a Java program that accesses Redis

Here we directly write test cases, directly with Spring+junit on the line, do simple and generous on the line, extravagance and shame AH.

Brother Maven, come out and play.

The structure of the project is Jiangzi. The contents of each file are detailed below.

1) pom.xml

As the exclusive area for nanny Maven, it defines the package to use, with spring (including core, context), Junit,jedis and Spring-data-redis. Spring-data-redis is the spring on the Jedis based on the package again, let us use more cool.

Just go directly to the code that depends on the package.

    <Dependencies>        <!--JUnit -        <Dependency>            <groupId>Junit</groupId>            <Artifactid>Junit</Artifactid>            <version>4.11</version>        </Dependency>        <Dependency>            <groupId>Redis.clients</groupId>            <Artifactid>Jedis</Artifactid>            <version>2.1.0</version>        </Dependency>        <!--Spring -        <Dependency>            <groupId>Org.springframework</groupId>            <Artifactid>Spring-core</Artifactid>            <version>3.1.2.RELEASE</version>        </Dependency>        <Dependency>            <groupId>Org.springframework</groupId>            <Artifactid>Spring-context</Artifactid>            <version>3.1.2.RELEASE</version>        </Dependency>        <!--Spring Data Redis -        <Dependency>            <groupId>Org.springframework.data</groupId>            <Artifactid>Spring-data-redis</Artifactid>            <version>1.1.1.RELEASE</version>        </Dependency>    </Dependencies>

Not much to say, the nanny hurried to work. (Maven children's shoes: t_t You This bandwidth makes me have no language)

2) Spring-redis.xml

Spring XML, of course, is the configuration bean.

<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"Xmlns:context= "Http://www.springframework.org/schema/context"Xmlns:tx= "Http://www.springframework.org/schema/tx"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-2.5.xsd Http://www.springframework.org/schema/context Http://www.springframework.org/schema/co Ntext/spring-context-2.5.xsd Http://www.springframework.org/schema/tx Http://www.springframework.org/schema /tx/spring-tx-2.5.xsd ">    <Context:property-placeholder Location= "Classpath:redis.properties" />    <BeanID= "Jedisconnectionfactory"class= "Org.springframework.data.redis.connection.jedis.JedisConnectionFactory">        < Propertyname= "HostName"value= "${hostname}" />        < Propertyname= "Port"value= "${port}" />        < Propertyname= "Database"value= "${index}" />    </Bean>    <BeanID= "Redistemplate"class= "Org.springframework.data.redis.core.StringRedisTemplate">        < Propertyname= "ConnectionFactory"ref= "Jedisconnectionfactory" />    </Bean></Beans>

Here is a small trick, some basic configuration information I may not want to write into the XML, for the wool, because in the Linux under the VI editing format will be messy, a little neat I prefer to edit the properties file, the form of key=value easier to edit, the format will not be disorganized.

So? Use the property placeholder bar, configuration is super simple, to use a key when only need ${key} so write it.

Here we need to define two Spring-data-redis for us to encapsulate the object, one is Jedisconnectionfactory, is not a bit connected to the taste of the pool, such as the typical factory pattern, from connection Factory inside can get the Redis connection object, then use this connection object yy, then maybe lol ... , the other is Stringredistemplate object, and a bit jdbctemplate flavor, a typical template method pattern, through this object we can be crud, but JdbcTemplate is for the relational database , and this redistemplate is for the Redis non-relational database.

Note: Here's redistemplate we're not using the base class Redistemplate object (maybe some tutorial articles use it, if your redis already has strings as key/value data, then beware of errors), But its subclass stringredistemplate. In Redis, the most common use of a crud is string, such as a string as a key, as value, as HashMap key or value, while the base class Redistemplate the default serialization/ The deserialization operation (which uses the Jdkserializationredisserializer Class) is not for strings, more specifically, the serialization/deserialization tool inside the Redistemplate class for strings/ The result of processing the byte array is not the result we want. The serialization/deserialization tool inside the subclass Stringredistemplate is an instance of the Stringredisserializer class that we want, so we use the Stringredistemplate instance here. Interested children's shoes can try, if you are using an instance of the Redistemplate class, write to Redis, what kind of data will be written.

3) Redis.properties

Storage configuration information for Redis. In the 2nd also said, specific Redis server-side configuration information, we wrote in this file.

Hostname=192.168.1.225port=6379index=0

Like MySQL and other databases, a Redis service can also have multiple databases, redis default connection is the No. 0 library, the default has 16 databases, where the configuration index refers to the number of database, scope 0~15, if you want to expand capacity, please modify the redis.conf.

4) Redistest.java

It was finally the foot of the pig's foot. Let's look at the code first.

 Packagecode.selwyn.spring.redis.demo.test;ImportOrg.junit.Assert;ImportOrg.junit.Before;Importorg.junit.Test;ImportOrg.springframework.context.ApplicationContext;ImportOrg.springframework.context.support.ClassPathXmlApplicationContext;Importorg.springframework.data.redis.core.RedisTemplate;Importorg.springframework.data.redis.core.ValueOperations;/*** Class redistest * Play Redis * *@authorSelwyn * Date:mar, 7:15:57 PM*/ Public classRedistest {/*** * Spring config file*/    Private Final Staticstring[] Config_loc = {        "Spring-redis.xml"    }; PrivateApplicationContext AppContext =NULL; PrivateApplicationContext Getappcontext () {return NewClasspathxmlapplicationcontext (Config_loc); } @Before Public voidsetUp () {//read the spring configuration file, load into the spring context         This. AppContext = This. Getappcontext (); }        /*** * Test Redis Single-value read and write*/@Test Public voidtestredisvalueoperation () {redistemplate template= (redistemplate) This. Appcontext.getbean ("Redistemplate"); //a single-valued object that can be used directly to crud a Redis (single-value operation)valueoperations<string, string> valueoper =Template.opsforvalue (); String Key= "Cat"; String valueexpected= "Tom"; String value=Valueoper.get (key);        Assert.assertnotnull (value); Assert.assertequals ("The cat is not TOM!!!", valueexpected, value); System.out.println (String.Format ("%s->%s", Key,value)); String NewValue= "Hello Kitty"; //set new valueValueoper.set (key, NewValue); System.out.println ("After changing ..."); System.out.println (String.Format ("%s->%s", Key,valueoper.get (key)); }}

As a test class, for a functional class of tests, there will be more than one test case, and each test case may be configured before the start, the test will be finished after the end of the work (such as disconnection ah what), JUnit provided two annotation to us, One is @before, one is @after. For a single test method (identified with @test), the order of execution is @After the specified method, @Test the specified method, as specified by the method. Of course, if all of the test cases in this testing class are loaded with the same configuration and end up with the same finishing touches, then we can use another two annotation, @BeforeClass and @afterclass, and we now have only one test case, Just follow the routine.

For the pre-work of this test method, of course, let Spring help us build a luxury villa (context), generating two maids (beans). And then in the test code, all we have to do is direct the industrious maid to work. Everything is such a river crab.

Passing a spring XML file name array to it through the construction method of Classpathxmlapplicationcontext, spring sees this array and starts initializing the context. Generates the Jedisconnectionfactory object and the Redistemplate object, and returns a ApplicationContext object from which we can easily get the two generated objects.

OK, next look at the test method.

Gets the Redistemplate object from the spring context, gets the member variable of the object, the Valueoperations object, which is a generic class, valueoperations<k, V> The underlying data type of the Redis database is string, that is, key is a literal, and value is a string.

With the Valueoperations object, you can do all the Redis-to-string operations, including operations such as Get,set,getex, and you can find the relevant interface methods through the API.

Examples of the use of the most basic get/set operation, I believe that we can also understand, do not say more.

3. Summary

The introductory example, relative or too simple, in-depth learning still requires mastering many of the basic commands of Redis, and which of the interfaces the spring encapsulates. As a yard, the face of new technology emerging, the replacement is too fast, I can only say: any heavy and long way, and key (key butt, coding) and ha skin.

Getting Started with spring 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.