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,BaseEntity> getParentEntity(){
        return new HashMap<>();
    }
}

spring bean 配置:


id="databaseSyncUtil" class="org.ty.cloudCourse.util.DatabaseSyncUtil">
    name="HOST" value="${redis.host}"/>
    name="PORT" value="${redis.port}"/>

同步工具类:

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> 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, BaseEntity> map2 = obj.getParentEntity();
                    for (Map.Entry, 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> map, Object a) {
        //获取传入类的所有属性,如果不为基础类型则记录其名称
        List 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, String>> fvs = map.entrySet();
        Iterator it = fvs.iterator();
        while (it.hasNext()) {
            Map.Entry, String> e = (Map.Entry, 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> map, Map, String> m, Object a) {
        //获取传入类的所有属性,如果不为基础类型则记录其名称
        List 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, String>> fvs = map.entrySet();
        Iterator it = fvs.iterator();
        while (it.hasNext()) {
            Map.Entry, String> e = (Map.Entry, 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;
    }
}

你可能感兴趣的:(Redis,Java)