Operate Redis in SpringBoot to parse JsonArray data into object List (ruoyi dictionary value sys_dict as an example)

Scene

If you follow the front-end and back-end separation version to teach you how to build the environment locally and run the project:

Ruoyi separates the front and back ends to teach you how to build the environment locally and run the project_How to run the project with the front and back ends separated_Overbearing rogue temperament blog-CSDN blog

On the basis of building the system above, the dictionary values of the system will be cached into redis.

Look at the data format that stores Json arrays, how to read from redis and parse it into a list of objects for data processing.

Note:

blog:
Domineering rogue temperament blog

Implementation

1. Find the place where the dictionary values are cached in the Ruoyi framework, in common-utils-DictUtils

When setting the dictionary cache, directly perform the following operations

 /**
     * Set dictionary cache
     *
     * @param key parameter key
     * @param dictDatas dictionary data list
     */
    public static void setDictCache(String key, List<SysDictData> dictDatas)
    {
        SpringUtils.getBean(RedisCache.class).setCacheObject(getCacheKey(key), dictDatas);
    }

Directly store the list of entity class SysDictData into redis.

2. Therefore, when reading and parsing, it is necessary to ensure that the entity classes under the same package path are used for receiving and parsing

 /**
     * Get dictionary cache
     *
     * @param key parameter key
     * @return dictDatas dictionary data list
     */
    public static List<SysDictData> getDictCache(String key)
    {
        Object cacheObj = SpringUtils.getBean(RedisCache.class).getCacheObject(getCacheKey(key));
        if (StringUtils.isNotNull(cacheObj))
        {
            List<SysDictData> dictDatas = StringUtils.cast(cacheObj);
            return dictDatas;
        }
        return null;
    }

This is in the tool class, so the dependency injection adopts this method. If it is in the business class, it can be injected directly through annotations

 Map<String, String> carTypeDictMap = new HashMap<>();
        //Get vehicle type dictionary value
        Object cacheObject = redisCache.getCacheObject(Constants.BUSCARTYPE);
        if (StringUtils.isNotNull(cacheObject))
        {
            List<SysDictData> dictDatas = StringUtils.cast(cacheObject);
            carTypeDictMap = dictDatas. stream(). collect(Collectors. toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        }

Pay attention to the direct injection of redisCache here

 @Autowired
    private RedisCache redisCache;

Among them, RedisCache is a tool class of spring redis

package com.badao.demo.utils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
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.BoundSetOperations;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

/**
 * spring redis tool class
 *
 **/
@SuppressWarnings(value = { "unchecked", "rawtypes" })
@Component
public class RedisCache
{
    @Autowired
    public RedisTemplate redisTemplate;

    /**
     * Cache basic objects, Integer, String, entity classes, etc.
     *
     * @param key cache key value
     * @param value cached value
     * @return cached object
     */
    public <T> ValueOperations<String, T> setCacheObject(String key, T value)
    {
        ValueOperations<String, T> operation = redisTemplate. opsForValue();
        operation.set(key, value);
        return operation;
    }

    /**
     * Cache basic objects, Integer, String, entity classes, etc.
     *
     * @param key cache key value
     * @param value cached value
     * @param timeout time
     * @param timeUnit time granularity
     * @return cached object
     */
    public <T> ValueOperations<String, T> setCacheObject(String key, T value, Integer timeout, TimeUnit timeUnit)
    {
        ValueOperations<String, T> operation = redisTemplate. opsForValue();
        operation.set(key, value, timeout, timeUnit);
        return operation;
    }

    /**
     * Get the basic object of the cache.
     *
     * @param key cache key value
     * @return data corresponding to cache key
     */
    public <T> T getCacheObject(String key)
    {
        ValueOperations<String, T> operation = redisTemplate. opsForValue();
        return operation. get(key);
    }

    /**
     * Delete a single object
     *
     * @param key
     */
    public void deleteObject(String key)
    {
        redisTemplate.delete(key);
    }

    /**
     * Delete collection object
     *
     * @param collection
     */
    public void deleteObject(Collection collection)
    {
        redisTemplate.delete(collection);
    }

    /**
     * Cache List data
     *
     * @param key cache key value
     * @param dataList List data to be cached
     * @return cached object
     */
    public <T> ListOperations<String, T> setCacheList(String key, List<T> dataList)
    {
        ListOperations listOperation = redisTemplate. opsForList();
        if (null != dataList)
        {
            int size = dataList. size();
            for (int i = 0; i < size; i ++ )
            {
                listOperation. leftPush(key, dataList. get(i));
            }
        }
        return listOperation;
    }

    /**
     * Get cached collection (fuzzy query)
     *
     * @param keys
     * @return
     */
    public <T> List<T> getCacheList(Set keys) {
        return redisTemplate.opsForValue().multiGet(keys);
    }

    /**
     * Get the cached list object
     *
     * @param key cache key value
     * @return data corresponding to cache key
     */
    public <T> List<T> getCacheList(String key)
    {
        List<T> dataList = new ArrayList<T>();
        ListOperations<String, T> listOperation = redisTemplate.opsForList();
        Long size = listOperation. size(key);

        for (int i = 0; i < size; i ++ )
        {
            dataList.add(listOperation.index(key, i));
        }
        return dataList;
    }

    /**
     * Cache Set
     *
     * @param key cache key value
     * @param dataSet cached data
     * @return cached data object
     */
    public <T> BoundSetOperations<String, T> setCacheSet(String key, Set<T> dataSet)
    {
        BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(key);
        Iterator<T> it = dataSet. iterator();
        while (it. hasNext())
        {
            setOperation. add(it. next());
        }
        return setOperation;
    }

    /**
     * Get cached set
     *
     * @param key
     * @return
     */
    public <T> Set<T> getCacheSet(String key)
    {
        Set<T> dataSet = new HashSet<T>();
        BoundSetOperations<String, T> operation = redisTemplate.boundSetOps(key);
        dataSet = operation. members();
        return dataSet;
    }

    /**
     * Cache Map
     *
     * @param key
     * @param dataMap
     * @return
     */
    public <T> HashOperations<String, String, T> setCacheMap(String key, Map<String, T> dataMap)
    {
        HashOperations hashOperations = redisTemplate.opsForHash();
        if (null != dataMap)
        {
            for (Map.Entry<String, T> entry : dataMap.entrySet())
            {
                hashOperations. put(key, entry. getKey(), entry. getValue());
            }
        }
        return hashOperations;
    }

    /**
     * Get the cached Map
     *
     * @param key
     * @return
     */
    public <T> Map<String, T> getCacheMap(String key)
    {
        Map<String, T> map = redisTemplate.opsForHash().entries(key);
        return map;
    }

    /**
     * Get a list of cached basic objects
     *
     * @param pattern string prefix
     * @return object list
     */
    public Collection<String> keys(String pattern)
    {
        return redisTemplate.keys(pattern);
    }
}

It must be noted that because the data stored in redis has @Type and the package name is specified, it needs to be parsed with the entity class under the package name when parsing.

3. After successful parsing, use Stream’s Collectors.toMap to convert object List to map

For example, if you want to use the corresponding attributes in the entity class as the key and value, you can

dictDatas.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

The effect after parsing