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

View File

@@ -43,6 +43,7 @@ import org.redkale.net.http.*;
import org.redkale.net.sncp.*; import org.redkale.net.sncp.*;
import org.redkale.props.spi.PropertiesModule; import org.redkale.props.spi.PropertiesModule;
import org.redkale.scheduled.spi.ScheduledModuleEngine; import org.redkale.scheduled.spi.ScheduledModuleEngine;
import org.redkale.service.RetCodes;
import org.redkale.service.Service; import org.redkale.service.Service;
import org.redkale.source.*; import org.redkale.source.*;
import org.redkale.source.spi.SourceModuleEngine; import org.redkale.source.spi.SourceModuleEngine;
@@ -369,6 +370,8 @@ public final class Application {
this.onEnvironmentLoaded(); this.onEnvironmentLoaded();
// init起始回调 // init起始回调
this.onAppPreInit(); this.onAppPreInit();
// 加载错误码
this.initRetCodes();
// 设置WorkExecutor // 设置WorkExecutor
this.initWorkExecutor(); this.initWorkExecutor();
// 回调Listener // 回调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 */ /** 设置WorkExecutor */
private void initWorkExecutor() { private void initWorkExecutor() {
int bufferCapacity = 32 * 1024; int bufferCapacity = 32 * 1024;

View File

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

View File

@@ -8,7 +8,7 @@ import java.text.MessageFormat;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.Map; import java.util.Map;
import java.util.concurrent.CompletableFuture; 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 { 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() { protected RetCodes() {
throw new IllegalStateException(); throw new IllegalStateException();
} }
public static void load(Class codeClass) { public static int load(Class codeClass) {
load(RetLabel.RetLoader.loadMap(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()) { if (map.isEmpty()) {
return; return 0;
} }
loadLock.lock(); AtomicInteger counter = new AtomicInteger();
RetInnerCache.loadLock.lock();
try { try {
Map<String, Map<Integer, String>> newMap = new LinkedHashMap<>(); 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.forEach((k, v) -> {
Map<Integer, String> m = newMap.get(k); newMap.computeIfAbsent(k, n -> new LinkedHashMap<>()).putAll(v);
if (m != null) { counter.addAndGet(v.size());
m.putAll(v);
} else {
newMap.put(k, v);
}
}); });
rets = newMap; RetInnerCache.allRets = newMap;
defret = rets.get(""); RetInnerCache.defRets = newMap.get("");
} finally { } finally {
loadLock.unlock(); RetInnerCache.loadLock.unlock();
} }
return counter.get();
} }
public static RetResult retResult(int retcode) { public static RetResult retResult(int retcode) {
@@ -135,7 +127,7 @@ public abstract class RetCodes {
if (retcode == 0) { if (retcode == 0) {
return "Success"; return "Success";
} }
return defret.getOrDefault(retcode, "Error"); return RetInnerCache.defRets.getOrDefault(retcode, "Error");
} }
public static String retInfo(String locale, int retcode) { public static String retInfo(String locale, int retcode) {
@@ -145,7 +137,7 @@ public abstract class RetCodes {
if (retcode == 0) { if (retcode == 0) {
return "Success"; return "Success";
} }
Map<Integer, String> map = rets.get(locale); Map<Integer, String> map = RetInnerCache.allRets.get(locale);
if (map == null) { if (map == null) {
return "Error"; 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; package org.redkale.service;
import java.io.*;
import java.lang.annotation.*; import java.lang.annotation.*;
import static java.lang.annotation.ElementType.*; import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME; 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> * 用于定义错误码的注解 <br>
@@ -46,81 +38,4 @@ public @interface RetLabel {
RetLabel[] value(); 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;
}
}
} }