Spring redis entry, springredis

Source: Internet
Author: User

Spring redis entry, springredis

1. Install the redis service on the Virtual Machine

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

Decompress, tar-zxvf redis-2.8.19.tar.gz

Go to the folder, cd redis-2.8.19/, compile it, make

Create an empty folder to store the redis program, mkdir/usr/local/redis

Copy the compiled product to the redis folder in sequence

1) After compilation, under the src folder

Red files are copied separately.

Cp redis-benchmark/usr/local/redis

Cp redis-cli/usr/local/redis

Cp redis-server/usr/local/redis

2) in the main folder after compilation

Cp redis. conf/usr/local/redis

After Qian Kun moved the app, let's see what the folder of the redis program looks like.


OK, everything is ready, and it only owes to startup. now let's enter the startup command gently:

./Redis-server./redis. conf

Want to run in the background? Do you think the command is too annoying? Want to set it to auto-start upon startup? Then add the command to the path and write it into rc. local.

I will not go into details here.

We started the server by default. The default hostName is localhost and the port is 6379. You can edit redis. conf to change them.

Okay. After the redis server is started, let's use the client to connect. Enter redis-cli (Port 6379 connected to localhost by default)

Here, the keys * command is used to check what is currently in the redis database.

We can simply enter several redis commands to test.

For more commands, visit. I will not go into detail here.

Note: the second part of java is used in windows. To access redis on a linux host, you also need to use a "backdoor ", you need to add 6379 as the firewall exception port in the iptables configuration, and restart the iptables service.


Add seasoning

Service iptables restart

2. Write the java program for accessing redis

Here we will directly write test cases. We can simply use spring + junit to make it concise and generous. It is a waste of shame.

Maven brother, come and play tricks.

The project structure is soy sauce. The following describes the content of each file.

1) pom. xml

As the exclusive area of Nanny maven, it defines the packages to be used, and spring (including core and context), junit, jedis, and spring-data-redis are used. Spring-data-redis is another encapsulation of spring on the basis of jedis, which makes it easier to use.

Directly rely on the package code.

    <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 to mention, the nanny should hurry to work. (Maven kids shoes: T_T, your bandwidth makes me speechless)

2) spring-redis.xml

Spring xml, which is of course bean configuration.

<?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: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/context/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" />    <bean id="jedisConnectionFactory"        class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">        <property name="hostName" value="${hostName}" />        <property name="port" value="${port}" />        <property name="database" value="${index}" />    </bean>    <bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">        <property name="connectionFactory" ref="jedisConnectionFactory" />    </bean></beans>

Here is a small trick. I may not want to write some basic configuration information into xml, because the vi editing format in linux will be messy, I prefer to edit the properties file. The key = value format is easier to edit and the format is not disordered.

So? Use property placeholder. It is easy to configure. You only need $ {key} to write a key.

Here we need to define two spring-data-redis encapsulated objects. One is JedisConnectionFactory. Is it a bit like a connection pool? A typical factory model, you can get the connection object of redis from the connection factory, use the connection object YY, and then possibly LOL ...; Another is the StringRedisTemplate object, which is a bit of a JdbcTemplate taste. The typical template method mode can be CRUD through this template object, but JdbcTemplate is for relational databases, this RedisTemplate is intended for redis non-relational databases.

Note: The redisTemplate here is not an object of the base class RedisTemplate (it may be used in some tutorial articles. If your redis already has strings as key/value data, so be careful), but its subclass StringRedisTemplate. When performing CRUD in redis, the most commonly used is String, such as String as key, value, key or value as hashmap, the default serialization/deserialization operation of the base class RedisTemplate (which uses the JdkSerializationRedisSerializer class) is not for strings. More specifically, the serialization/deserialization tool in the RedisTemplate class processes the string/byte array and the result is not what we want. The serialization/deserialization tool in the StringRedisTemplate subclass is an instance of the StringRedisSerializer class. This class is what we want, so we use the StringRedisTemplate instance here. If you are interested, you can try it out. If you are using a RedisTemplate instance, what kind of data will be written to redis during write operations.

