Instructions for using common collections of RedisTemplate (1)

   Here I use the spring-boot-starter-data-redis jar package of redisTemplate combined with the spring-boot framework, which is introduced by POM. The import code is as follows:

 

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.6.RELEASE</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-configuration-processor</artifactId>
        <optional>true</optional>
    </dependency>
</dependencies>

  RedisTemplate mainly supports String, List, Hash, Set, ZSet parameters, and the corresponding methods are opsForValue(), opsForList(), opsForHash(), opsForSet(), opsForZSet(). The use of these methods is described below.

 

  Before the introduction, let's talk about the serialization method of RedisTemplate first. There is a StringRedisTemplate class that inherits this class under the RedisTemplate class. This class is mainly used for the implementation of the String type of the opsForValue() method, and the internal implementation of these two classes Not the same, if the RedisTemplate class is used as the tool class for connecting to Redis, if the opsForValue method is not used, we can initialize the serialization method like this:

 

ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setKeySerializer(template.getStringSerializer());
template.setValueSerializer(jackson2JsonRedisSerializer);
template.setHashValueSerializer(jackson2JsonRedisSerializer);

 If we need to use the opsForValue() method, we must use the following serialization method:

 

 

ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
//Use this to change the serialization method when using the String data structure
RedisSerializer<String> stringSerializer = new StringRedisSerializer();
template.setKeySerializer(stringSerializer );
template.setValueSerializer(stringSerializer );
template.setHashKeySerializer(stringSerializer );
template.setHashValueSerializer(stringSerializer );

   Of course, if you want to use the RedisTemplate method as a bean, you must implement the code in the following way (all the methods described here are used by using spring-boot):

1.   We can define the following redis connection in the application.properties file :

 

	#Configure cache redis
spring.redis.database=8
# Redis server address
spring.redis.host=127.0.0.1
# Redis server connection port
spring.redis.port=6379
# Redis server connection password (default is empty)
spring.redis.password=
# The maximum number of connections in the connection pool (use a negative value to indicate no limit)
spring.redis.pool.max-active=8
# Connection pool maximum blocking wait time (use a negative value to indicate no limit)
spring.redis.pool.max-wait=-1
# Maximum idle connections in the connection pool
spring.redis.pool.max-idle=8
# Minimum idle connection in the connection pool
spring.redis.pool.min-idle=0
# Connection timeout (ms)
spring.redis.keytimeout=1000
spring.redis.timeout=0

2.  Use the RedisTemplate class to set up the bean file:

 

 

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;

/**
 * @author liaoyubo
 * @version 1.0 2017/8/1
 * @description
 */
@Configuration
public class RedisConfig {

    @Value("${spring.redis.host}")
    private String hostName;
    @Value("${spring.redis.port}")
    private int port;
    @Value("${spring.redis.password}")
    private String passWord;
    @Value("${spring.redis.pool.max-idle}")
    private int maxIdl;
    @Value("${spring.redis.pool.min-idle}")
    private int minIdl;
    @Value("${spring.redis.database}")
    private int database;
    @Value("${spring.redis.keytimeout}")
    private long keytimeout;
    @Value("${spring.redis.timeout}")
    private int timeout;

    /*@Bean
    public JedisConnectionFactory redisConnectionFactory() {
        JedisConnectionFactory factory = new JedisConnectionFactory();
        factory.setHostName(hostName);
        factory.setPort(port);
        factory.setTimeout(timeout); //Set the connection timeout
        return factory;
    }

    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
        StringRedisTemplate template = new StringRedisTemplate(factory);
        setSerializer(template); //Set the serializer so that ReportBean does not need to implement the Serializable interface
        template.afterPropertiesSet();
        return template;
    }
    private void setSerializer(StringRedisTemplate template) {
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        template.setValueSerializer(jackson2JsonRedisSerializer);
    }*/

    @Bean
    public RedisConnectionFactory redisConnectionFactory(){
        JedisPoolConfig poolConfig=new JedisPoolConfig();
        poolConfig.setMaxIdle(maxIdl);
        poolConfig.setMinIdle(minIdl);
        poolConfig.setTestOnBorrow(true);
        poolConfig.setTestOnReturn (true);
        poolConfig.setTestWhileIdle (true);
        poolConfig.setNumTestsPerEvictionRun (10);
        poolConfig.setTimeBetweenEvictionRunsMillis (60000);
        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(poolConfig);
        jedisConnectionFactory.setHostName(hostName);
        if(!passWord.isEmpty()){
            jedisConnectionFactory.setPassword(passWord);
        }
        jedisConnectionFactory.setPort(port);
        jedisConnectionFactory.setDatabase(database);
        return jedisConnectionFactory;
    }
    @Bean
    public RedisTemplate<String, Object> redisTemplateObject() throws Exception {
        RedisTemplate<String, Object> redisTemplateObject = new RedisTemplate<String, Object>();
        redisTemplateObject.setConnectionFactory(redisConnectionFactory());
        setSerializer(redisTemplateObject);
        redisTemplateObject.afterPropertiesSet();
        return redisTemplateObject;
    }



