栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

mybatis自定义插件实现分布式id

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

mybatis自定义插件实现分布式id

开发时间紧,只贴代码做记录使用
package com.nfcpwl.efarm.aop;

import com.nfcpwl.efarm.aop.annotation.DistributedInsert;
import com.nfcpwl.efarm.aop.annotation.IdWorker;
import com.nfcpwl.efarm.ds.IdCreator;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;


@Slf4j
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
public class IdWorkerInterceptor implements Interceptor {

    IdCreator idCreator;

    public IdCreator getIdCreator() {
        return idCreator;
    }

    public void setIdCreator(IdCreator idCreator) {
        this.idCreator = idCreator;
    }

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs();
        /// mapper.xml
        MappedStatement arg = (MappedStatement) args[0];

        if (SqlCommandType.INSERT.name().equals(arg.getSqlCommandType().name())) {
            for (Object entity : args) {
                Class aClass = entity.getClass();
                DistributedInsert distributedInsert = aClass.getAnnotation(DistributedInsert.class);

                if (distributedInsert != null) {
                    Field[] fields = aClass.getDeclaredFields();
                    for (Field field : fields) {
                        IdWorker annotation = field.getAnnotation(IdWorker.class);
                        if (annotation != null) {
//                            long snowflakeNextId = IdUtil.getSnowflakeNextId();
                            Integer distributedId10 = idCreator.nextIdInt();
                            setField(entity, field.getName(), distributedId10);
                        }
                        break;
                    }
                }
            }


        }
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object o) {
        return Plugin.wrap(o, this);
    }

    @Override
    public void setProperties(Properties properties) {
        log.warn(properties.toString());
    }

    public static void setField(Object o, String args, Object attributeValue) {
        Class cls = o.getClass();
        //判断该属性是否存在
        Field field = null;
        try {
            field = cls.getDeclaredField(args);
            if (field == null) {
                field = cls.getField(args);
            }
            if (field == null) {
                return;
            }
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }

        String fieldName = "set" + args.substring(0, 1).toUpperCase() + (args.length() > 1 ? args.substring(1) : "");
        Method method = null;
        try {
            method = cls.getMethod(fieldName, attributeValue.getClass());
            method.invoke(o, attributeValue);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}

package com.nfcpwl.efarm.ds;

public interface IdCreator {
    String nextIdStr();
    Long nextIdLong();
    Integer nextIdInt();
}
///
package com.nfcpwl.efarm.ds;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;


@Component("defIdCreator")
public class DefIdCreator implements IdCreator {

    @Autowired
    StringRedisTemplate redisTemplate;


    @Override
    public synchronized String nextIdStr() {

        return null;
    }

    @Override
    public Long nextIdLong() {
        return null;
    }

    @Override
    public Integer nextIdInt() {
        /// TODO 从最大的id进行重置
        Boolean my_mjg_id = redisTemplate.opsForValue().setIfAbsent("MY_MJG_ID", "1000000000");
        if (my_mjg_id){
            Long resultId = redisTemplate.opsForValue().increment("MY_MJG_ID", 1);
            return resultId.intValue();
        }else {
            Long resultId = redisTemplate.opsForValue().increment("MY_MJG_ID", 1);
            return resultId.intValue();
        }
    }
}

配置mybatis插件
package com.nfcpwl.efarm.ds;

import com.nfcpwl.efarm.aop.IdWorkerInterceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;


@Configuration
public class MybatisInterceptorConfig {

    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    @Autowired
    IdWorkerInterceptor idWorkerInterceptor;

    @PostConstruct
    public void addInterceptor() {
        this.sqlSessionFactory.getConfiguration().addInterceptor(idWorkerInterceptor);
    }

}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/956489.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号