当前位置:网站首页>Save the object in redis, save the bean in redis hash, and attach the bean map interoperation tool class

Save the object in redis, save the bean in redis hash, and attach the bean map interoperation tool class

2022-06-12 05:17:00 Refuel every day!

Go to redis Stored object , take bean Deposit in redis hash in

because redis in Hash Characteristics of data types , Especially suitable for storing objects , So we use hash Store the object

The final effect we want to accomplish is :

image-20220208182627053

First of all, we need to know if hash Of key Chinese plus English colon :, When you use the visualization tool, it will automatically change to the upper left corner of the above figure

Here I saved it key yes :umbrella: Wang Wu oR83j4kkq2CyvVmuxl6znKbrWi2A

Go to hash Zhongcun Bean There are three ways , I put it at the end of the article , You can review it

1.SpringBoot Add redis Configuration class

Coordinate dependence :

<!-- redis -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--  Object pool , Use redis Storage Object Must introduce  -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
</dependency>

Configuration class code :

@Configuration
public class RedisConfig extends CachingConfigurerSupport {
    
    @Bean
    @ConditionalOnMissingBean(name = "redisTemplate")
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
    
        // Initialize a redis Templates 
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        // Use fastjson Realize the serialization of objects 
        Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        serializer.setObjectMapper(om);

        // Set up “ value ” How to serialize 
        template.setValueSerializer(serializer);
        // Set up “hash” Serialization of type data 
        template.setHashValueSerializer(serializer);
        // Set up “key" How to serialize 
        template.setKeySerializer(new StringRedisSerializer());
        // Set up “hash Of key” How to serialize 
        template.setHashKeySerializer(new StringRedisSerializer());
        // Set up redis The factory object of the template 
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
}

2. Implementation code

@Resource
private RedisTemplate<String,Object> redisTemplate;

@Test
public void TestRedis() throws InstantiationException, IllegalAccessException {
    
	// To get a JavaBean
    UmbrellaBorrow umbrellaBorrow = umbrellaBorrowService.getById(1);
    // Set up key
    String key="umbrella:"+" Zhang San oR83j4kkq2CyvVmuxl6znKbrWi2A";
    String key2="umbrella:"+" Li Si oR83j4kkq2CyvVmuxl6znKbrWi2A";
    String key3="umbrella:"+" Wang Wu oR83j4kkq2CyvVmuxl6znKbrWi2A";
    // Get redis Action object 
    HashOperations<String, Object, Object> redisHash = redisTemplate.opsForHash();
    try {
    
        // Deposit in redis in 
        parseMap(key,redisHash,umbrellaBorrow);
        parseMap(key2,redisHash,umbrellaBorrow);
        parseMap(key3,redisHash,umbrellaBorrow);
    } catch (InvocationTargetException e) {
    
        e.printStackTrace();
    }
}
/** *  take bean Turn into map */
private void parseMap(String key,HashOperations<String, Object, Object> redisHash, Object bean) throws IllegalAccessException, InstantiationException, InvocationTargetException {
    
    //1.  Get all get Method 
    List<Method> allGetMethod = getAllGetMethod(bean);
    //2.  Traversal to redis Medium deposit value 
    for(Method m : allGetMethod){
    
        // Intercepting attribute name 
        String field = m.getName().substring(3);
        // Activate the method to get the value 
        Object value = m.invoke(bean)+"";// Adding an empty string is to add LocalDataTime Convert to string 
        // Go to redis Save these fields 
        redisHash.put(key,field,value);
    }

}

/** *  Take out all get Method  * * @param bean  Specify the instance  * @return  return get Set of methods  */
private List<Method> getAllGetMethod(Object bean) {
    
    List<Method> getMethods = new ArrayList<>();
    Method[] methods = bean.getClass().getMethods();
    for (Method m : methods) {
    
        if (m.getName().startsWith("get")) {
    
            getMethods.add(m);
        }
    }
    return getMethods;
}

