一个基于Java的责任链框架,支持核心模块独立使用和Spring Boot集成。
atlas-chain/
├── atlas-chain-core/ # 核心模块,无Spring依赖,可独立使用
├── atlas-chain-spring-boot-starter/ # Spring Boot集成模块
├── examples/ # 使用示例
│ ├── core-example/ # core模块使用示例
│ └── spring-example/ # spring模块使用示例
└── pom.xml # 父项目POM
核心模块不依赖Spring框架,可以在任何Java 8+环境中独立使用。
- HandlerContext<P, R> - 责任链上下文,用于在处理者之间传递数据
- BaseHandler<P, R> - 抽象处理者类,所有具体处理者需要继承此类
- ChainRegistry<P, R> - 链注册器,负责注册和管理处理者
- ChainExecutor<P, R> - 链执行器,负责执行责任链
Spring Boot集成模块提供了自动配置和注解驱动功能。
- @ChainHandler - 注解,用于标记处理者类
- ChainHandlerAutoConfiguration - 自动配置类
- ChainHandlerProperties - 配置属性类
- ChainHandlerRegistrar - 处理者注册器
对于纯Java项目使用core模块:
<dependency>
<groupId>io.github.nemoob</groupId>
<artifactId>atlas-chain-core</artifactId>
<version>0.1.0</version>
</dependency>对于Spring Boot项目使用starter模块:
<dependency>
<groupId>io.github.nemoob</groupId>
<artifactId>atlas-chain-spring-boot-starter</artifactId>
<version>0.1.0</version>
</dependency>// 创建注册器
ChainRegistry<UserRequest, UserResponse> registry = new ChainRegistry<>();
// 创建处理者
AuthenticationHandler authHandler = new AuthenticationHandler();
AuthorizationHandler authzHandler = new AuthorizationHandler();
BusinessLogicHandler businessHandler = new BusinessLogicHandler();
// 注册处理者到指定链路
String chainId = "user-process-chain";
registry.registerHandler(chainId, authHandler);
registry.registerHandler(chainId, authzHandler);
registry.registerHandler(chainId, businessHandler);
// 创建执行器
ChainExecutor<UserRequest, UserResponse> executor = new ChainExecutor<>(registry);
// 创建上下文
UserRequest request = new UserRequest("testUser", "testPassword");
HandlerContext<UserRequest, UserResponse> context = new HandlerContext<>(request, null);
// 执行责任链
UserResponse response = executor.execute(chainId, context);
// 关闭执行器
executor.shutdown();- 在处理者类上添加@ChainHandler和@Component注解:
@Component // 必须添加,让Spring管理此Bean
@ChainHandler(value = "user-process", order = 1)
public class UserValidateHandler extends BaseHandler<UserRequest, UserResponse> {
@Override
protected boolean doHandle(HandlerContext<UserRequest, UserResponse> context) {
// 处理逻辑
return true;
}
}- 在服务类中注入ChainExecutor并使用:
@Service
public class UserService {
@Autowired
private ChainExecutor<UserRequest, UserResponse> chainExecutor;
public UserResponse processUser(Long userId) {
UserRequest request = new UserRequest(userId, "testUser");
HandlerContext<UserRequest, UserResponse> context = new HandlerContext<>(request, null);
return chainExecutor.execute("user-process", context);
}
}在Spring Boot项目中,可以通过以下属性配置线程池:
chain:
handler:
core-pool-size: 5
max-pool-size: 10
keep-alive-time: 60
queue-capacity: 100Atlas-Chain 支持灵活的线程池配置,既可以使用默认配置,也可以自定义线程池。
零配置开箱即用!框架会自动创建 ChainExecutor Bean:
// 自动配置 - 使用默认线程池
@Bean("chainExecutor")
@ConditionalOnMissingBean(name = "chainExecutor")
public ChainExecutor<Object, Object> chainExecutor(ChainRegistry<Object, Object> chainRegistry) {
return new ChainExecutor<>(chainRegistry); // 内部创建默认线程池
}默认线程池配置:
- 核心线程数: 5
- 最大线程数: 10
- 空闲时间: 60秒
- 队列容量: 100
- 线程名称:
atlas-chain-{id} - 拒绝策略: CallerRunsPolicy
使用方式:
@Service
public class UserService {
@Autowired
private ChainExecutor<Object, Object> chainExecutor; // 直接注入即可
public Object processUser(Object request) {
HandlerContext<Object, Object> context = new HandlerContext<>(request);
return chainExecutor.execute("userChain", context);
}
}如果需要自定义线程池,直接创建自己的 ChainExecutor Bean:
@Configuration
public class CustomChainConfig {
@Bean("chainExecutor")
@Primary // 覆盖默认配置
public ChainExecutor<Object, Object> customChainExecutor(ChainRegistry<Object, Object> chainRegistry) {
// 创建自定义线程池
ExecutorService customPool = new ThreadPoolExecutor(
10, 20, 60L, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(200),
r -> {
Thread t = new Thread(r);
t.setName("custom-chain-" + t.getId());
return t;
}
);
return new ChainExecutor<>(chainRegistry, customPool);
}
}方式三:为不同责任链配置专用线程池
@Configuration
public class MultiChainConfig {
// 用户处理专用线程池
@Bean("userChainExecutor")
public ChainExecutor<UserRequest, UserResponse> userChainExecutor(
ChainRegistry<UserRequest, UserResponse> registry) {
ExecutorService userPool = new ThreadPoolExecutor(
5, 10, 60L, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(50),
r -> new Thread(r, "user-chain-" + System.currentTimeMillis())
);
return new ChainExecutor<>(registry, userPool);
}
// 订单处理专用线程池
@Bean("orderChainExecutor")
public ChainExecutor<OrderRequest, OrderResponse> orderChainExecutor(
ChainRegistry<OrderRequest, OrderResponse> registry) {
ExecutorService orderPool = new ThreadPoolExecutor(
8, 15, 60L, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(100),
r -> new Thread(r, "order-chain-" + System.currentTimeMillis())
);
return new ChainExecutor<>(registry, orderPool);
}
@Bean("highPriorityChainExecutor")
public ChainExecutor<HighPriorityRequest, HighPriorityResponse> highPriorityChainExecutor(
ChainRegistry<HighPriorityRequest, HighPriorityResponse> registry,
@Qualifier("highPriorityExecutorService") ExecutorService executorService) {
// 使用现有的高优先级线程池
return new ChainExecutor<>(registry, executorService);
}
}然后在服务中使用@Qualifier注入指定的执行器:
@Service
public class UserService {
@Autowired
@Qualifier("userChainExecutor")
private ChainExecutor<UserRequest, UserResponse> userChainExecutor;
@Autowired
@Qualifier("orderChainExecutor")
private ChainExecutor<OrderRequest, OrderResponse> orderChainExecutor;
public UserResponse processUser(UserRequest request) {
HandlerContext<UserRequest, UserResponse> context =
new HandlerContext<>(request, null);
return userChainExecutor.execute("user-chain", context);
}
public OrderResponse processOrder(OrderRequest request) {
HandlerContext<OrderRequest, OrderResponse> context =
new HandlerContext<>(request, null);
return orderChainExecutor.execute("order-chain", context);
}
}🎯 选择合适的配置方式:
- 默认配置 - 适用于大多数场景,无需任何配置
- 方式一 - 需要调整线程池参数,但使用单一执行器
- 方式二 - 需要完全控制 ChainExecutor 的创建
- 方式三 - 不同业务链需要不同的线程池策略
⚡ 性能优化建议:
// 高性能配置示例
@Bean("handlerExecutorService")
public ExecutorService handlerExecutorService() {
return new ThreadPoolExecutor(
Runtime.getRuntime().availableProcessors(), // 核心线程数 = CPU核数
Runtime.getRuntime().availableProcessors() * 2, // 最大线程数 = CPU核数 * 2
60L, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(1000), // 适当的队列大小
new ThreadFactoryBuilder()
.setNameFormat("atlas-chain-%d")
.setDaemon(false)
.build(),
new ThreadPoolExecutor.CallerRunsPolicy() // 优雅降级
);
}🔧 Bean冲突解决:
当项目中存在多个 ExecutorService Bean 时:
@Configuration
public class ConflictResolver {
@Bean("handlerExecutorService") // 框架会优先使用这个
public ExecutorService handlerExecutorService() {
return new ThreadPoolExecutor(/* 配置 */);
}
@Bean("otherExecutorService") // 其他业务使用
public ExecutorService otherExecutorService() {
return Executors.newCachedThreadPool();
}
}- 基于注解的链路注册机制 - 通过@ChainHandler注解和ID执行责任链
- 节点跳过机制 - boolean doHandle返回false时终止后续节点执行
- 异步执行机制 - 支持异步执行,可配置自定义线程池
- 泛型约束 - HandlerContext使用泛型约束,支持参数和响应类型分离
- 类型安全属性 - 节点间通信属性支持类型约束
- 模块化设计 - core包(独立使用) + spring-boot-starter包
- 兼容性 - JDK 1.8 + Spring Boot 2.2 + Spring 5.2
- 代码简化 - 全包使用Lombok,添加完整注释
# 构建整个项目
mvn clean install
# 运行核心模块示例
mvn exec:java -pl examples/core-example
# 运行Spring Boot示例
mvn spring-boot:run -pl examples/spring-example
# 运行测试
mvn testStar History