当前位置:网站首页>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
List of articles
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 :

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.BeanMaptransformation , 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>

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
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
The third method is most suitable for storing objects

Common commands :
hset <key><field><value>: to <key> In the collection <field> Key assignment <value>hget <key1><field>: from <key1> aggregate <field> Take out valuehmset <key1><field1><value1><field2><value2>...: Batch settings hash Valuehexists <key1><field>: Look at the hash table key in , Given domain field Whether there ishkeys <key>: List the hash All of the collection fieldhvals <key>: List the hash All of the collection valuehincrby <key><field><increment>: Hash table key In the domain field Plus the increment 1 -1hsetnx <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.
边栏推荐
- Yolov5 realizes road crack detection
- Chrome is amazingly fast, fixing 40 vulnerabilities in less than 30 days
- Can‘t find a suitable configuration file in this directory or any parent. Error reporting and resolution
- How to deploy dolphin scheduler Apache dolphin scheduler 1.2.0 in cdh5.16.2
- Detailed explanation of data envelopment analysis (DEA) (taking the 8th Ningxia provincial competition as an example)
- Detailed tutorial on the use of yolov5 and training your own dataset with yolov5
- Thingsboard view telemetry data through database
- 加速訓練之並行化 tf.data.Dataset 生成器
- New year news of osdu open underground data space Forum
- The master programmer "plays" a C program that is not like C
猜你喜欢

How to count the total length of roads in the region and draw data histogram

Ubunt 20.04 uses CDROM or ISO as the installation source

Token based authentication

InnoDB data storage structure – MySQL

File contains (regardless of suffix) Apache log remote file contains PHP encapsulated pseudo protocol:

Introduction to MMS memory optimization of Hisilicon MPP service

2022 self study materials for Zhejiang computer level III network and security technology examination (1) (updated on 2.28)

Thingsboard create RCP widget

Some problems of Qinglong panel

Yolov5 realizes road crack detection
随机推荐
Fundamentals of intensive learning openai gym environment construction demo
Introduction to MMS memory optimization of Hisilicon MPP service
2022-02-28 WPF upper computer 126 understand mqtt
Ubunt 20.04 uses CDROM or ISO as the installation source
Esp32-who face detection
MySQL Linux Installation mysql-5.7.24
WiFi smartconfig implementation
How Bi makes SaaS products have a "sense of security" and "sensitivity" (Part I)
Thingsboard create RCP widget
Why is Julia so popular?
asp. Net core theme Middleware
Object class not ended
How to clear floating, and how does it work?
1009 word search
Report on the current market situation and future development trend of adhesive industry for radar and ultrasonic sensors in the world and China 2022 ~ 2028
[backtracking] backtracking to solve subset problems
Spatial distribution data of China's tertiary watershed / national new area distribution data /npp net primary productivity data / spatial distribution data of vegetation cover / land use data /ndvi d
Asp. Net core EF value conversion
Common MySQL date query
12.24 day exercise -- Programming summation, 99 multiplication table, while loop and for loop exercises