It can also be used. org.springframework.cglib.beans.BeanMap transformation , It can be encapsulated as a tool class

/** *  take bean Deposit in Redis in  */
private void parseRedisMap(String key, Object bean,HashOperations<String, Object, Object> redisHash) {
    
    Map<String, Object> map = BeanMapUtil.beanToMap(bean);
    map.forEach((field,value)->redisHash.put(key,field, String.valueOf(value)));
}

Tool class :

public class BeanMapUtil {
    

    public static <T> Map<String, Object> beanToMap(T bean) {
    
        BeanMap beanMap = BeanMap.create(bean);
        Map<String, Object> map = new HashMap<>();

        beanMap.forEach((key, value) -> {
    
            map.put(String.valueOf(key), value);
        });
        return map;
    }

    public static <T> T mapToBean(Map<String, ?> map, Class<T> clazz)
            throws IllegalAccessException, InstantiationException {
    
        T bean = clazz.newInstance();
        BeanMap beanMap = BeanMap.create(bean);
        beanMap.putAll(map);
        return bean;
    }

    public static <T> List<Map<String, Object>> objectsToMaps(List<T> objList) {
    
        List<Map<String, Object>> list = new ArrayList<>();
        if (objList != null && objList.size() > 0) {
    
            Map<String, Object> map = null;
            T bean = null;
            for (int i = 0, size = objList.size(); i < size; i++) {
    
                bean = objList.get(i);
                map = beanToMap(bean);
                list.add(map);
            }
        }
        return list;
    }

    public static <T> List<T> mapsToObjects(List<Map<String, Object>> maps, Class<T> clazz)
            throws InstantiationException, IllegalAccessException {
    
        List<T> list = new ArrayList<>();
        if (maps != null && maps.size() > 0) {
    
            Map<String, ?> map = null;
            for (int i = 0, size = maps.size(); i < size; i++) {
    
                map = maps.get(i);
                T bean = mapToBean(map, clazz);
                list.add(bean);
            }
        }
        return list;
    }
}
	

appendix Hash (hash) review

Redis hash It's a collection of key-value pairs .

Redis hash It's a String Type of field and value Mapping table ,hash Ideal for storing objects . similar Java Inside Map<String,Object>

image-20220208112708716

How to save objects to Redis What about China? ?

The first one is Convert the object to a JSON character string , As shown in the figure above :user={id=1,name=“ Zhang San ”,age=20}

shortcoming : This object cannot be manipulated directly , For example, I want to age Add one , Need to deserialize first Change it and then serialize it back . It's expensive . Too complicated , Generally do not use

The second kind : Through users key:id+ Object attribute labels ,value: Property

image-20220208113436681

advantage : It is convenient to operate the attributes in the object

shortcoming : The data is too scattered , More data makes it very confusing , Generally we don't have to

The third kind of : adopt hash Mapping storage ,key:id,value:<field,value> In the form of

image-20220208115418767

The third method is most suitable for storing objects

image-20220208121355632

Common commands :

  • hset <key><field><value>: to <key> In the collection <field> Key assignment <value>
  • hget <key1><field>: from <key1> aggregate <field> Take out value
  • hmset <key1><field1><value1><field2><value2>...: Batch settings hash Value
  • hexists <key1><field>: Look at the hash table key in , Given domain field Whether there is
  • hkeys <key>: List the hash All of the collection field
  • hvals <key>: List the hash All of the collection value
  • hincrby <key><field><increment>: Hash table key In the domain field Plus the increment 1 -1
  • hsetnx <key><field><value>: Hash table key In the domain field Is set to value , If and only if domain field non-existent

data structure :

Hash There are two kinds of data structures corresponding to types :ziplist( Compressed list ),hashtable( Hashtable ).

When field-value When the length is short and the number is small , Use ziplist, Otherwise use hashtable.

原网站

版权声明
本文为[Refuel every day!]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203010620088080.html