Search in sources :

Example 1 with BaseEntity

use of com.mendmix.mybatis.core.BaseEntity in project jeesuite-libs by vakinge.

the class CacheHandler method genarateQueryCacheKey.

/**
 * 生成查询缓存key
 * @param cacheInfo
 * @param param
 * @return
 */
@SuppressWarnings("unchecked")
public static String genarateQueryCacheKey(InvocationVals invocationVal, String keyPattern, Object param) {
    String text;
    try {
        Object[] args;
        if (param instanceof Map) {
            Map<String, Object> map = (Map<String, Object>) param;
            if (map.containsKey(STR_PARAM + "1")) {
                args = new String[map.size() / 2];
                for (int i = 0; i < args.length; i++) {
                    args[i] = CacheKeyUtils.objcetToString(map.get(STR_PARAM + (i + 1)));
                }
            } else {
                args = new String[] { CacheKeyUtils.objcetToString(map) };
            }
        } else if (param instanceof BaseEntity) {
            Serializable id = ((BaseEntity) param).getId();
            if (id != null && !"0".equals(id.toString())) {
                args = new String[] { (((BaseEntity) param).getId()).toString() };
            } else {
                args = new String[] { CacheKeyUtils.objcetToString(param) };
            }
        } else if (param instanceof Object[]) {
            args = (Object[]) param;
        } else if (param == null) {
            args = new Object[0];
        } else {
            args = new String[] { CacheKeyUtils.objcetToString(param) };
        }
        text = StringUtils.join(args, GlobalConstants.UNDER_LINE);
    } catch (Exception e) {
        text = JsonUtils.toJson(param);
        e.printStackTrace();
    }
    if (text.length() > 64)
        text = DigestUtils.md5(text);
    String key = String.format(keyPattern, text);
    QueryCacheMethodMetadata methodMetadata = invocationVal.getQueryMethodMetadata();
    if (methodMetadata == null || methodMetadata.isPk || methodMetadata.uniqueIndex) {
        return key;
    }
    StringBuilder sb = new StringBuilder(key);
    String tenantId = CurrentRuntimeContext.getTenantId();
    if (tenantId != null) {
        sb.append(GlobalConstants.AT).append(tenantId);
    }
    AuthUser currentUser;
    if (invocationVal.isDynaDataPermEnabled() && (currentUser = CurrentRuntimeContext.getCurrentUser()) != null) {
        sb.append(GlobalConstants.AT).append(currentUser.getId());
    }
    return sb.toString();
}
Also used : Serializable(java.io.Serializable) BaseEntity(com.mendmix.mybatis.core.BaseEntity) AuthUser(com.mendmix.common.model.AuthUser) Map(java.util.Map) HashMap(java.util.HashMap) MybatisHanlerInitException(com.mendmix.mybatis.exception.MybatisHanlerInitException)

Example 2 with BaseEntity

use of com.mendmix.mybatis.core.BaseEntity in project jeesuite-libs by vakinge.

the class CacheHandler method start.

@Override
public void start(JeesuiteMybatisInterceptor context) {
    dataSourceGroupName = context.getGroupName();
    Map<String, DataSource> dataSources = InstanceFactory.getBeansOfType(DataSource.class);
    if (dataSources.size() == 1) {
        dataSource = new ArrayList<>(dataSources.values()).get(0);
    } else {
        for (String beanName : dataSources.keySet()) {
            if (beanName.startsWith(dataSourceGroupName)) {
                dataSource = dataSources.get(beanName);
                break;
            }
        }
    }
    defaultCacheExpire = Long.parseLong(MybatisConfigs.getProperty(context.getGroupName(), MybatisConfigs.CACHE_EXPIRE_SECONDS, "0"));
    List<MapperMetadata> mappers = MybatisMapperParser.getMapperMetadatas(context.getGroupName());
    Class<BaseEntity> baseEntityClass = BaseEntity.class;
    QueryCacheMethodMetadata methodCache = null;
    for (MapperMetadata mm : mappers) {
        if (mm.getMapperClass().isAnnotationPresent(CacheIgnore.class))
            continue;
        if (!baseEntityClass.isAssignableFrom(mm.getEntityClass())) {
            logger.warn("[{}] not extends from [{}],ignore register auto cache!!!!", mm.getEntityClass().getName(), baseEntityClass.getName());
            continue;
        }
        Class<?> mapperClass = mm.getMapperClass();
        // 按主键查询方法定义
        QueryCacheMethodMetadata queryByPKMethod = generateQueryByPKMethod(mapperClass, mm.getEntityClass());
        if (queryByPKMethod == null)
            continue;
        Map<String, QueryCacheMethodMetadata> tmpMap = new HashMap<>();
        // 主键查询方法
        tmpMap.put(queryByPKMethod.methodName, queryByPKMethod);
        String keyPatternForPK = queryByPKMethod.keyPattern;
        // 接口定义的自动缓存方法
        for (MapperMethod method : mm.getMapperMethods().values()) {
            if (method.getMethod().isAnnotationPresent(Cache.class)) {
                if (tmpMap.containsKey(method.getFullName()))
                    continue;
                methodCache = generateQueryMethodCacheByMethod(mm, method);
                tmpMap.put(method.getFullName(), methodCache);
                logger.info("解析查询方法{}自动缓存配置 ok,keyPattern:[{}]", methodCache.methodName, methodCache.keyPattern);
            }
        }
        // 缓存需要自动缓存的mapper
        cacheEnableMappers.add(mm.getMapperClass().getName());
        logger.info("解析查询方法{}自动缓存配置 ok,keyPattern:[{}]", queryByPKMethod.methodName, queryByPKMethod.keyPattern);
        queryCacheMethods.put(mapperClass.getName(), tmpMap);
        // 更新缓存方法
        generateUpdateByPkCacheMethod(mapperClass, mm.getEntityClass(), keyPatternForPK);
    }
    // 
    logger.info(">>>customUpdateCacheMapppings:{}", customUpdateCacheMapppings);
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) BaseEntity(com.mendmix.mybatis.core.BaseEntity) MapperMetadata(com.mendmix.mybatis.metadata.MapperMetadata) DataSource(javax.sql.DataSource) MapperMethod(com.mendmix.mybatis.metadata.MapperMetadata.MapperMethod)

Aggregations

BaseEntity (com.mendmix.mybatis.core.BaseEntity)2 HashMap (java.util.HashMap)2 AuthUser (com.mendmix.common.model.AuthUser)1 MybatisHanlerInitException (com.mendmix.mybatis.exception.MybatisHanlerInitException)1 MapperMetadata (com.mendmix.mybatis.metadata.MapperMetadata)1 MapperMethod (com.mendmix.mybatis.metadata.MapperMetadata.MapperMethod)1 Serializable (java.io.Serializable)1 ArrayList (java.util.ArrayList)1 Map (java.util.Map)1 DataSource (javax.sql.DataSource)1