perf[orm]: 简化orm,并删除无用代码

This commit is contained in:
jaysunxiao
2021-06-26 12:21:42 +08:00
parent 1babd554e4
commit 8b65c6601b
5 changed files with 83 additions and 140 deletions
@@ -18,7 +18,6 @@ import com.zfoo.orm.manager.IOrmManager;
import com.zfoo.orm.manager.OrmManager;
import com.zfoo.orm.model.accessor.IAccessor;
import com.zfoo.orm.model.query.IQuery;
import com.zfoo.orm.schema.OrmProcessor;
import com.zfoo.protocol.util.ReflectionUtils;
import com.zfoo.scheduler.SchedulerContext;
import org.slf4j.Logger;
@@ -88,13 +87,7 @@ public class OrmContext implements ApplicationListener<ApplicationContextEvent>,
instance.ormManager = applicationContext.getBean(IOrmManager.class);
instance.ormManager.initBefore();
var beanNames = applicationContext.getBeanDefinitionNames();
var processor = applicationContext.getBean(OrmProcessor.class);
for (var beanName : beanNames) {
processor.postProcessAfterInitialization(applicationContext.getBean(beanName), beanName);
}
instance.ormManager.inject();
instance.ormManager.initAfter();
} else if (event instanceof ContextClosedEvent) {
shutdownBefore();
@@ -29,6 +29,8 @@ public interface IOrmManager {
void initBefore();
void inject();
void initAfter();
@@ -19,7 +19,9 @@ import com.mongodb.ServerAddress;
import com.mongodb.client.*;
import com.mongodb.client.model.IndexOptions;
import com.mongodb.client.model.Indexes;
import com.zfoo.orm.OrmContext;
import com.zfoo.orm.model.anno.EntityCache;
import com.zfoo.orm.model.anno.EntityCachesInjection;
import com.zfoo.orm.model.cache.EntityCaches;
import com.zfoo.orm.model.cache.IEntityCaches;
import com.zfoo.orm.model.config.OrmConfig;
@@ -28,6 +30,7 @@ import com.zfoo.orm.model.vo.EntityDef;
import com.zfoo.protocol.collection.CollectionUtils;
import com.zfoo.protocol.util.AssertionUtils;
import com.zfoo.protocol.util.JsonUtils;
import com.zfoo.protocol.util.ReflectionUtils;
import com.zfoo.protocol.util.StringUtils;
import com.zfoo.util.net.HostAndPort;
import org.bson.Document;
@@ -42,6 +45,8 @@ import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
@@ -158,6 +163,81 @@ public class OrmManager implements IOrmManager {
}
}
@Override
public void inject() {
var applicationContext = OrmContext.getApplicationContext();
var beanNames = applicationContext.getBeanDefinitionNames();
for (var beanName : beanNames) {
var bean = applicationContext.getBean(beanName);
ReflectionUtils.filterFieldsInClass(bean.getClass()
, field -> field.isAnnotationPresent(EntityCachesInjection.class)
, field -> {
Type type = field.getGenericType();
if (!(type instanceof ParameterizedType)) {
throw new RuntimeException(StringUtils.format("变量[{}]的类型不是泛型类", field.getName()));
}
Type[] types = ((ParameterizedType) type).getActualTypeArguments();
Class<? extends IEntity<?>> clazz = (Class<? extends IEntity<?>>) types[1];
IEntityCaches<?, ?> entityCaches = OrmContext.getOrmManager().getEntityCaches(clazz);
if (entityCaches == null) {
throw new RuntimeException(StringUtils.format("实体缓存对象[entityCaches:{}]不存在", clazz));
}
ReflectionUtils.makeAccessible(field);
ReflectionUtils.setField(field, bean, entityCaches);
entityCaches.setUsable(true);
});
}
}
@Override
public void initAfter() {
var unusableEntityClassList = entityCachesMap.entrySet().stream()
.filter(it -> !it.getValue().isUsable())
.map(it -> it.getKey())
.collect(Collectors.toList());
unusableEntityClassList.forEach(it -> {
entityCachesMap.remove(it);
});
}
@Override
public <E extends IEntity<?>> IEntityCaches<?, E> getEntityCaches(Class<E> clazz) {
return (IEntityCaches<?, E>) entityCachesMap.get(clazz);
}
@Override
public Collection<IEntityCaches<?, ?>> getAllEntityCaches() {
return Collections.unmodifiableCollection(entityCachesMap.values());
}
@Override
public ClientSession getClientSession() {
return mongoClient.startSession();
}
@Override
public <E extends IEntity<?>> MongoCollection<E> getCollection(Class<E> entityClazz) {
var collectionName = collectionNameMap.get(entityClazz);
if (collectionName == null) {
collectionName = StringUtils.substringBeforeLast(StringUtils.uncapitalize(entityClazz.getSimpleName()), "Entity");
collectionNameMap.put(entityClazz, collectionName);
}
return mongodbDatabase.getCollection(collectionName, entityClazz);
}
@Override
public MongoCollection<Document> getCollection(String collection) {
return mongodbDatabase.getCollection(collection);
}
private Map<Class<? extends IEntity<?>>, EntityDef> scanEntity() {
var cacheDefMap = new HashMap<Class<? extends IEntity<?>>, EntityDef>();
var entityPackage = ormConfig.getEntityPackage();
@@ -206,49 +286,4 @@ public class OrmManager implements IOrmManager {
throw new RuntimeException("无法读取实体信息:" + e);
}
}
@Override
public void initAfter() {
var unusableStorageClassList = entityCachesMap.entrySet().stream()
.filter(it -> !it.getValue().isUsable())
.map(it -> it.getKey())
.collect(Collectors.toList());
unusableStorageClassList.forEach(it -> {
entityCachesMap.remove(it);
});
}
@Override
public <E extends IEntity<?>> IEntityCaches<?, E> getEntityCaches(Class<E> clazz) {
return (IEntityCaches<?, E>) entityCachesMap.get(clazz);
}
@Override
public Collection<IEntityCaches<?, ?>> getAllEntityCaches() {
return Collections.unmodifiableCollection(entityCachesMap.values());
}
@Override
public ClientSession getClientSession() {
return mongoClient.startSession();
}
@Override
public <E extends IEntity<?>> MongoCollection<E> getCollection(Class<E> entityClazz) {
var collectionName = collectionNameMap.get(entityClazz);
if (collectionName == null) {
collectionName = StringUtils.substringBeforeLast(StringUtils.uncapitalize(entityClazz.getSimpleName()), "Entity");
collectionNameMap.put(entityClazz, collectionName);
}
return mongodbDatabase.getCollection(collectionName, entityClazz);
}
@Override
public MongoCollection<Document> getCollection(String collection) {
return mongodbDatabase.getCollection(collection);
}
}
@@ -51,12 +51,6 @@ public class OrmDefinitionParser implements BeanDefinitionParser {
builder = BeanDefinitionBuilder.rootBeanDefinition(clazz);
parserContext.getRegistry().registerBeanDefinition(name, builder.getBeanDefinition());
// 注册OrmProcessor
clazz = OrmProcessor.class;
name = StringUtils.uncapitalize(clazz.getSimpleName());
builder = BeanDefinitionBuilder.rootBeanDefinition(clazz);
parserContext.getRegistry().registerBeanDefinition(name, builder.getBeanDefinition());
// 注册OrmManager
clazz = OrmManager.class;
name = StringUtils.uncapitalize(clazz.getSimpleName());
@@ -1,81 +0,0 @@
/*
* Copyright (C) 2020 The zfoo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations under the License.
*/
package com.zfoo.orm.schema;
import com.zfoo.orm.OrmContext;
import com.zfoo.orm.model.anno.EntityCachesInjection;
import com.zfoo.orm.model.cache.IEntityCaches;
import com.zfoo.orm.model.entity.IEntity;
import com.zfoo.protocol.util.ReflectionUtils;
import com.zfoo.protocol.util.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.function.Consumer;
import java.util.function.Predicate;
/**
* FactoryBean,在某些情况下,实例化Bean非常复杂,如果按照传统的方式,则需要在bean标签中配置大量的信息,
* 配置方式的灵活性是受到限制的,这时采用编码的方式可能会获得一个简单的方案
*
* @author jaysunxiao
* @version 3.0
*/
public class OrmProcessor implements BeanPostProcessor {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (OrmContext.getOrmContext() == null) {
return bean;
}
ReflectionUtils.filterFieldsInClass(bean.getClass()
, new Predicate<Field>() {
@Override
public boolean test(Field field) {
if (!field.isAnnotationPresent(EntityCachesInjection.class)) {
return false;
}
return true;
}
}
, new Consumer<Field>() {
@Override
public void accept(Field field) {
Type type = field.getGenericType();
if (!(type instanceof ParameterizedType)) {
throw new RuntimeException(StringUtils.format("变量[{}]的类型不是泛型类", field.getName()));
}
Type[] types = ((ParameterizedType) type).getActualTypeArguments();
Class<? extends IEntity<?>> clazz = (Class<? extends IEntity<?>>) types[1];
IEntityCaches<?, ?> entityCaches = OrmContext.getOrmManager().getEntityCaches(clazz);
if (entityCaches == null) {
throw new RuntimeException(StringUtils.format("实体缓存对象[entityCaches:{}]不存在", clazz));
}
ReflectionUtils.makeAccessible(field);
ReflectionUtils.setField(field, bean, entityCaches);
entityCaches.setUsable(true);
}
});
return bean;
}
}