SpringBoot integrates Redis and Redis tool class writing

Reprint address: https://www.cnblogs.com/zeng1994/p/03303c805731afc9aa9c60dbbd32a323.html

SpringBoot integrates many Redis blogs, but many of them are not the results I want. Because I just need to integrate, I can operate Redis, and I don't need to use it with caching-related annotations (such as @Cacheable). After reading many blogs, I successfully integrated and wrote a Redis operating tool class. This record is intended to facilitate subsequent reference.

Maven Dependence

(1) The SpringBook version used in this article is as follows

<parent>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-parent</artifactId>

        <version>2.0.2.RELEASE</version>

        <relativePath/> <!-- lookup parent from repository -->

    </parent>

(2) Adding Redis-related dependencies

<dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-data-redis</artifactId>

</dependency> 

2. Adding redis-related configuration to application.properties

# Redis database index (default 0)  

spring.redis.database=0  

# Redis server address  

spring.redis.host=192.168.0.24  

# Redis Server Connection Port  

spring.redis.port=6379  

# Redis server connection password (default is empty)  

spring.redis.password=  

# Maximum number of connections in connection pool (no restrictions with negative values)  

spring.redis.pool.max-active=200  

# Maximum blocking waiting time for connection pools (using negative values to indicate no restrictions)  

spring.redis.pool.max-wait=-1  

# Maximum idle connection in connection pool  

spring.redis.pool.max-idle=10 

# Minimum idle connection in connection pool  

spring.redis.pool.min-idle=0  

# Connection timeout time (milliseconds)  

spring.redis.timeout=1000 

3. Write a redis configuration class

(1) Talk about the automatic configuration of RedisTemplate

In fact, you can now inject RedisTemplate into your code. Why can you inject it directly? Look at the source code first. The following is a screenshot of the RedisAutoConfiguration class. To prevent the image from invalidating, the code is also attached.

Code:

@Configuration

@ConditionalOnClass(RedisOperations.class)

@EnableConfigurationProperties(RedisProperties.class)

@Import({ LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class })

public class RedisAutoConfiguration {


    @Bean

    @ConditionalOnMissingBean(name = "redisTemplate")

    public RedisTemplate<Object, Object> redisTemplate(

            RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {

        RedisTemplate<Object, Object> template = new RedisTemplate<>();

        template.setConnectionFactory(redisConnectionFactory);

        return template;
    }


    @Bean

    @ConditionalOnMissingBean

    public StringRedisTemplate stringRedisTemplate(

            RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {

        StringRedisTemplate template = new StringRedisTemplate();

        template.setConnectionFactory(redisConnectionFactory);

        return template;

    }


}

As you can see from the source code, SpringBoot automatically generates a RedisTemplate and a String RedisTemplate in the container. However, the generic type of RedisTemplate is <Object, Object>, which is inconvenient to write code and requires many types of conversion code; we need a RedisTemplate in the form of <String, Object>. Moreover, the RedisTemplate does not set the serialization of key and value when data exists in Redis.

When you see the @ConditionalOnMissingBean annotation, you know that if there is a RedisTemplate object in the Spring container, the automatically configured RedisTemplate will not be instantiated. So we can write our own configuration class to configure RedisTemplate.

 

(2) Since automatic configuration is not working well, reconfigure a RedisTemplate

The code is as follows:

package com.zxy.demo.redis;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;

/**

 * redis Configuration class

 * @author ZENG.XIAO.YAN

 * @date   2018 June 6, 2000

 * 

 */

@Configuration

public class RedisConfig {

    

    @Bean

    @SuppressWarnings("all")

    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {

        RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();

        template.setConnectionFactory(factory);

        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);

        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();

        // key uses String serialization

        template.setKeySerializer(stringRedisSerializer);

        // hash's key also uses String serialization

        template.setHashKeySerializer(stringRedisSerializer);

        // value serialization using jackson

        template.setValueSerializer(jackson2JsonRedisSerializer);

        // hash's value serialization method adopts jackson

        template.setHashValueSerializer(jackson2JsonRedisSerializer);

        template.afterPropertiesSet();

        return template;

    }


}

4. Write a Redis tool class

It takes a lot of lines of code to operate Redis directly with RedisTemplate, so encapsulating a RedisUtils directly makes it easier to write code. This RedisUtils is handed over to the Spring container for instantiation and direct annotation injection when used.

The tool class code is as follows:

package com.zxy.demo.redis;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

/**

 * Redis Tool class
 * @author ZENG.XIAO.YAN
 * @date   2018 7 June 2000
 */

@Component

public final class RedisUtil {

    
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    // =============================common============================

    /**
     * Specify cache expiration time
     * @param key key
     * @param time Time (seconds)
     * @return
     */

