当前位置:网站首页>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.
边栏推荐
- Day18 creation and restoration of sparse array
- Link: fatal error lnk1168: cannot open debug/test Solution of exe for writing
- JS controls the display and hiding of tags through class
- Lvgl8.1 hi3536c platform use
- Qinglong wool - Kaka
- Pupanvr- an open source embedded NVR system (1)
- SQL injection upload one sentence Trojan horse (turn)
- Sv806 QT UI development
- Variables and data types
- CCF access control system
猜你喜欢

kali_ Change_ Domestic source

4.3 simulate browser operation and page waiting (display waiting and implicit waiting, handle)

Introduction to MMS memory optimization of Hisilicon MPP service

Development of video preview for main interface of pupanvr-ui

How to deploy PostgreSQL as a docker container

Codec of ASoC framework driven by alsa

22-2-28 there are many things to do at work today, ETH analysis

Normalized vegetation index (NDVI) data, NPP data, GPP data, evapotranspiration data, vegetation type data, ecosystem type distribution data
![[cjson] precautions for root node](/img/6c/4462bc8126935f00a5c64f18de13ea.png)
[cjson] precautions for root node

SQL transaction
随机推荐
Set common methods
When the build When gradle does not load the dependencies, and you need to add a download path in libraries, the path in gradle is not a direct downloadable path
12.24 day exercise -- Programming summation, 99 multiplication table, while loop and for loop exercises
LabVIEW關於TDMS和Binary存儲速度
Enhanced vegetation index evi, NDVI data, NPP data, GPP data, land use data, vegetation type data, rainfall data
Stm32f4 ll library multi-channel ADC
How Bi makes SaaS products have a "sense of security" and "sensitivity" (Part I)
kali_ Change_ Domestic source
2022“高考记忆” 已打包完成,请查收!
Chrome is amazingly fast, fixing 40 vulnerabilities in less than 30 days
Nbiot module me3616 at command mqtt connecting thingsboard
How to generate provincial data from county-level data in ArcGIS?
[GIS tutorial] land use transfer matrix
Microsoft announces that it will discontinue support for older versions of visual studio
Force/release learning and sorting in IC Verification (6) research on the influence of wire type signals
2022 self study materials for Zhejiang computer level III network and security technology examination (1) (updated on 2.28)
2022 "college entrance examination memory" has been packaged, please check!
Simulation of array implementation stack
Walking "daily question" and "DP"
Abstract methods and interfaces