    private void setSerializer(RedisTemplate<String, Object> template) {
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(
                Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        /*template.setKeySerializer(template.getStringSerializer());
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.setHashValueSerializer(jackson2JsonRedisSerializer);*/
        //Use this to change the serialization method when using the String data structure
        RedisSerializer<String> stringSerializer = new StringRedisSerializer();
        template.setKeySerializer(stringSerializer );
        template.setValueSerializer(stringSerializer );
        template.setHashKeySerializer(stringSerializer );
        template.setHashValueSerializer(stringSerializer );

    }

}

 3.   Create a startup class App class

 

 

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @author liaoyubo
 * @version 1.0 2017/7/31
 * @description
 */
@SpringBootApplication
public class App {

    public static void main(String [] args){
        SpringApplication.run(App.class);
    }

}

  Through the above steps, we can use the RedisTemplate template class normally by bean injection . If Redis is not installed , please go to https://redis.io/download official website to download the required Redis . The following mainly introduces the RedisTemplate collection and the use of pipeline and multi . The official website address is http://docs.spring.io/spring-data/redis/docs/current/api/org/springframework/data/redis/core/RedisTemplate. html . Inject the RedisTemplate method as follows :

 

 

 

@Autowired
private RedisTemplate<String,Object> redisTemplate;

 1. Introduction to pipeline

 

      Pipeline is a channel function provided by redis . Pipeline is usually used when there is no need to wait for the result to return immediately. The advantage of using pipeline is that it processes data faster because it specially opens up a pipeline to process data ( specific comparison You can refer to the article on the Internet ) , it is one-way, sending data from the client to the server, when the pipeline closes the link, the data will be returned from the server, and the data from the server cannot be obtained again during this period.

   Because of the needs of this example, we modify the serialization method of the RedisConfig.java class to:

 

template.setKeySerializer(template.getStringSerializer());
template.setValueSerializer(jackson2JsonRedisSerializer);
template.setHashValueSerializer(jackson2JsonRedisSerializer);

 Here is a basic usage example:

import com.springRedis.App;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;


/**
 * @author liaoyubo
 * @version 1.0 2017/7/31
 * @description
 */

@RunWith(SpringRunner.class)
@SpringBootTest(classes = App.class)
public class PipelineTest {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Test
    public void testPipeLine(){
        redisTemplate.opsForValue().set("a",1);
        redisTemplate.opsForValue().set("b",2);
        redisTemplate.executePipelined(new RedisCallback<Object>() {
            @Override
            public Object doInRedis(RedisConnection redisConnection) throws DataAccessException {
                redisConnection.openPipeline();
                for (int i = 0;i < 10;i++){
                    redisConnection.incr("a".getBytes());
                }
                System.out.println("a:"+redisTemplate.opsForValue().get("a"));
                redisTemplate.opsForValue().set("c",3);
                for(int j = 0;j < 20;j++){
                    redisConnection.incr("b".getBytes());
                }
                System.out.println("b:"+redisTemplate.opsForValue().get("b"));
                System.out.println("c:"+redisTemplate.opsForValue().get("c"));
                redisConnection.closePipeline();
                return null;
            }
        });
        System.out.println("b:"+redisTemplate.opsForValue().get("b"));
        System.out.println("a:"+redisTemplate.opsForValue().get("a"));
    }

}

 Second, multi and exec

 

   These two methods are transaction methods provided by the RedisTemplate.java class. Before using this method, the transaction must be opened for normal use. Examples are as follows:

 

import com.springRedis.App;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

/**
 * @author liaoyubo
 * @version 1.0 2017/8/4
 * @description
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = App.class)
public class MultiTest {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Test
    public void testMulti(){
        ValueOperations<String,Object> valueOperations = redisTemplate.opsForValue();
        redisTemplate.setEnableTransactionSupport(true);
        //Until it is submitted, it is not worth getting it, and it will report an error again in a loop
        while (true){
            redisTemplate.watch("multiTest");
            redisTemplate.multi();
            valueOperations.set("multiTest",1);
            valueOperations.increment("multiTest",2);
            Object o = valueOperations.get("multiTest");
            List list = redisTemplate.exec();
            System.out.println(list);
            System.out.println(o);
        }

    }

}

           When using the exec() method, no parameters are brought in, the default serialization method is used, and an exec Jackson2JsonRedisSerializer is provided.(RedisSerializer<?> valueSerializer)方法,这个方法可以自己定义序列化方法,如

The use of the RedisTemplate collection        will be introduced later.

 

 

 

 

 

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327069780&siteId=291194637