This commit is contained in:
redkale
2024-06-12 19:09:18 +08:00
parent 9acb7a5290
commit a47f73cf10
7 changed files with 340 additions and 292 deletions

366
pom.xml
View File

@@ -1,183 +1,183 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.redkale</groupId>
<artifactId>redkale</artifactId>
<packaging>jar</packaging>
<name>RedkaleProject</name>
<url>https://redkale.org</url>
<description>redkale -- java framework</description>
<version>2.8.0-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<junit.version>5.9.0</junit.version>
<maven-jar-plugin.version>3.4.0</maven-jar-plugin.version>
<maven-compiler-plugin.version>3.13.0</maven-compiler-plugin.version>
<maven-surefire-plugin.version>3.2.5</maven-surefire-plugin.version>
<maven-failsafe-plugin.version>3.2.5</maven-failsafe-plugin.version>
<spotless-maven-plugin.version>2.43.0</spotless-maven-plugin.version>
<palantir-java-format.version>2.46.0</palantir-java-format.version>
</properties>
<licenses>
<license>
<name>Apache 2</name>
<url>https://www.apache.org/licenses/</url>
<distribution>repo</distribution>
<comments>Apache License</comments>
</license>
</licenses>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<repositories>
<repository>
<id>central</id>
<name>Central Repository</name>
<url>https://repo.maven.apache.org/maven2</url>
</repository>
<repository>
<id>sonatype-nexus-snapshots</id>
<name>Sonatype Nexus Snapshots</name>
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
</repository>
</repositories>
<developers>
<developer>
<id>Redkale</id>
<name>redkale</name>
<email>redkale@qq.com</email>
<url>https://redkale.org</url>
<roles>
<role>Project Manager</role>
<role>Architect</role>
</roles>
<organization>redkale</organization>
<organizationUrl>https://redkale.org</organizationUrl>
<properties>
<dept>No</dept>
</properties>
<timezone>8</timezone>
</developer>
</developers>
<scm>
<url>https://github.com/redkale/redkale</url>
<connection>scm:git:git@github.com/redkale/redkale.git</connection>
<developerConnection>scm:git:git@github.com:redkale/redkale.git</developerConnection>
</scm>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<encoding>UTF-8</encoding>
<compilerArgs>
<arg>-parameters</arg>
</compilerArgs>
</configuration>
</plugin>
<!-- 需要注释掉, 否则会生成native-image配置信息
<plugin>
<groupId>org.redkale.maven.plugins</groupId>
<artifactId>redkale-maven-plugin</artifactId>
<version>1.1.0</version>
<executions>
<execution>
<id>redkale-compile</id>
<phase>process-classes</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
</executions>
</plugin>
-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>${maven-jar-plugin.version}</version>
<configuration>
<archive>
<addMavenDescriptor>false</addMavenDescriptor>
<manifest>
<mainClass>org.redkale.boot.Application</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<forkMode>once</forkMode>
<argLine>-Dfile.encoding=UTF-8</argLine>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<version>${maven-failsafe-plugin.version}</version>
</plugin>
<plugin>
<groupId>com.diffplug.spotless</groupId>
<artifactId>spotless-maven-plugin</artifactId>
<version>${spotless-maven-plugin.version}</version>
<configuration>
<lineEndings>UNIX</lineEndings>
<formats>
<format>
<includes>
<include>src/**/java/**/*.java</include>
</includes>
<trimTrailingWhitespace/>
<endWithNewline/>
<indent>
<spaces>true</spaces>
<spacesPerTab>4</spacesPerTab>
</indent>
</format>
</formats>
<java>
<palantirJavaFormat>
<version>${palantir-java-format.version}</version>
<style>PALANTIR</style>
<formatJavadoc>true</formatJavadoc>
</palantirJavaFormat>
</java>
</configuration>
<executions>
<execution>
<goals>
<goal>check</goal>
</goals>
<phase>compile</phase>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.redkale</groupId>
<artifactId>redkale</artifactId>
<packaging>jar</packaging>
<name>RedkaleProject</name>
<url>https://redkale.org</url>
<description>redkale -- java framework</description>
<version>2.8.0-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<junit.version>5.9.0</junit.version>
<maven-jar-plugin.version>3.4.0</maven-jar-plugin.version>
<maven-compiler-plugin.version>3.13.0</maven-compiler-plugin.version>
<maven-surefire-plugin.version>3.2.5</maven-surefire-plugin.version>
<maven-failsafe-plugin.version>3.2.5</maven-failsafe-plugin.version>
<spotless-maven-plugin.version>2.43.0</spotless-maven-plugin.version>
<palantir-java-format.version>2.46.0</palantir-java-format.version>
</properties>
<licenses>
<license>
<name>Apache 2</name>
<url>https://www.apache.org/licenses/</url>
<distribution>repo</distribution>
<comments>Apache License</comments>
</license>
</licenses>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<repositories>
<repository>
<id>central</id>
<name>Central Repository</name>
<url>https://repo.maven.apache.org/maven2</url>
</repository>
<repository>
<id>sonatype-nexus-snapshots</id>
<name>Sonatype Nexus Snapshots</name>
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
</repository>
</repositories>
<developers>
<developer>
<id>Redkale</id>
<name>redkale</name>
<email>redkale@qq.com</email>
<url>https://redkale.org</url>
<roles>
<role>Project Manager</role>
<role>Architect</role>
</roles>
<organization>redkale</organization>
<organizationUrl>https://redkale.org</organizationUrl>
<properties>
<dept>No</dept>
</properties>
<timezone>8</timezone>
</developer>
</developers>
<scm>
<url>https://github.com/redkale/redkale</url>
<connection>scm:git:git@github.com/redkale/redkale.git</connection>
<developerConnection>scm:git:git@github.com:redkale/redkale.git</developerConnection>
</scm>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<encoding>UTF-8</encoding>
<compilerArgs>
<arg>-parameters</arg>
</compilerArgs>
</configuration>
</plugin>
<!-- 需要注释掉, 否则会生成native-image配置信息
<plugin>
<groupId>org.redkale.maven.plugins</groupId>
<artifactId>redkale-maven-plugin</artifactId>
<version>1.1.0</version>
<executions>
<execution>
<id>redkale-compile</id>
<phase>process-classes</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
</executions>
</plugin>
-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>${maven-jar-plugin.version}</version>
<configuration>
<archive>
<addMavenDescriptor>false</addMavenDescriptor>
<manifest>
<mainClass>org.redkale.boot.Application</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<forkMode>once</forkMode>
<argLine>-Dfile.encoding=UTF-8</argLine>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<version>${maven-failsafe-plugin.version}</version>
</plugin>
<plugin>
<groupId>com.diffplug.spotless</groupId>
<artifactId>spotless-maven-plugin</artifactId>
<version>${spotless-maven-plugin.version}</version>
<configuration>
<lineEndings>UNIX</lineEndings>
<formats>
<format>
<includes>
<include>src/**/java/**/*.java</include>
</includes>
<trimTrailingWhitespace/>
<endWithNewline/>
<indent>
<spaces>true</spaces>
<spacesPerTab>4</spacesPerTab>
</indent>
</format>
</formats>
<java>
<palantirJavaFormat>
<version>${palantir-java-format.version}</version>
<style>PALANTIR</style>
<formatJavadoc>true</formatJavadoc>
</palantirJavaFormat>
</java>
</configuration>
<executions>
<execution>
<goals>
<goal>check</goal>
</goals>
<phase>compile</phase>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@@ -43,6 +43,7 @@ import org.redkale.net.http.*;
import org.redkale.net.sncp.*;
import org.redkale.props.spi.PropertiesModule;
import org.redkale.scheduled.spi.ScheduledModuleEngine;
import org.redkale.service.RetCodes;
import org.redkale.service.Service;
import org.redkale.source.*;
import org.redkale.source.spi.SourceModuleEngine;
@@ -369,6 +370,8 @@ public final class Application {
this.onEnvironmentLoaded();
// init起始回调
this.onAppPreInit();
// 加载错误码
this.initRetCodes();
// 设置WorkExecutor
this.initWorkExecutor();
// 回调Listener
@@ -710,6 +713,22 @@ public final class Application {
}
}
/** 加载错误码 */
private void initRetCodes() throws IOException {
ClassFilter<RetCodes> filter = new ClassFilter(this.getClassLoader(), RetCodes.class);
loadClassByFilters(filter);
StringBuilder sb = new StringBuilder();
filter.getFilterEntrys().forEach(en -> {
if (en.getType() != RetCodes.class) {
int c = RetCodes.load(en.getType());
sb.append("Load RetCodes (type=").append(en.getType().getName() + ") " + c + " records\r\n");
}
});
if (sb.length() > 0) {
logger.log(Level.INFO, sb.toString().trim());
}
}
/** 设置WorkExecutor */
private void initWorkExecutor() {
int bufferCapacity = 32 * 1024;

View File

@@ -63,6 +63,10 @@ public final class ClassFilter<T> {
private final ClassLoader classLoader;
public ClassFilter(RedkaleClassLoader classLoader, Class superClass) {
this(classLoader, null, superClass, (Class[]) null, null);
}
public ClassFilter(RedkaleClassLoader classLoader, Class<? extends Annotation> annotationClass, Class superClass) {
this(classLoader, annotationClass, superClass, (Class[]) null, null);
}

View File

@@ -8,7 +8,7 @@ import java.text.MessageFormat;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 错误码加载器
@@ -20,41 +20,33 @@ import java.util.concurrent.locks.ReentrantLock;
*/
public abstract class RetCodes {
private static final ReentrantLock loadLock = new ReentrantLock();
private static Map<String, Map<Integer, String>> rets = new LinkedHashMap<>();
private static Map<Integer, String> defret = new LinkedHashMap<>();
protected RetCodes() {
throw new IllegalStateException();
}
public static void load(Class codeClass) {
load(RetLabel.RetLoader.loadMap(codeClass));
public static int load(Class codeClass) {
return load(RetInnerCache.loadMap(codeClass));
}
public static void load(Map<String, Map<Integer, String>> map) {
public static int load(Map<String, Map<Integer, String>> map) {
if (map.isEmpty()) {
return;
return 0;
}
loadLock.lock();
AtomicInteger counter = new AtomicInteger();
RetInnerCache.loadLock.lock();
try {
Map<String, Map<Integer, String>> newMap = new LinkedHashMap<>();
rets.forEach((k, v) -> newMap.put(k, new LinkedHashMap<>(v)));
RetInnerCache.allRets.forEach((k, v) -> newMap.put(k, new LinkedHashMap<>(v)));
map.forEach((k, v) -> {
Map<Integer, String> m = newMap.get(k);
if (m != null) {
m.putAll(v);
} else {
newMap.put(k, v);
}
newMap.computeIfAbsent(k, n -> new LinkedHashMap<>()).putAll(v);
counter.addAndGet(v.size());
});
rets = newMap;
defret = rets.get("");
RetInnerCache.allRets = newMap;
RetInnerCache.defRets = newMap.get("");
} finally {
loadLock.unlock();
RetInnerCache.loadLock.unlock();
}
return counter.get();
}
public static RetResult retResult(int retcode) {
@@ -135,7 +127,7 @@ public abstract class RetCodes {
if (retcode == 0) {
return "Success";
}
return defret.getOrDefault(retcode, "Error");
return RetInnerCache.defRets.getOrDefault(retcode, "Error");
}
public static String retInfo(String locale, int retcode) {
@@ -145,7 +137,7 @@ public abstract class RetCodes {
if (retcode == 0) {
return "Success";
}
Map<Integer, String> map = rets.get(locale);
Map<Integer, String> map = RetInnerCache.allRets.get(locale);
if (map == null) {
return "Error";
}

View File

@@ -0,0 +1,13 @@
/*
*/
package org.redkale.service;
import java.util.function.BiFunction;
/**
*
* @author zhangjx
*/
public interface RetInfoTransfer extends BiFunction<Integer, String, String> {}

View File

@@ -0,0 +1,105 @@
/*
*/
package org.redkale.service;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;
import java.util.ServiceLoader;
import java.util.concurrent.locks.ReentrantLock;
import static org.redkale.boot.Application.SYSNAME_APP_CONF_DIR;
import static org.redkale.boot.Application.SYSNAME_APP_HOME;
import org.redkale.util.RedkaleClassLoader;
/**
*
* @author zhangjx
*/
class RetInnerCache {
static final ReentrantLock loadLock = new ReentrantLock();
static Map<String, Map<Integer, String>> allRets = new LinkedHashMap<>();
static Map<Integer, String> defRets = new LinkedHashMap<>();
private RetInnerCache() {}
static Map<String, Map<Integer, String>> loadMap(Class clazz) {
final Map<String, Map<Integer, String>> allRetMap = new LinkedHashMap<>();
ServiceLoader<RetInfoTransfer> loader = ServiceLoader.load(RetInfoTransfer.class);
RedkaleClassLoader.putServiceLoader(RetInfoTransfer.class);
Iterator<RetInfoTransfer> it = loader.iterator();
RetInfoTransfer func = it.hasNext() ? it.next() : null;
if (func != null) {
RedkaleClassLoader.putReflectionPublicConstructors(
func.getClass(), func.getClass().getName());
}
RedkaleClassLoader.putReflectionPublicFields(clazz.getName());
for (Field field : clazz.getFields()) {
if (!Modifier.isStatic(field.getModifiers())) {
continue;
}
if (field.getType() != int.class) {
continue;
}
RetLabel[] infos = field.getAnnotationsByType(RetLabel.class);
if (infos == null || infos.length == 0) {
continue;
}
int value;
try {
value = field.getInt(null);
} catch (Exception ex) {
ex.printStackTrace();
continue;
}
for (RetLabel info : infos) {
allRetMap
.computeIfAbsent(info.locale(), k -> new LinkedHashMap<>())
.put(value, func == null ? info.value() : func.apply(value, info.value()));
}
}
try {
File homePath = new File(System.getProperty(SYSNAME_APP_HOME, ""), "conf");
File propPath = new File(System.getProperty(SYSNAME_APP_CONF_DIR, homePath.getPath()));
if (propPath.isDirectory() && propPath.canRead()) {
final String prefix = clazz.getSimpleName().toLowerCase();
for (File propFile : propPath.listFiles(
f -> f.getName().startsWith(prefix) && f.getName().endsWith(".properties"))) {
if (propFile.isFile() && propFile.canRead()) {
String locale =
propFile.getName().substring(prefix.length()).replaceAll("\\.\\d+", "");
locale = locale.substring(0, locale.indexOf(".properties"));
Map<Integer, String> defRetMap = allRetMap.get(locale);
if (defRetMap != null) {
InputStreamReader in =
new InputStreamReader(new FileInputStream(propFile), StandardCharsets.UTF_8);
Properties prop = new Properties();
prop.load(in);
in.close();
prop.forEach((k, v) -> {
int retcode = Integer.parseInt(k.toString());
if (defRetMap.containsKey(retcode)) {
defRetMap.put(retcode, v.toString());
}
});
}
}
}
}
} catch (Exception e) {
// do nothing
}
return allRetMap;
}
}

View File

@@ -5,17 +5,9 @@
*/
package org.redkale.service;
import java.io.*;
import java.lang.annotation.*;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.reflect.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.function.BiFunction;
import static org.redkale.boot.Application.SYSNAME_APP_CONF_DIR;
import static org.redkale.boot.Application.SYSNAME_APP_HOME;
import org.redkale.util.RedkaleClassLoader;
/**
* 用于定义错误码的注解 <br>
@@ -46,81 +38,4 @@ public @interface RetLabel {
RetLabel[] value();
}
public static interface RetInfoTransfer extends BiFunction<Integer, String, String> {}
public abstract static class RetLoader {
private RetLoader() {
throw new IllegalStateException();
}
public static Map<String, Map<Integer, String>> loadMap(Class clazz) {
final Map<String, Map<Integer, String>> rets = new LinkedHashMap<>();
ServiceLoader<RetInfoTransfer> loader = ServiceLoader.load(RetInfoTransfer.class);
RedkaleClassLoader.putServiceLoader(RetInfoTransfer.class);
Iterator<RetInfoTransfer> it = loader.iterator();
RetInfoTransfer func = it.hasNext() ? it.next() : null;
if (func != null) {
RedkaleClassLoader.putReflectionPublicConstructors(
func.getClass(), func.getClass().getName());
}
RedkaleClassLoader.putReflectionPublicFields(clazz.getName());
for (Field field : clazz.getFields()) {
if (!Modifier.isStatic(field.getModifiers())) {
continue;
}
if (field.getType() != int.class) {
continue;
}
RetLabel[] infos = field.getAnnotationsByType(RetLabel.class);
if (infos == null || infos.length == 0) {
continue;
}
int value;
try {
value = field.getInt(null);
} catch (Exception ex) {
ex.printStackTrace();
continue;
}
for (RetLabel info : infos) {
rets.computeIfAbsent(info.locale(), k -> new LinkedHashMap<>())
.put(value, func == null ? info.value() : func.apply(value, info.value()));
}
}
try {
File homePath = new File(System.getProperty(SYSNAME_APP_HOME, ""), "conf");
File propPath = new File(System.getProperty(SYSNAME_APP_CONF_DIR, homePath.getPath()));
if (propPath.isDirectory() && propPath.canRead()) {
final String prefix = clazz.getSimpleName().toLowerCase();
for (File propFile : propPath.listFiles(
f -> f.getName().startsWith(prefix) && f.getName().endsWith(".properties"))) {
if (propFile.isFile() && propFile.canRead()) {
String locale = propFile.getName()
.substring(prefix.length())
.replaceAll("\\.\\d+", "");
locale = locale.substring(0, locale.indexOf(".properties"));
Map<Integer, String> defrets = rets.get(locale);
if (defrets != null) {
InputStreamReader in =
new InputStreamReader(new FileInputStream(propFile), StandardCharsets.UTF_8);
Properties prop = new Properties();
prop.load(in);
in.close();
prop.forEach((k, v) -> {
int retcode = Integer.parseInt(k.toString());
if (defrets.containsKey(retcode)) {
defrets.put(retcode, v.toString());
}
});
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return rets;
}
}
}