Spring integration Redis environment can be built using the built SSM environment, square (lazy) then (people) fast (dedicated) quick (use), first push!

@[toc]

1. Prepare the dependency Jar package

<! - = = = = = = = = = = = = = = = = spring integration Redis = = = = = = = = = = = = = = = = = = -- -- ><! Jedis --> jedis --> jedis
    <dependency>
      <groupId>redis.clients</groupId>
      <artifactId>jedis</artifactId>
      <version>2.4.2</version>
    </dependency>
    
<! --> < span style = "max-width: 100%;
    <dependency>
      <groupId>org.springframework.data</groupId>
      <artifactId>spring-data-redis</artifactId>
      <version>1.4.2. RELEASE</version>
    </dependency>
Copy the code

1.1 overview of Jedis

Yes, the Jedis JAR package is used above, here is a brief introduction to Jedis.

Java clients can access Redis using Jedis, Redisson, Jredis, jDBC-redis, etc. Jedis and Redisson are officially recommended. Commonly used Jedis. The operation of Jedis is basically the same as the operation of the native Redis command. In other words, Jedis is actually the Java implementation of the native command. The advantage is that it is very convenient to use and there is no need to memorize other APIS. For starters, Jedis is faster and more comfortable.

2. Configuration in spring-redis.xml

Start with the following configuration in Spring’s XML:

2.1. Configure connection pool information

<! --1, set connection pool information --><bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <! -- Max connections -->
        <property name="maxTotal" value="50"></property>
        <property name="maxIdle" value="5"></property>
        <! Redis test = Spring;
    </bean>
Copy the code

Of course configuration, redis. Clients. Jedis. JedisPoolConfig also has the default configuration information! After all, I’m the one who says so.

2.2. Configure connection pool information

<! -2 -Jedis (Redis) --><bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <! -- Need to customize some factory property configuration information -->
        <! -- Specify server address -->
        <property name="hostName" value="192.168.113.231"></property>
        <! -- Specify the service port number -->
        <property name="port" value="6379"></property>
        <! Redis3 specifies the password -->
        <property name="password" value="yichun"></property>

        <! New JedisPoolConfig = new JedisPoolConfig = new JedisPoolConfig-->
        <property name="poolConfig" ref="jedisPoolConfig"></property>
    </bean>
Copy the code

If the connection pool configuration is not customized, the default connection pool configuration will be used. The factory has the property new JedisPoolConfig, as follows:

2.3. Configure the RedisTemplate template

Now that the RedisTemplate template is configured, let’s take a look at the RedisTemplate template.

Spring-data-redis provides RedisTemplate to implement redis access operations, it encapsulates the redis connection pool management logic, business code need not care about the acquisition, release connection logic; Spring Redis also supports Jedis, Jredis, and RJC client operations. RedisTemplate provides the use of several commonly used interface methods, which respectively store the operation of Redis String (String), hash (Map), list (list), set (set) and sorted set (sorted sets) and other data types.

RedisTemplate greatly simplifies Redis data access, allowing us to persist keys and values of all types, not just byte arrays.

Configure the RedisTemplate template

<! --3Insert JedisConnectionFactory into the RedisTemplate template.<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
        <property name="connectionFactory" ref="jedisConnectionFactory"></property>
 
 
    <! Serialization of key and value
        <property name="keySerializer">
            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"></bean>
        </property>
        <property name="valueSerializer">
            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"></bean>
        </property>
    </bean>
Copy the code

Specific can enter the source code to watch, the following post a simple analysis of its:

3. Service code writing

First write an interface

package com.gx.service;

public interface RedisUserService {
    public String getString(String key);
}
Copy the code

Write the actual service code

package com.gx.service.Impl;

import com.gx.service.RedisUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;

@Service
public class RedisUserServiceImpl implements RedisUserService {
    /** * the main business code is through a key to get the value: * does not exist in Redis: into the database query * exists: into Redis query */
    @Autowired
    RedisTemplate<String.String> redisTemplate;

    @Override
    public String getString(String key) {
        ValueOperations<String.String> string=redisTemplate.opsForValue();//opsForValue stores String data. OpsForValue provides many operations on Redis String data.

       / / redisTemplate. OpsForValue (). The set (" cs1 ", "1" cs data, 1, TimeUnit. HOURS). // Set the storage data and expiration time to 1 hour

        if (redisTemplate.hasKey(key)) {
            System.out.println("Fetch and return in Redis");
            return string.get(key);
        }else {
            String result="Value of RedisTemplate";

            string.set(key,result);
            System.out.println("Fetch it from the database and return it.");
            returnresult; }}}Copy the code

RedisTemplateTest Test code writing

package com.gx.test;

import com.gx.service.RedisUserService;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class RedisTemplateTest {
    public static void main(String[] args) {
    // I only load applicationContext.xml because I put the spring-redis. XML configuration directly into applicationContext.xml.
        ClassPathXmlApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
        RedisUserService userService=ctx.getBean(RedisUserService.class);

        String key="cs2";
        String result=userService.getString(key); // call the getString(key) method we wrote in userServiceSystem.out.println(result); }}Copy the code

Do remember to open ports and firewalls before running, otherwise it will report an error if the connection fails, here is a reminder!! = =

First run

OK, here Spring integration Redis preliminary integration completed!

If this article helped you a little bit, please give it a thumbs up. Your approval is my biggest motivation. Thank you

Finally, if there is insufficient or improper place, welcome to criticize, grateful! If you have any questions welcome to leave a message, absolutely the first time reply!

Welcome to pay attention to my public number, there are some Java learning materials and a large wave of Java electronic books, such as Zhou Zhiming teacher’s in-depth Java virtual machine, Java programming thought, core technology volume, big talk design mode, Java concurrent programming combat….. Are Java bible, don’t say fast on the Tomcat car, how we go! The most important is to discuss technology together, yearning for technology, the pursuit of technology, good come is a friend oh…