Redis的hash结构特别适合 用来存储对象; 比如我们有吧问题的回答根据id存储到Redis中,
key为 "siye_answerId:"+answer.getId();
然后把对象转换成map直接存储进去, hashkey为对象的field,hashvalue为对象的值;
当有人对回答进行浏览,评论,点赞,踩,收藏等操作的时候直接更新这1个字段,
然后获取对象的时候可以直接转换为对象;
下面为 实例代码: 和转换的工具类(注意只能转换基本数据类型,String,Date等里面有2级对象的不能转换;)
@Test
public void test2() throws Exception {
Date date = new Date();
UserInfo user = new UserInfo(25L, "嬴政", 2000, date);
String key = "test_UserInfoId:" + user.getId();
Map<String, String> stringMap = EntityUtils.objectToHash(user);//对象转换map
hashOps.putAll(key, stringMap);
hashOps.put(key, "name", "姜子牙");
Map<String, Object> map4 = hashOps.entries(key);// 返回map集合
UserInfo user2 = EntityUtils.hashToObject2(map4, UserInfo.class);
Long age = hashOps.increment(key, "age", 500L);// 指定字段的值增加,可用来点赞等操作;
Map<String, Object> map5 = hashOps.entries(key);// 返回map集合
UserInfo user3 = EntityUtils.hashToObject2(map5, UserInfo.class);
System.out.println(user3);
}
下面为转换器
public class EntityUtils {
static {
ConvertUtils.register(new LongConverter(null), Long.class);
ConvertUtils.register(new ByteConverter(null), Byte.class);
ConvertUtils.register(new IntegerConverter(null), Integer.class);
ConvertUtils.register(new DoubleConverter(null), Double.class);
ConvertUtils.register(new ShortConverter(null), Short.class);
ConvertUtils.register(new FloatConverter(null), Float.class);
ConvertUtils.register(new Converter() {
public Object convert(Class type, Object value) {
if (value == null) {
return null;
}
return new Date(Long.valueOf((String) value));
}
}, Date.class);
}
public static Map<String, String> objectToHash(Object obj) {
try {
Map<String, String> map = Maps.newHashMap();
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
if (!property.getName().equals("class")) {
if (property.getReadMethod().invoke(obj) != null) {
// 时间类型会错乱所以吧时间手动转换成long;
if (property.getReadMethod().invoke(obj) != null) {
if ("java.util.Date".equals(property.getPropertyType().getTypeName())) {
Date invoke = (Date) property.getReadMethod().invoke(obj);
long time = invoke.getTime();
map.put(property.getName(), String.valueOf(time));
} else {
map.put(property.getName(), "" + property.getReadMethod().invoke(obj));
}
}
}
}
}
return map;
} catch (IntrospectionException | InvocationTargetException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
public static <T> T hashToObject2(Map<?, ?> map, Class t) {
try {
Object o = t.newInstance();
BeanUtils.populate(o, (Map) map);
return (T) o;
} catch (IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException(e);
} catch (InstantiationException e) {
e.printStackTrace();
}
return null;
}
}
转载请注明原文地址: https://www.6miu.com/read-27401.html