    public boolean expire(String key, long time) {
        try {
            if (time > 0) {
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * Obtain expiration time based on key
     * @param key The key cannot be null
     * @return Time (seconds) returns 0 for permanent validity
     */
    public long getExpire(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

    /**
     * Judging whether key exists
     * @param key key
     * @return true Existence false does not exist
     */
    public boolean hasKey(String key) {
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }


    /**
     * Delete Cache
     * @param key Can pass one or more values
     */
    @SuppressWarnings("unchecked")
    public void del(String... key) {
        if (key != null && key.length > 0) {
            if (key.length == 1) {
                redisTemplate.delete(key[0]);
            } else {
                redisTemplate.delete(CollectionUtils.arrayToList(key));
            }

        }

    }


    // ============================String=============================

    /**
     * Ordinary cache acquisition
     * @param key key
     * @return value
     */
    public Object get(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }
    /**
     * Ordinary cache placement
     * @param key key
     * @param value value
     * @return true Successful false failures
     */
    public boolean set(String key, Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * Placing and setting time of common cache
     * @param key key
     * @param value value
     * @param time Time (seconds) should be greater than 0. If time is less than or equal to 0, it will be set indefinitely.
     * @return true Successful false failures
     */

    public boolean set(String key, Object value, long time) {
        try {
            if (time > 0) {
                redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            } else {
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    /**
     * Increase progressively
     * @param key key
     * @param delta To add a few (more than 0)
     * @return
     */
    public long incr(String key, long delta) {

        if (delta < 0) {
            throw new RuntimeException("Incremental factor must be greater than 0");
        }
        return redisTemplate.opsForValue().increment(key, delta);
    }

    /**
     * Decrement
     * @param key key
     * @param delta To reduce a few (less than 0)
     * @return
     */
    public long decr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("Decreasing factor must be greater than 0");
        }
        return redisTemplate.opsForValue().increment(key, -delta);
    }

    // ================================Map=================================

    /**
     * HashGet
     * @param key The key cannot be null
     * @param item Item cannot be null
     * @return value
     */

    public Object hget(String key, String item) {
        return redisTemplate.opsForHash().get(key, item);
    }
    /**
     * Get all key values corresponding to hashKey
     * @param key key
     * @return Corresponding multiple key values
     */
    public Map<Object, Object> hmget(String key) {
        return redisTemplate.opsForHash().entries(key);
    }

    /**
     * HashSet
     * @param key key

     * @param map Corresponding to multiple key values

     * @return true Successful false failures

     */

    public boolean hmset(String key, Map<String, Object> map) {

        try {

            redisTemplate.opsForHash().putAll(key, map);

            return true;

        } catch (Exception e) {

            e.printStackTrace();

            return false;

        }

    }


    /**

     * HashSet And set the time

     * @param key key

     * @param map Corresponding to multiple key values

     * @param time Time (seconds)

     * @return true Successful false failures
     */

    public boolean hmset(String key, Map<String, Object> map, long time) {

        try {

            redisTemplate.opsForHash().putAll(key, map);

            if (time > 0) {

                expire(key, time);

            }

            return true;
        } catch (Exception e) {

            e.printStackTrace();

            return false;

        }

    }

    /**

     * Put data into a hash table and create it if it does not exist

     * @param key key

     * @param item term

     * @param value value

     * @return true Successful false failures

     */

    public boolean hset(String key, String item, Object value) {

        try {

            redisTemplate.opsForHash().put(key, item, value);

            return true;

        } catch (Exception e) {

            e.printStackTrace();

            return false;

        }

    }

    /**

     * Put data into a hash table and create it if it does not exist

     * @param key key

     * @param item term

     * @param value value

     * @param time Time (seconds) Note: If the existing hash table has time, the original time will be replaced here.

     * @return true Successful false failures

     */

    public boolean hset(String key, String item, Object value, long time) {

        try {

            redisTemplate.opsForHash().put(key, item, value);

            if (time > 0) {

                expire(key, time);

            }

            return true;

        } catch (Exception e) {

            e.printStackTrace();

            return false;

        }

    }


    /**

     * Delete values from hash tables

     * @param key The key cannot be null
     * @param item Items can make multiple items not null

     */

    public void hdel(String key, Object... item) {
        redisTemplate.opsForHash().delete(key, item);
    }


    /**

     * Determine whether there is a value for this item in the hash table
     * @param key The key cannot be null
     * @param item Item cannot be null
     * @return true Existence false does not exist
     */

    public boolean hHasKey(String key, String item) {
        return redisTemplate.opsForHash().hasKey(key, item);
    }


    /**
     * hash If increment does not exist, it creates one and returns the added value.
     * @param key key
     * @param item term
     *@param by To add a few (more than 0)
     * @return
     */

    public double hincr(String key, String item, double by) {
        return redisTemplate.opsForHash().increment(key, item, by);
    }


    /**
     * hash reduce
     * @param key key
     * @param item term
     * @param by To reduce the memory (less than 0)
     * @return
     */

    public double hdecr(String key, String item, double by) {
        return redisTemplate.opsForHash().increment(key, item, -by);
    }


    // ============================set=============================
    /**
     * Get all the values in the Set based on key
     * @param key key
     * @return
     */
    public Set<Object> sGet(String key) {
    try {
            return redisTemplate.opsForSet().members(key);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * Query from a set based on value if it exists
     * @param key key
     * @param value value
     * @return true Existence false does not exist
     */
public boolean sHasKey(String key, Object value) {
        try {
            return redisTemplate.opsForSet().isMember(key, value);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**

     * Put data into set cache
     * @param key key
     * @param values Values can be multiple
     * @return Number of successes
     */

    public long sSet(String key, Object... values) {
        try {
            return redisTemplate.opsForSet().add(key, values);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * Put set data into the cache
     * @param key key
     * @param time Time (seconds)
     * @param values Values can be multiple
     * @return Number of successes
     */

    public long sSetAndTime(String key, long time, Object... values) {

        try {
            Long count = redisTemplate.opsForSet().add(key, values);
            if (time > 0)
                expire(key, time);
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**

     * Get the length of set cache
     * @param key key
     * @return
     */
    public long sGetSetSize(String key) {
        try {
            return redisTemplate.opsForSet().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**

     * Removal of value
     * @param key key
     * @param values Values can be multiple
     * @return Number of removals
     */

    public long setRemove(String key, Object... values) {
        try {
            Long count = redisTemplate.opsForSet().remove(key, values);
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }

    }

    // ===============================list=================================

    /**
     * Get the contents of the list cache
     * @param key key
     * @param start start
     * @param end End 0 to - 1 represents all values
     * @return
     */

    public List<Object> lGet(String key, long start, long end) {
        try {
            return redisTemplate.opsForList().range(key, start, end);
        } catch (Exception e) {
            e.printStackTrace();
           return null;
        }
    }

    /**

     * Get the length of the list cache

     * @param key key

     * @return

     */

    public long lGetListSize(String key) {

        try {

            return redisTemplate.opsForList().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }

    }

    /**

     * Get the values in the list by index

     * @param key key

     * @param index When index >= 0, 0 header, 1 second element, and so on; when index < 0, - 1, tail, - 2 penultimate element, and so on.

     * @return

     */

    public Object lGetIndex(String key, long index) {

        try {

            return redisTemplate.opsForList().index(key, index);

        } catch (Exception e) {

            e.printStackTrace();

            return null;

        }

    }

    /**

     * Put the list in the cache

     * @param key key

     * @param value value

     * @param time Time (seconds)

     * @return

     */

    public boolean lSet(String key, Object value) {

        try {

            redisTemplate.opsForList().rightPush(key, value);

            return true;

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**

     * Put the list in the cache

     * @param key key

     * @param value value

     * @param time Time (seconds)

     * @return

     */

    public boolean lSet(String key, Object value, long time) {

        try {

            redisTemplate.opsForList().rightPush(key, value);

            if (time > 0)

                expire(key, time);

            return true;

        } catch (Exception e) {

            e.printStackTrace();

            return false;

        }

    }

    /**

     * Put the list in the cache

     * @param key key
    * @param value value

     * @param time Time (seconds)

     * @return

     */

    public boolean lSet(String key, List<Object> value) {

        try {

            redisTemplate.opsForList().rightPushAll(key, value);

            return true;

        } catch (Exception e) {

            e.printStackTrace();

            return false;

        }

    }

    /**

     * Put the list in the cache

     * 

     * @param key key

     * @param value value

     * @param time Time (seconds)

     * @return

     */

    public boolean lSet(String key, List<Object> value, long time) {

        try {

            redisTemplate.opsForList().rightPushAll(key, value);

            if (time > 0)

                expire(key, time);

            return true;

        } catch (Exception e) {

            e.printStackTrace();

            return false;

        }

    }


    /**

     * Modify a data item in the list according to the index

     * @param key key

     * @param index Indexes

     * @param value value

     * @return

     */

    public boolean lUpdateIndex(String key, long index, Object value) {

        try {

            redisTemplate.opsForList().set(key, index, value);

            return true;

        } catch (Exception e) {

            e.printStackTrace();

            return false;

        }

    }

    /**

     * Remove N values of value

     * @param key key

     * @param count How many are removed?

     * @param value value

     * @return Number of removals

     */

    public long lRemove(String key, long count, Object value) {

        try {

            Long remove = redisTemplate.opsForList().remove(key, count, value);

            return remove;

        } catch (Exception e) {

            e.printStackTrace();

            return 0;

        }

    }

}

 

V. Summary

In fact, integration is not troublesome, there are many blog posts on the Internet. Pay attention to the serialization of key and value, otherwise the data stored in Redis will look like scrambling.

 

 

 

Keywords: Redis Spring Java less

Added by JParishy on Thu, 25 Jul 2019 09:58:32 +0300