3) redis. properties

Stores the configuration information of redis. As mentioned in the second part, the specific configuration information of the redis server is written in this file.


Just like databases such as mysql, A redis service can also have multiple databases. redis is connected to database No. 0 by default and has 16 databases by default, the index configuration here refers to the number of databases in the range of 0 ~ 15. If you want to increase the capacity, modify redis. conf on your own.

4) RedisTest. java

Finally, it was the turn of pig debut. Let's look at the code first.

Package code. selwyn. spring. redis. demo. test; import org. junit. assert; import org. junit. before; import org. junit. test; import org. springframework. context. applicationContext; import org. springframework. context. support. classPathXmlApplicationContext; import org. springframework. data. redis. core. redisTemplate; import org. springframework. data. redis. core. valueOperations;/*** Class RedisTest * Playing redis *** @ author Selwyn * Date: Mar 28,201 5 7:15:57 */public class RedisTest {/*** spring configuration file */private final static String [] CONFIG_LOC = {"spring-redis.xml "}; private ApplicationContext appContext = null; private ApplicationContext getAppContext () {return new ClassPathXmlApplicationContext (CONFIG_LOC) ;}@ Before public void setUp () {// read the spring configuration file, load to spring context this. appContext = this. getAppContext (); }/*** Test redis single value read and write */@ Test public void testRedisValueOperation () {RedisTemplate template = (RedisTemplate) this. appContext. getBean ("redisTemplate"); // an object for Single-value operations. Through this object, you can directly perform CRUD (single-value operation) ValueOperations <String, String> ValueOperations = template on redis. opsForValue (); String key = "cat"; String valueExpected = "tom"; String value = value.pdf. get (key); Assert. assertNotNull (value); Assert. assertEquals (" Cat is not Tom !!! ", ValueExpected, value); System. out. println (String. format ("% s-> % s", key, value); String newValue = "hello kitty"; // set the new value valueiterator. set (key, newValue); System. out. println ("After changing... "); System. out. println (String. format ("% s-> % s", key, valueparameters. get (key )));}}

As a Test class, the Test class is for a function class Test, which contains multiple Test cases, and each Test case may be configured before the start, after the test is completed, the work will be completed (for example, disconnected or something). junit provides two annotation statements for us: @ Before and @ After. For a single Test method (identified by @ Test), the execution sequence is @ Before specifies the method-> @ Test specifies the method-> @ After specifies the method. Of course, if all the Test cases in the Test class have the same configuration and end operations after the end, we can use the other two annotation, @ BeforeClass and @ AfterClass, now we only have one test case. Let's proceed as usual.

For the front-end work of this test method, of course, let spring help us build a luxury villa (context) and generate two servants (beans ). What we need to do in the test code is to instruct the hardworking servant to do the work. Everything is so crab.

Use the ClassPathXmlApplicationContext constructor to pass a spring xml file name array to it. When spring sees this array, it starts to initialize the context, generate a jedisConnectionFactory object and redisTemplate object, and return an ApplicationContext object, from this object, we may easily obtain the two generated objects.

Okay. Next, let's take a look at the test method.

Obtain the redisTemplate object from the spring context and obtain the member variable of the object, that is, the ValueOperations object. This class is a generic class, ValueOperations <K, V>, it corresponds to the basic data type String of the redis database, that is, the key is a String, and the value is also a String.

Using the ValueOperations object, you can perform all redis operations on the String type, including get, set, getex, and other operations. Through the api, you can find related interface methods.

The example uses the most basic get/set operations. I believe you can understand them as well.

3. Summary

The Getting Started example is relatively simple. To learn more, you still need to master many basic commands of redis and the methods of interfaces corresponding to spring encapsulation. As a code farmer, in the face of an endless stream of new technologies and fast upgrades, I can only say: there is a long way to go, and coding.

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.