bean容器重构ing

This commit is contained in:
aoshiguchen
2022-07-02 19:59:54 +08:00
parent 9cfbcaba66
commit 1429c78278
18 changed files with 491 additions and 296 deletions
@@ -39,11 +39,16 @@ public class Aop {
private static final Cache<Class<?>, Object> proxyBeanCache = new MemoryCache<>();
public static <T> T get(Class<T> clazz) {
return (T)LockUtil.doubleCheckProcess(() -> !proxyBeanCache.containsKey(clazz),
clazz,
() -> proxyBeanCache.set(clazz, getProxyFactory(clazz).get(clazz)),
() -> proxyBeanCache.get(clazz)
);
try {
return (T)LockUtil.doubleCheckProcess(() -> !proxyBeanCache.containsKey(clazz),
clazz,
() -> proxyBeanCache.set(clazz, getProxyFactory(clazz).get(clazz)),
() -> proxyBeanCache.get(clazz)
);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
@@ -55,7 +55,7 @@ public class InterceptorFactory {
* @param <T>
* @return
*/
private static <T> T getOrNewCacheBean(Class<T> clazz, Cache cache) {
private static <T> T getOrNewCacheBean(Class<T> clazz, Cache cache) throws Exception {
return (T)LockUtil.doubleCheckProcess(() -> !cache.containsKey(clazz),
clazz,
() -> {
@@ -80,7 +80,12 @@ public class InterceptorFactory {
* @return
*/
public static <T extends Interceptor> T get(Class<? extends Interceptor> clazz) {
return (T)getOrNewCacheBean(clazz, interceptorCache);
try {
return (T)getOrNewCacheBean(clazz, interceptorCache);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
@@ -90,7 +95,12 @@ public class InterceptorFactory {
* @return
*/
private static <T extends Filter> T getFilter(Class<? extends Filter> clazz) {
return (T)getOrNewCacheBean(clazz, filterCache);
try {
return (T)getOrNewCacheBean(clazz, filterCache);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
@@ -113,7 +123,12 @@ public class InterceptorFactory {
* @return
*/
private static <T extends ResultAdvice> T getResultAdvice(Class<? extends ResultAdvice> clazz) {
return (T)getOrNewCacheBean(clazz, resultAdviceCache);
try {
return (T)getOrNewCacheBean(clazz, resultAdviceCache);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
@@ -136,7 +151,12 @@ public class InterceptorFactory {
* @return
*/
private static <T extends ExceptionHandler> T getExceptionHandler(Class<? extends ExceptionHandler> clazz) {
return (T)getOrNewCacheBean(clazz, exceptionHandlerCache);
try {
return (T)getOrNewCacheBean(clazz, exceptionHandlerCache);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
@@ -160,25 +180,30 @@ public class InterceptorFactory {
public static List<Interceptor> getListByTargetMethod(Method targetMethod) {
Assert.notNull(targetMethod, "目标方法不能为空!");
return LockUtil.doubleCheckProcess(() -> !methodInterceptorListMap.containsKey(targetMethod),
targetMethod,
() -> {
List<Interceptor> interceptors = new ArrayList<>();
interceptors.addAll(globalInterceptorList);
addInterceptorByAnnotation(interceptors, targetMethod.getDeclaringClass().getAnnotation(Intercept.class));
addInterceptorByAnnotation(interceptors, targetMethod.getAnnotation(Intercept.class));
// 如果被代理方法所属类是一个接口,那么该接口所有继承接口链路上的注解都对该方法生效
if (ClassUtil.isInterface(targetMethod.getDeclaringClass())) {
List<Class<?>> interfaceList = ReflectUtil.getInterfaceAll(targetMethod.getDeclaringClass());
if (CollectionUtil.notEmpty(interfaceList)) {
for (Class<?> clazz : interfaceList) {
addInterceptorByAnnotation(interceptors, clazz.getAnnotation(Intercept.class));
try {
return LockUtil.doubleCheckProcess(() -> !methodInterceptorListMap.containsKey(targetMethod),
targetMethod,
() -> {
List<Interceptor> interceptors = new ArrayList<>();
interceptors.addAll(globalInterceptorList);
addInterceptorByAnnotation(interceptors, targetMethod.getDeclaringClass().getAnnotation(Intercept.class));
addInterceptorByAnnotation(interceptors, targetMethod.getAnnotation(Intercept.class));
// 如果被代理方法所属类是一个接口,那么该接口所有继承接口链路上的注解都对该方法生效
if (ClassUtil.isInterface(targetMethod.getDeclaringClass())) {
List<Class<?>> interfaceList = ReflectUtil.getInterfaceAll(targetMethod.getDeclaringClass());
if (CollectionUtil.notEmpty(interfaceList)) {
for (Class<?> clazz : interfaceList) {
addInterceptorByAnnotation(interceptors, clazz.getAnnotation(Intercept.class));
}
}
}
}
methodInterceptorListMap.put(targetMethod, interceptors);
},
() -> methodInterceptorListMap.get(targetMethod));
methodInterceptorListMap.put(targetMethod, interceptors);
},
() -> methodInterceptorListMap.get(targetMethod));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
@@ -33,6 +33,5 @@ public interface CodeBlock {
/**
* 执行
*/
void execute();
void execute() throws Exception;
}
@@ -371,25 +371,29 @@ public abstract class AbstractBeanFactory implements BeanFactory, BeanRegistry,
* @return
*/
protected <T> T getOrNew(BeanWrapper bean) throws BeanException {
return (T)LockUtil.doubleCheckProcess(
() -> !(BeanStatus.INIT == bean.getStatus() || BeanStatus.RUNNING == bean.getStatus()),
bean,
() -> {
if (BeanStatus.REGISTER == bean.getStatus()) {
dependencyCheck(bean);
}
if (BeanStatus.DEPENDENCY_CHECKING == bean.getStatus()) {
newInstance(bean);
}
if (BeanStatus.INSTANCE == bean.getStatus()) {
inject(bean);
}
if (BeanStatus.INJECT == bean.getStatus()) {
bean.init();
}
},
() -> bean.getInstance()
);
try {
return (T)LockUtil.doubleCheckProcess(
() -> !(BeanStatus.INIT == bean.getStatus() || BeanStatus.RUNNING == bean.getStatus()),
bean,
() -> {
if (BeanStatus.REGISTER == bean.getStatus()) {
dependencyCheck(bean);
}
if (BeanStatus.DEPENDENCY_CHECKING == bean.getStatus()) {
newInstance(bean);
}
if (BeanStatus.INSTANCE == bean.getStatus()) {
inject(bean);
}
if (BeanStatus.INJECT == bean.getStatus()) {
bean.init();
}
},
() -> bean.getInstance()
);
} catch (Exception e) {
throw new BeanException(String.format("Bean[type:%s name:%s] getOrNew bean实例异常!"), e);
}
}
/**
@@ -398,7 +402,7 @@ public abstract class AbstractBeanFactory implements BeanFactory, BeanRegistry,
* @return
* @throws BeanException
*/
protected abstract boolean dependencyCheck(BeanWrapper bean) throws BeanException;
protected abstract void dependencyCheck(BeanWrapper bean) throws Exception;
/**
* 实例化
@@ -415,5 +419,5 @@ public abstract class AbstractBeanFactory implements BeanFactory, BeanRegistry,
* @return
* @throws BeanException
*/
protected abstract boolean inject(BeanWrapper bean) throws BeanException;
protected abstract void inject(BeanWrapper bean) throws Exception;
}
@@ -114,26 +114,31 @@ public class BeanWrapper implements LifeCycle {
}
private boolean newInstance0() {
return LockUtil.doubleCheckProcess(() -> !hasInstance(),
this,
() -> {
try {
// 暂时先只支持yml配置
Configuration configuration = type.getAnnotation(Configuration.class);
if (null != configuration) {
instance = ConfigUtil.getYmlConfig(type);
} else if (ClassUtil.isInterface(type)) {
instance = Aop.get(type);
} else {
// 由编码规避没有无参构造器的问题
instance = type.newInstance();
try {
return LockUtil.doubleCheckProcess(() -> !hasInstance(),
this,
() -> {
try {
// 暂时先只支持yml配置
Configuration configuration = type.getAnnotation(Configuration.class);
if (null != configuration) {
instance = ConfigUtil.getYmlConfig(type);
} else if (ClassUtil.isInterface(type)) {
instance = Aop.get(type);
} else {
// 由编码规避没有无参构造器的问题
instance = type.newInstance();
}
} catch (Exception e) {
// ignore
}
} catch (Exception e) {
// ignore
}
},
() -> hasInstance()
);
},
() -> hasInstance()
);
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
private void inject(ApplicationContext context) {
@@ -21,15 +21,17 @@
*/
package fun.asgc.neutrino.core.bean;
import fun.asgc.neutrino.core.annotation.Autowired;
import fun.asgc.neutrino.core.annotation.Lazy;
import fun.asgc.neutrino.core.annotation.Order;
import fun.asgc.neutrino.core.exception.BeanException;
import fun.asgc.neutrino.core.runner.ApplicationRunner;
import fun.asgc.neutrino.core.util.ClassUtil;
import fun.asgc.neutrino.core.util.CollectionUtil;
import fun.asgc.neutrino.core.util.*;
import lombok.extern.slf4j.Slf4j;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
/**
@@ -69,18 +71,51 @@ public class SimpleBeanFactory extends AbstractBeanFactory {
}
@Override
protected boolean dependencyCheck(BeanWrapper bean) throws BeanException {
return false;
protected void dependencyCheck(BeanWrapper bean) throws Exception {
LockUtil.doubleCheckProcess(
() -> BeanStatus.REGISTER == bean.getStatus(),
bean,
() -> {
Set<Field> fieldSet = ReflectUtil.getInheritChainDeclaredFieldSet(bean.getType());
if (CollectionUtil.notEmpty(fieldSet)) {
fieldSet.forEach(field -> {
Autowired autowired = field.getAnnotation(Autowired.class);
if (null == autowired) {
return;
}
String name = field.getName();
// TODO
});
}
}
);
}
@Override
protected <T> T newInstance(BeanWrapper bean) throws BeanException {
return null;
try {
return LockUtil.doubleCheckProcess(
() -> BeanStatus.DEPENDENCY_CHECKING == bean.getStatus(),
bean,
() -> {
bean.getClass().newInstance();
},
() -> (T)bean.getInstance()
);
} catch (Exception e) {
throw new BeanException(String.format("Bean[type:%s name:%s] 实例化异常", bean.getType().getName(), bean.getName()), e);
}
}
@Override
protected boolean inject(BeanWrapper bean) throws BeanException {
return false;
protected void inject(BeanWrapper bean) throws Exception {
LockUtil.doubleCheckProcess(
() -> BeanStatus.INSTANCE == bean.getStatus(),
bean,
() -> {
// TODO
}
);
}
@Override
@@ -53,11 +53,15 @@ public class MemoryCacheGroup<K,V> implements CacheGroup<K,V> {
@Override
public void set(String group, K k, V v) {
LockUtil.doubleCheckProcess(() -> !cacheGroup.containsKey(group),
group,
() -> cacheGroup.set(group, new MemoryCache<>())
);
cacheGroup.get(group).set(k, v);
try {
LockUtil.doubleCheckProcess(() -> !cacheGroup.containsKey(group),
group,
() -> cacheGroup.set(group, new MemoryCache<>())
);
cacheGroup.get(group).set(k, v);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
@@ -40,22 +40,34 @@ public class LifeCycleManager {
public synchronized void init(CodeBlock codeBlock) {
if (this.status == LifeCycleStatus.CREATE) {
codeBlock.execute();
this.status = LifeCycleStatus.INIT;
try {
codeBlock.execute();
this.status = LifeCycleStatus.INIT;
} catch (Exception e) {
e.printStackTrace();
}
}
}
public synchronized void run(CodeBlock codeBlock) {
if (this.status == LifeCycleStatus.INIT) {
codeBlock.execute();
this.status = LifeCycleStatus.RUN;
try {
codeBlock.execute();
this.status = LifeCycleStatus.RUN;
} catch (Exception e) {
e.printStackTrace();
}
}
}
public synchronized void destroy(CodeBlock codeBlock) {
if (this.status != LifeCycleStatus.DESTROY) {
codeBlock.execute();
this.status = LifeCycleStatus.DESTROY;
try {
codeBlock.execute();
this.status = LifeCycleStatus.DESTROY;
} catch (Exception e) {
e.printStackTrace();
}
}
}
@@ -51,7 +51,7 @@ public class SqlMapperInterceptor implements Interceptor {
private static final Cache<Method, Params> paramsCache = new MemoryCache<>();
@Override
public void intercept(Invocation inv) throws SQLException {
public void intercept(Invocation inv) throws Exception {
Assert.notNull(jdbcTemplate, "JdbcTemplate未注入,调用失败!");
Params params = getParams(inv.getTargetMethod());
if (null == params) {
@@ -85,7 +85,7 @@ public class SqlMapperInterceptor implements Interceptor {
* @param method
* @return
*/
private static Params getParams(Method method) {
private static Params getParams(Method method) throws Exception {
return LockUtil.doubleCheckProcess(
() -> !paramsCache.containsKey(method),
method,
@@ -58,12 +58,17 @@ public class DbCache {
* @return
*/
public static String toColumnName(String s) {
return LockUtil.doubleCheckProcess(
() -> !nameMappingCache.containsKey(GROUP_COLUMN_NAME_TO, s),
GROUP_COLUMN_NAME_TO,
() -> nameMappingCache.set(GROUP_COLUMN_NAME_TO, s, DefaultColumnNameConvert.getInstance().to(s)),
() -> nameMappingCache.get(GROUP_COLUMN_NAME_TO, s)
);
try {
return LockUtil.doubleCheckProcess(
() -> !nameMappingCache.containsKey(GROUP_COLUMN_NAME_TO, s),
GROUP_COLUMN_NAME_TO,
() -> nameMappingCache.set(GROUP_COLUMN_NAME_TO, s, DefaultColumnNameConvert.getInstance().to(s)),
() -> nameMappingCache.get(GROUP_COLUMN_NAME_TO, s)
);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
@@ -72,12 +77,17 @@ public class DbCache {
* @return
*/
public static String fromColumnName(String s) {
return LockUtil.doubleCheckProcess(
() -> !nameMappingCache.containsKey(GROUP_COLUMN_NAME_FROM, s),
GROUP_COLUMN_NAME_FROM,
() -> nameMappingCache.set(GROUP_COLUMN_NAME_FROM, s, DefaultColumnNameConvert.getInstance().from(s)),
() -> nameMappingCache.get(GROUP_COLUMN_NAME_FROM, s)
);
try {
return LockUtil.doubleCheckProcess(
() -> !nameMappingCache.containsKey(GROUP_COLUMN_NAME_FROM, s),
GROUP_COLUMN_NAME_FROM,
() -> nameMappingCache.set(GROUP_COLUMN_NAME_FROM, s, DefaultColumnNameConvert.getInstance().from(s)),
() -> nameMappingCache.get(GROUP_COLUMN_NAME_FROM, s)
);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
@@ -86,12 +96,17 @@ public class DbCache {
* @return
*/
public static String toTableName(String s) {
return LockUtil.doubleCheckProcess(
() -> !nameMappingCache.containsKey(GROUP_TABLE_NAME_TO, s),
GROUP_TABLE_NAME_TO,
() -> nameMappingCache.set(GROUP_TABLE_NAME_TO, s, DefaultTableNameConvert.getInstance().to(s)),
() -> nameMappingCache.get(GROUP_TABLE_NAME_TO, s)
);
try {
return LockUtil.doubleCheckProcess(
() -> !nameMappingCache.containsKey(GROUP_TABLE_NAME_TO, s),
GROUP_TABLE_NAME_TO,
() -> nameMappingCache.set(GROUP_TABLE_NAME_TO, s, DefaultTableNameConvert.getInstance().to(s)),
() -> nameMappingCache.get(GROUP_TABLE_NAME_TO, s)
);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
@@ -100,20 +115,25 @@ public class DbCache {
* @return
*/
public static String toTableName(Class<?> clazz) {
return LockUtil.doubleCheckProcess(() -> !classTableNameCache.containsKey(clazz),
clazz,
() -> {
Table table = clazz.getAnnotation(Table.class);
String tableName;
if (null != table && StringUtil.notEmpty(table.value())) {
tableName = table.value();
} else {
tableName = toTableName(TypeUtil.getSimpleName(clazz));
}
classTableNameCache.set(clazz, tableName);
},
() -> classTableNameCache.get(clazz)
);
try {
return LockUtil.doubleCheckProcess(() -> !classTableNameCache.containsKey(clazz),
clazz,
() -> {
Table table = clazz.getAnnotation(Table.class);
String tableName;
if (null != table && StringUtil.notEmpty(table.value())) {
tableName = table.value();
} else {
tableName = toTableName(TypeUtil.getSimpleName(clazz));
}
classTableNameCache.set(clazz, tableName);
},
() -> classTableNameCache.get(clazz)
);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
@@ -122,12 +142,17 @@ public class DbCache {
* @return
*/
public static String fromTableName(String s) {
return LockUtil.doubleCheckProcess(
() -> !nameMappingCache.containsKey(GROUP_TABLE_NAME_FROM, s),
GROUP_TABLE_NAME_FROM,
() -> nameMappingCache.set(GROUP_TABLE_NAME_FROM, s, DefaultTableNameConvert.getInstance().from(s)),
() -> nameMappingCache.get(GROUP_TABLE_NAME_FROM, s)
);
try {
return LockUtil.doubleCheckProcess(
() -> !nameMappingCache.containsKey(GROUP_TABLE_NAME_FROM, s),
GROUP_TABLE_NAME_FROM,
() -> nameMappingCache.set(GROUP_TABLE_NAME_FROM, s, DefaultTableNameConvert.getInstance().from(s)),
() -> nameMappingCache.get(GROUP_TABLE_NAME_FROM, s)
);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
@@ -137,25 +162,30 @@ public class DbCache {
* @return
*/
public static List<Field> getField(Class<?> clazz, String column) {
return LockUtil.doubleCheckProcess(
() -> !fieldToColumnCache.containsKey(clazz),
fieldToColumnCacheLock,
() -> initFieldCache(clazz),
() -> {
List<Field> list = Lists.newArrayList();
Cache<Field, String> cache = fieldToColumnCache.get(clazz);
if (null == cache || cache.isEmpty()) {
try {
return LockUtil.doubleCheckProcess(
() -> !fieldToColumnCache.containsKey(clazz),
fieldToColumnCacheLock,
() -> initFieldCache(clazz),
() -> {
List<Field> list = Lists.newArrayList();
Cache<Field, String> cache = fieldToColumnCache.get(clazz);
if (null == cache || cache.isEmpty()) {
return list;
}
for (Field field : cache.keySet()) {
if (cache.get(field).equals(column)) {
list.add(field);
}
}
return list;
}
for (Field field : cache.keySet()) {
if (cache.get(field).equals(column)) {
list.add(field);
}
}
return list;
}
);
);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
@@ -164,20 +194,25 @@ public class DbCache {
* @return
*/
public static List<Field> getFieldList(Class<?> clazz) {
return LockUtil.doubleCheckProcess(
() -> !fieldToColumnCache.containsKey(clazz),
fieldToColumnCacheLock,
() -> initFieldCache(clazz),
() -> {
List<Field> list = Lists.newArrayList();
Cache<Field, String> cache = fieldToColumnCache.get(clazz);
if (null == cache || cache.isEmpty()) {
try {
return LockUtil.doubleCheckProcess(
() -> !fieldToColumnCache.containsKey(clazz),
fieldToColumnCacheLock,
() -> initFieldCache(clazz),
() -> {
List<Field> list = Lists.newArrayList();
Cache<Field, String> cache = fieldToColumnCache.get(clazz);
if (null == cache || cache.isEmpty()) {
return list;
}
list.addAll(cache.keySet());
return list;
}
list.addAll(cache.keySet());
return list;
}
);
);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
@@ -186,26 +221,36 @@ public class DbCache {
* @return
*/
public static Cache<Field, String> getFieldCache(Class<?> clazz) {
return LockUtil.doubleCheckProcess(
() -> !fieldToColumnCache.containsKey(clazz),
clazz,
() -> initFieldCache(clazz),
() -> fieldToColumnCache.get(clazz)
);
try {
return LockUtil.doubleCheckProcess(
() -> !fieldToColumnCache.containsKey(clazz),
clazz,
() -> initFieldCache(clazz),
() -> fieldToColumnCache.get(clazz)
);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String getColumnNameByField(Field field) {
return LockUtil.doubleCheckProcess(
() -> !fieldToColumnCache.containsKey(field.getDeclaringClass()),
fieldToColumnCacheLock,
() -> initFieldCache(field.getDeclaringClass()),
() -> {
if (!fieldToColumnCache.containsKey(field.getDeclaringClass()) || !fieldToColumnCache.get(field.getDeclaringClass()).containsKey(field)) {
return null;
try {
return LockUtil.doubleCheckProcess(
() -> !fieldToColumnCache.containsKey(field.getDeclaringClass()),
fieldToColumnCacheLock,
() -> initFieldCache(field.getDeclaringClass()),
() -> {
if (!fieldToColumnCache.containsKey(field.getDeclaringClass()) || !fieldToColumnCache.get(field.getDeclaringClass()).containsKey(field)) {
return null;
}
return fieldToColumnCache.get(field.getDeclaringClass()).get(field);
}
return fieldToColumnCache.get(field.getDeclaringClass()).get(field);
}
);
);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
@@ -65,17 +65,17 @@ public class NeutrinoLauncher {
stopWatch.start();
environmentInit();
// this.applicationContainer = new DefaultApplicationContainer(environment);
// SystemUtil.RunContext runContext = SystemUtil.waitProcessDestroy(() -> {
// this.applicationContainer.destroy();
// log.info("Application already stop.");
// });
ApplicationContext context = new ApplicationContext(environment);
context.run();
this.applicationContainer = new DefaultApplicationContainer(environment);
SystemUtil.RunContext runContext = SystemUtil.waitProcessDestroy(() -> {
context.destroy();
this.applicationContainer.destroy();
log.info("Application already stop.");
});
// ApplicationContext context = new ApplicationContext(environment);
// context.run();
// SystemUtil.RunContext runContext = SystemUtil.waitProcessDestroy(() -> {
// context.destroy();
// log.info("Application already stop.");
// });
stopWatch.stop();
printLog(environment, stopWatch);
@@ -35,12 +35,17 @@ import java.util.Date;
public class DateUtil {
private static final Cache<String, SimpleDateFormat> sdfCache = new MemoryCache<>();
private static SimpleDateFormat getSimpleDateFormat(String format) {
return LockUtil.doubleCheckProcess(
() -> !sdfCache.containsKey(format),
format,
() -> sdfCache.set(format, new SimpleDateFormat(format)),
() -> sdfCache.get(format)
);
try {
return LockUtil.doubleCheckProcess(
() -> !sdfCache.containsKey(format),
format,
() -> sdfCache.set(format, new SimpleDateFormat(format)),
() -> sdfCache.get(format)
);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
@@ -40,7 +40,7 @@ public class LockUtil {
* @param lock
* @param lockProcess
*/
public static void doubleCheckProcess(BooleanSupplier isLock, Object lock, CodeBlock lockProcess) {
public static void doubleCheckProcess(BooleanSupplier isLock, Object lock, CodeBlock lockProcess) throws Exception {
if (isLock.getAsBoolean()) {
synchronized (lock) {
if (isLock.getAsBoolean()) {
@@ -57,9 +57,8 @@ public class LockUtil {
* @param lockProcess
* @param nonLockProcess
*/
public static <T> T doubleCheckProcess(BooleanSupplier isLock, Object lock, CodeBlock lockProcess, Supplier<T> nonLockProcess) {
public static <T> T doubleCheckProcess(BooleanSupplier isLock, Object lock, CodeBlock lockProcess, Supplier<T> nonLockProcess) throws Exception {
doubleCheckProcess(isLock, lock, lockProcess);
return nonLockProcess.get();
}
}
@@ -57,14 +57,19 @@ public class ReflectUtil {
* @return
*/
public static Set<Field> getFields(Class<?> clazz) {
return kvProcess(fieldsCache, clazz, c -> {
Field[] fields = c.getFields();
Set<Field> fieldSet = new HashSet<>();
if (ArrayUtil.notEmpty(fields)) {
fieldSet = Stream.of(fields).collect(Collectors.toSet());
}
return fieldSet;
});
try {
return kvProcess(fieldsCache, clazz, c -> {
Field[] fields = c.getFields();
Set<Field> fieldSet = new HashSet<>();
if (ArrayUtil.notEmpty(fields)) {
fieldSet = Stream.of(fields).collect(Collectors.toSet());
}
return fieldSet;
});
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
@@ -73,14 +78,19 @@ public class ReflectUtil {
* @return
*/
public static Set<Field> getDeclaredFields(Class<?> clazz) {
return kvProcess(declaredFieldsCache, clazz, c -> {
Field[] fields = c.getDeclaredFields();
Set<Field> fieldSet = new HashSet<>();
if (ArrayUtil.notEmpty(fields)) {
fieldSet = Stream.of(fields).collect(Collectors.toSet());
}
return fieldSet;
});
try {
return kvProcess(declaredFieldsCache, clazz, c -> {
Field[] fields = c.getDeclaredFields();
Set<Field> fieldSet = new HashSet<>();
if (ArrayUtil.notEmpty(fields)) {
fieldSet = Stream.of(fields).collect(Collectors.toSet());
}
return fieldSet;
});
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
@@ -98,29 +108,34 @@ public class ReflectUtil {
* @return
*/
public static Set<Field> getInheritChainDeclaredFieldSet(Class<?> clazz, Set<Class<?>> ignoreClasses) {
return kvProcess(inheritChainDeclaredFieldSetCache,
clazz,
(Class<?> c) -> {
Set<String> nameSet = new HashSet<>();
Set<Field> set = new HashSet<>();
Set<Class<?>> ignores = null == ignoreClasses ? new HashSet<>() : ignoreClasses;
while (null != c && !ignores.contains(c)) {
Set<Field> fields = getDeclaredFields(c);
if (CollectionUtil.notEmpty(fields)) {
for (Field field : fields) {
if (field.getName().equals("this$0") || nameSet.contains(field.getName())) {
continue;
try {
return kvProcess(inheritChainDeclaredFieldSetCache,
clazz,
(Class<?> c) -> {
Set<String> nameSet = new HashSet<>();
Set<Field> set = new HashSet<>();
Set<Class<?>> ignores = null == ignoreClasses ? new HashSet<>() : ignoreClasses;
while (null != c && !ignores.contains(c)) {
Set<Field> fields = getDeclaredFields(c);
if (CollectionUtil.notEmpty(fields)) {
for (Field field : fields) {
if (field.getName().equals("this$0") || nameSet.contains(field.getName())) {
continue;
}
nameSet.add(field.getName());
set.add(field);
}
nameSet.add(field.getName());
set.add(field);
}
}
c = c.getSuperclass();
c = c.getSuperclass();
}
return set;
}
return set;
}
);
);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
@@ -129,14 +144,19 @@ public class ReflectUtil {
* @return
*/
public static Set<Method> getMethods(Class<?> clazz) {
return kvProcess(methodsCache, clazz, c -> {
Method[] methods = c.getMethods();
Set<Method> methodSet = new HashSet<>();
if (ArrayUtil.notEmpty(methods)) {
methodSet = Stream.of(methods).collect(Collectors.toSet());
}
return methodSet;
});
try {
return kvProcess(methodsCache, clazz, c -> {
Method[] methods = c.getMethods();
Set<Method> methodSet = new HashSet<>();
if (ArrayUtil.notEmpty(methods)) {
methodSet = Stream.of(methods).collect(Collectors.toSet());
}
return methodSet;
});
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
@@ -145,14 +165,19 @@ public class ReflectUtil {
* @return
*/
public static Set<Method> getDeclaredMethods(Class<?> clazz) {
return kvProcess(declaredMethodsCache, clazz, c -> {
Method[] methods = c.getDeclaredMethods();
Set<Method> methodSet = new HashSet<>();
if (ArrayUtil.notEmpty(methods)) {
methodSet = Stream.of(methods).collect(Collectors.toSet());
}
return methodSet;
});
try {
return kvProcess(declaredMethodsCache, clazz, c -> {
Method[] methods = c.getDeclaredMethods();
Set<Method> methodSet = new HashSet<>();
if (ArrayUtil.notEmpty(methods)) {
methodSet = Stream.of(methods).collect(Collectors.toSet());
}
return methodSet;
});
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
@@ -161,14 +186,19 @@ public class ReflectUtil {
* @return
*/
public static Set<Class<?>> getExceptionTypes(Method method) {
return kvProcess(methodExceptionTypesCache, method, c -> {
Class<?>[] classes = method.getExceptionTypes();
Set<Class<?>> classSet = new HashSet<>();
if (ArrayUtil.notEmpty(classes)) {
classSet = Stream.of(classes).collect(Collectors.toSet());
}
return classSet;
});
try {
return kvProcess(methodExceptionTypesCache, method, c -> {
Class<?>[] classes = method.getExceptionTypes();
Set<Class<?>> classSet = new HashSet<>();
if (ArrayUtil.notEmpty(classes)) {
classSet = Stream.of(classes).collect(Collectors.toSet());
}
return classSet;
});
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
@@ -180,7 +210,7 @@ public class ReflectUtil {
* @param <V>
* @return
*/
private static <K,V> V kvProcess(Cache<K,V> cache, K k, Function<K,V>fn) {
private static <K,V> V kvProcess(Cache<K,V> cache, K k, Function<K,V>fn) throws Exception {
return LockUtil.doubleCheckProcess(
() -> !cache.containsKey(k),
k,
@@ -216,12 +246,17 @@ public class ReflectUtil {
* @return
*/
public static Method getGetMethod(Field field) {
return kvProcess(getMethodCache, field, f -> {
String getMethodName = getGetMethodName(field);
return getMethods(field.getDeclaringClass()).stream()
.filter(method -> method.getName().equals(getMethodName) && method.getParameters().length == 0)
.findFirst().get();
});
try {
return kvProcess(getMethodCache, field, f -> {
String getMethodName = getGetMethodName(field);
return getMethods(field.getDeclaringClass()).stream()
.filter(method -> method.getName().equals(getMethodName) && method.getParameters().length == 0)
.findFirst().get();
});
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
@@ -246,30 +281,35 @@ public class ReflectUtil {
* @return
*/
public static Method getSetMethod(Field field) {
return kvProcess(setMethodCache, field, f -> {
String setMethodName = getSetMethodName(field);
Optional<Method> methodOptional = getMethods(field.getDeclaringClass()).stream()
.filter(method -> method.getName().equals(setMethodName) && method.getParameters().length == 1 && method.getParameterTypes()[0] == field.getType())
.findFirst();
if (methodOptional.isPresent()) {
return methodOptional.get();
}
int level = TypeMatchLevel.NOT.getDistanceMax();
Method method = null;
for (Method m : getMethods(field.getDeclaringClass())) {
if (m.getName().equals(setMethodName) && m.getParameters().length == 1) {
int curLevel = TypeUtil.typeMatch(m.getParameterTypes()[0], field.getType()).getTypeDistance();
if (curLevel < level) {
level = curLevel;
method = m;
try {
return kvProcess(setMethodCache, field, f -> {
String setMethodName = getSetMethodName(field);
Optional<Method> methodOptional = getMethods(field.getDeclaringClass()).stream()
.filter(method -> method.getName().equals(setMethodName) && method.getParameters().length == 1 && method.getParameterTypes()[0] == field.getType())
.findFirst();
if (methodOptional.isPresent()) {
return methodOptional.get();
}
int level = TypeMatchLevel.NOT.getDistanceMax();
Method method = null;
for (Method m : getMethods(field.getDeclaringClass())) {
if (m.getName().equals(setMethodName) && m.getParameters().length == 1) {
int curLevel = TypeUtil.typeMatch(m.getParameterTypes()[0], field.getType()).getTypeDistance();
if (curLevel < level) {
level = curLevel;
method = m;
}
}
}
}
if (level < TypeMatchLevel.NOT.getDistanceMin() && method != null) {
return method;
}
return null;
});
if (level < TypeMatchLevel.NOT.getDistanceMin() && method != null) {
return method;
}
return null;
});
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
@@ -53,7 +53,11 @@ public class SystemUtil {
SystemUtil.addShutdownHook(() -> {
synchronized (context) {
if (null != destroy) {
destroy.execute();
try {
destroy.execute();
} catch (Exception e) {
e.printStackTrace();
}
}
context.stop();
context.notify();
@@ -21,6 +21,7 @@
*/
package fun.asgc.neutrino.core.util;
import fun.asgc.neutrino.core.aop.interceptor.ExceptionHandler;
import lombok.Data;
import org.checkerframework.checker.units.qual.A;
import org.junit.Test;
@@ -53,11 +54,15 @@ public class LockUtilTest {
*/
@Test
public void test2() {
for (int i = 0; i < 10; i++) {
for (int i = 0; i < 10; i++) {
ThreadUtil.run(() -> {
LockUtil.doubleCheckProcess(() -> a == null,
LockUtilTest.class,
() -> a = new A());
try {
LockUtil.doubleCheckProcess(() -> a == null,
LockUtilTest.class,
() -> a = new A());
} catch (Exception e) {
e.printStackTrace();
}
});
}
SystemUtil.waitProcessDestroy().sync();
@@ -43,13 +43,17 @@ public class ClientChannelHandler extends SimpleChannelInboundHandler<ProxyMessa
public ClientChannelHandler() {
LockUtil.doubleCheckProcess(() -> null == dispatcher,
ClientChannelHandler.class,
() -> {
dispatcher = new DefaultDispatcher<>("消息调度器",
BeanManager.getBeanListBySuperClass(ProxyMessageHandler.class),
proxyMessage -> ProxyDataTypeEnum.of((int)proxyMessage.getType()) == null ? null : ProxyDataTypeEnum.of((int)proxyMessage.getType()).getName());
});
try {
LockUtil.doubleCheckProcess(() -> null == dispatcher,
ClientChannelHandler.class,
() -> {
dispatcher = new DefaultDispatcher<>("消息调度器",
BeanManager.getBeanListBySuperClass(ProxyMessageHandler.class),
proxyMessage -> ProxyDataTypeEnum.of((int)proxyMessage.getType()) == null ? null : ProxyDataTypeEnum.of((int)proxyMessage.getType()).getName());
});
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
@@ -40,13 +40,17 @@ public class ServerChannelHandler extends SimpleChannelInboundHandler<ProxyMessa
private static volatile Dispatcher<ChannelHandlerContext, ProxyMessage> dispatcher;
public ServerChannelHandler() {
LockUtil.doubleCheckProcess(() -> null == dispatcher,
ServerChannelHandler.class,
() -> {
dispatcher = new DefaultDispatcher<>("消息调度器",
BeanManager.getBeanListBySuperClass(ProxyMessageHandler.class),
proxyMessage -> ProxyDataTypeEnum.of((int)proxyMessage.getType()) == null ? null : ProxyDataTypeEnum.of((int)proxyMessage.getType()).getName());
});
try {
LockUtil.doubleCheckProcess(() -> null == dispatcher,
ServerChannelHandler.class,
() -> {
dispatcher = new DefaultDispatcher<>("消息调度器",
BeanManager.getBeanListBySuperClass(ProxyMessageHandler.class),
proxyMessage -> ProxyDataTypeEnum.of((int)proxyMessage.getType()) == null ? null : ProxyDataTypeEnum.of((int)proxyMessage.getType()).getName());
});
} catch (Exception e) {
e.printStackTrace();
}
}
@Override