Redis与Java结合——mysql redis同步工具类

首先将所有实体类都继承BaseEntity:

BaseEntity:

package org.ty.cloudCourse.entity;

import java.util.HashMap;
import java.util.Map;

/**
 * @author kangtaiyang
 * @date 2018/7/3
 */
public abstract class BaseEntity {
    protected Integer id = null;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Map<String,BaseEntity> getParentEntity(){
        return new HashMap<>();
    }
}

spring bean 配置:

<!-- DatabaseSyncUtil配置 -->
<bean id="databaseSyncUtil" class="org.ty.cloudCourse.util.DatabaseSyncUtil">
    <property name="HOST" value="${redis.host}"/>
    <property name="PORT" value="${redis.port}"/>
</bean>

同步工具类:

DatabaseSyncUtil:

package org.ty.cloudCourse.util;

import org.apache.commons.beanutils.BeanUtils;

import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.ArrayConverter;
import org.apache.commons.beanutils.converters.SqlDateConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.ty.cloudCourse.entity.*;
import org.ty.cloudCourse.entity.Class;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.*;

/**
 * @author kangtaiyang
 * @date 2018/7/2
 */
public class DatabaseSyncUtil {

    @Autowired
    private RedisFactory redisFactory;
    private String HOST;
    private String PORT;

    /**
     * 实体类转为redis中的hash
     *
     * @param obj
     * @return
     * @throws IllegalAccessException
     */
    public Tuple classTransforToHash(BaseEntity obj) throws IllegalAccessException {
        redisFactory.getJedis();
        Tuple tuple = new Tuple();
        //这是key
        tuple.add(obj.getClass().getSimpleName() + ":" + obj.getId());
        Map<String, String> map = new HashMap<>();
        Field[] fields = obj.getClass().getDeclaredFields();
        //计数器,遇到类中类直接一次性处理,避免单条处理
        int j = 0;
        //i=1是怕把类的id也存进去,id是key,不用重复存
        for (int i = 1; i < fields.length; i++) {
            Field f = fields[i];
            String str = f.getType().getTypeName();
            if (str.contains("lang")) {
                f.setAccessible(true);
                map.put(f.getName(), "" + f.get(obj));
            }
            if (str.contains("ty.cloudCourse.entity")) {
                if (j == 0) {
                    f.setAccessible(true);
                    Map<String, BaseEntity> map2 = obj.getParentEntity();
                    for (Map.Entry<String, BaseEntity> e :
                            map2.entrySet()) {
                        if (e.getValue() == null) {
                            map2.remove(e.getKey());
                        } else {
                            map.put(e.getKey(), "" + e.getValue().getId());
                        }
                    }
                    i++;
                }
            }
        }
        tuple.add(map);
        return tuple;
    }

    /**
     * hash转实体类
     *
     * @param map
     * @param a
     * @return
     */
    public Object hashTransforToClass(Map<String, String> map, Object a) {
        //获取传入类的所有属性,如果不为基础类型则记录其名称
        List<String> strList = new ArrayList<>();
        for (Field f :
                a.getClass().getDeclaredFields()) {
            if (f.getType().getTypeName().contains("ty.cloudCourse.entity")) {
                strList.add(f.getName());
            }
        }
        Object obj = a;
        Set<Map.Entry<String, String>> fvs = map.entrySet();
        Iterator it = fvs.iterator();
        while (it.hasNext()) {
            Map.Entry<String, String> e = (Map.Entry<String, String>) it.next();
            if (e.getValue().equals("null") || strList.contains(e.getKey())) {
                it.remove();
            }
        }
        try {
            BeanUtils.populate(obj, map);
            return obj;
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        return obj;
    }

    /**
     * 第二个参数是怕obj里面有复杂属性,所以按原库对比,如果有之前的存的就不设为null了
     *
     * @param map
     * @param m
     * @param a
     * @return
     */
    public Object hashTransforToClass(Map<String, String> map, Map<String, String> m, Object a) {
        //获取传入类的所有属性,如果不为基础类型则记录其名称
        List<String> strList = new ArrayList<>();
        for (Field f :
                a.getClass().getDeclaredFields()) {
            if (f.getType().getTypeName().contains("ty.cloudCourse.entity")) {
                strList.add(f.getName());
            }
        }

        Object obj = a;

        Set<Map.Entry<String, String>> fvs = map.entrySet();
        Iterator it = fvs.iterator();
        while (it.hasNext()) {
            Map.Entry<String, String> e = (Map.Entry<String, String>) it.next();
            System.out.println(strList);
            if (e.getValue().equals("null")) {
                it.remove();
            }
            if (strList.contains(e.getKey())) {
                if (m.containsKey(e.getKey())) {
                    e.setValue(m.get(e.getKey()));
                }
            }
        }
        try {
            BeanUtils.populate(obj, map);
            return obj;
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        return obj;
    }

    /**
     * 通过实体类获取a的类型和key
     *
     * @param entity
     * @return
     */
    public Tuple getTypeAndKeyFromEntity(BaseEntity entity) {
        String type = entity.getClass().getSimpleName();
        String key = type + ":" + entity.getId();
        return new Tuple(type, key);
    }

    @Deprecated
    public void setRedisFactory(RedisFactory redisFactory) {
        this.redisFactory = redisFactory;
    }

    @Deprecated
    public void setHOST(String HOST) {
        this.HOST = HOST;
    }

    @Deprecated
    public void setPORT(String PORT) {
        this.PORT = PORT;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_37580283/article/details/80941976