code stringlengths 1 1.05M | repo_name stringlengths 6 83 | path stringlengths 3 242 | language stringclasses 222 values | license stringclasses 20 values | size int64 1 1.05M |
|---|---|---|---|---|---|
extends Button
# Called when the node enters the scene tree for the first time.
func _on_pressed() -> void:
$"../../modelimg".texture=load("res://model2.png")
| 2303_806435pww/turing_machine_moved | model_2.gd | GDScript | mit | 163 |
extends Button
# Called when the node enters the scene tree for the first time.
func _ready() -> void:
pass # Replace with function body.
# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta: float) -> void:
pass
func _on_pressed() -> void:
$"../../modelimg".texture=load("res://model3.png")
| 2303_806435pww/turing_machine_moved | model_3.gd | GDScript | mit | 344 |
extends Button
# Called when the node enters the scene tree for the first time.
func _ready() -> void:
pass # Replace with function body.
# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta: float) -> void:
pass
func _on_pressed() -> void:
$"../../modelimg".texture=load("res://model4.png")
| 2303_806435pww/turing_machine_moved | model_4.gd | GDScript | mit | 345 |
extends Button
# Called when the node enters the scene tree for the first time.
func _ready() -> void:
pass # Replace with function body.
# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta: float) -> void:
pass
func _on_pressed() -> void:
$"../../modelimg".texture=load("res://model5.png")
| 2303_806435pww/turing_machine_moved | model_5.gd | GDScript | mit | 344 |
extends RichTextLabel
# Called when the node enters the scene tree for the first time.
func _ready() -> void:
pass # Replace with function body.
# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta: float) -> void:
pass
func _on_meta_clicked(meta):
if meta == "http://godotengine.org":
OS.shell_open(meta)
#func _on_meta_clicked(meta: Variant) -> void:
#if meta == "http://godotengine.org"
#OS.shell_open(meta)
| 2303_806435pww/turing_machine_moved | rich_text_label.gd | GDScript | mit | 470 |
extends RichTextLabel
# Called when the node enters the scene tree for the first time.
func _ready() -> void:
pass # Replace with function body.
# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta: float) -> void:
pass
func _on_meta_clicked(meta):
OS.shell_open(meta)
| 2303_806435pww/turing_machine_moved | rich_text_label_2.gd | GDScript | mit | 322 |
extends Window
# Called when the node enters the scene tree for the first time.
func _ready() -> void:
pass # Replace with function body.
# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta: float) -> void:
pass
func _on_close_requested() -> void:
$".".visible=false
| 2303_806435pww/turing_machine_moved | window.gd | GDScript | mit | 320 |
import ttkbootstrap as tk
#from ttkbootstrap import style
from ttkbootstrap.constants import *
from tkinter.filedialog import *
#style = style.Style(theme="superhero")
#root = style.master
root = tk.Window()
root.title("python编辑器")
text = tk.Text(root)
text.config(font=('Arial', 12), wrap='word')
text.pack(side="bottom")
def save():
filenewpath = asksaveasfilename(defaultextension='.py')
if filenewpath != "":
f = open(filenewpath,"w")
f.write(text.get("1.0","end"))
f.close()
def run():
exec(text.get("1.0","end"))
def delet():
text.delete('1.0', 'end')
def file():
path = askopenfilename()
if path != "":
f = open(path,"r")
a = f.read()
f.close()
text.insert("end",a)
botton1 = tk.Button(root,text="保存",bootstyle=(INFO,OUTLINE),command=save)
botton1.pack(side="left")
button2 = tk.Button(root,text="运行",bootstyle=(INFO,OUTLINE),command=run)
button2.pack(side="left")
button3 = tk.Button(root,text="清空",bootstyle=(INFO,OUTLINE),command=delet)
button3.pack(side="left")
button4 = tk.Button(root,text="打开",bootstyle=(INFO,OUTLINE),command=file)
button4.pack(side="left")
root.mainloop()
| 2401_82606246/PythonEditor | python编辑器.py | Python | unknown | 1,145 |
/// 应用级别的常量配置统一放在这里,便于集中管理与调优。
class AppConfig {
AppConfig._();
/// 体验用的占位 Token。正式环境请替换为你自己的 GitCode 访问令牌,
/// 并优先考虑使用安全存储或远程配置方案,避免泄露敏感信息。
static const demoToken = 'kAqxjRKWb1iN9Pidiay8fsd5';
}
| 2401_82544706/gitcode_pocket_tool | lib/core/app_config.dart | Dart | unknown | 361 |
import 'package:flutter/material.dart';
/// 应用主题配置,定义全局颜色、字体和样式
class AppTheme {
// 主色调
static const Color primaryColor = Color(0xFF4361ee);
static const Color primaryLight = Color(0xFF7209b7);
static const Color primaryDark = Color(0xFF3a0ca3);
// 辅助色
static const Color secondaryColor = Color(0xFFf72585);
static const Color secondaryLight = Color(0xFFb5179e);
// 中性色
static const Color backgroundColor = Color(0xFFf8f9fa);
static const Color cardColor = Color(0xFFffffff);
static const Color surfaceColor = Color(0xFFf5f5f5);
static const Color textPrimary = Color(0xFF212529);
static const Color textSecondary = Color(0xFF6c757d);
static const Color borderColor = Color(0xFFdee2e6);
// 状态色
static const Color successColor = Color(0xFF2ecc71);
static const Color errorColor = Color(0xFFe74c3c);
static const Color warningColor = Color(0xFFf39c12);
static const Color infoColor = Color(0xFF3498db);
// 阴影
static const BoxShadow cardShadow = BoxShadow(
color: Color(0x10000000),
blurRadius: 8,
spreadRadius: 2,
offset: Offset(0, 2),
);
// 创建主题数据
static ThemeData get lightTheme {
return ThemeData(
// 主颜色配置
primaryColor: primaryColor,
primarySwatch: createMaterialColor(primaryColor),
// 亮度和主题模式
brightness: Brightness.light,
// 文本主题
textTheme: const TextTheme(
headlineLarge: TextStyle(
fontSize: 32, fontWeight: FontWeight.bold, color: textPrimary),
headlineMedium: TextStyle(
fontSize: 28, fontWeight: FontWeight.bold, color: textPrimary),
headlineSmall: TextStyle(
fontSize: 24, fontWeight: FontWeight.bold, color: textPrimary),
titleLarge: TextStyle(
fontSize: 20, fontWeight: FontWeight.bold, color: textPrimary),
bodyLarge: TextStyle(fontSize: 16, color: textPrimary),
bodyMedium: TextStyle(fontSize: 14, color: textSecondary),
bodySmall: TextStyle(fontSize: 12, color: textSecondary),
),
// 卡片主题
cardTheme: CardTheme(
color: cardColor,
elevation: 0,
shadowColor: Colors.transparent,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
side: const BorderSide(color: borderColor),
),
),
// 按钮主题
elevatedButtonTheme: ElevatedButtonThemeData(
style: ElevatedButton.styleFrom(
backgroundColor: primaryColor,
foregroundColor: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
),
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
textStyle: const TextStyle(fontWeight: FontWeight.bold),
),
),
// 输入框主题
inputDecorationTheme: InputDecorationTheme(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
borderSide: const BorderSide(color: borderColor),
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
borderSide: const BorderSide(color: borderColor),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
borderSide: const BorderSide(color: primaryColor, width: 2),
),
errorBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
borderSide: const BorderSide(color: errorColor),
),
filled: true,
fillColor: surfaceColor,
contentPadding:
const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
),
// 应用栏主题
appBarTheme: const AppBarTheme(
backgroundColor: primaryColor,
foregroundColor: Colors.white,
elevation: 4,
centerTitle: true,
titleTextStyle: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
// 底部导航栏主题
bottomNavigationBarTheme: BottomNavigationBarThemeData(
backgroundColor: Colors.white,
selectedItemColor: primaryColor,
unselectedItemColor: textSecondary,
selectedLabelStyle: const TextStyle(fontWeight: FontWeight.bold),
elevation: 8,
),
// 图标主题
iconTheme: const IconThemeData(color: textPrimary),
primaryIconTheme: const IconThemeData(color: Colors.white),
// 分隔线主题
dividerTheme: const DividerThemeData(
color: borderColor,
thickness: 1,
indent: 16,
endIndent: 16,
),
// 其他
scaffoldBackgroundColor: backgroundColor,
colorScheme: ColorScheme.fromSwatch().copyWith(
primary: primaryColor,
secondary: secondaryColor,
background: backgroundColor,
surface: surfaceColor,
error: errorColor,
onPrimary: Colors.white,
onSecondary: Colors.white,
onBackground: textPrimary,
onSurface: textPrimary,
onError: Colors.white,
),
);
}
// 将Color转换为MaterialColor(用于primarySwatch)
static MaterialColor createMaterialColor(Color color) {
// 简化实现,只提供必要的颜色映射
return MaterialColor(color.value, {
500: color,
100: color,
200: color,
300: color,
400: color,
600: color,
700: color,
800: color,
900: color,
50: color,
});
}
}
| 2401_82544706/gitcode_pocket_tool | lib/core/app_theme.dart | Dart | unknown | 5,621 |
import 'package:dio/dio.dart';
/// 本文件集中封装了调用 GitCode API 所需的 HTTP 客户端、数据模型
/// 以及通用的解析逻辑,便于在 UI 层直接复用,避免重复拼装请求。
/// GitCode API 的轻量封装,负责统一请求参数、超时和错误处理。
class GitCodeApiClient {
GitCodeApiClient({Dio? dio})
: _dio = dio ??
Dio(
BaseOptions(
// 默认基准端点指向 GitCode v5 API,所有请求在此路径下拼接。
baseUrl: 'https://api.gitcode.com/api/v5',
// 连接和读取阶段都限定为 5 秒,能在弱网场景下快速失败,提示用户重试。
connectTimeout: const Duration(seconds: 5),
receiveTimeout: const Duration(seconds: 5),
),
) {
// 初始化时设置日志拦截器
_setupLogging();
}
// 添加日志拦截器,帮助调试
void _setupLogging() {
_dio.interceptors.add(LogInterceptor(
responseBody: true,
requestBody: true,
responseHeader: true,
requestHeader: true,
));
}
final Dio _dio;
/// 通过登录名获取用户详情,可选地携带 token 进行授权访问。
Future<GitCodeUser> fetchUser(
String username, {
String? personalToken,
bool allowSearchFallback = true,
}) async {
// 统一去除空白,避免因为用户误输入空格导致请求 404。
final trimmed = username.trim();
if (trimmed.isEmpty) {
throw const GitCodeApiException('用户名不能为空');
}
try {
final response = await _dio.get<Map<String, dynamic>>(
'/users/${Uri.encodeComponent(trimmed)}',
options: Options(
headers: _buildHeaders(personalToken),
responseType: ResponseType.json,
// 允许 4xx 结果进入响应分支,以便输出更友好的提示。
validateStatus: (status) => status != null && status < 500,
),
);
final statusCode = response.statusCode ?? 0;
switch (statusCode) {
case 200:
final data = response.data;
if (data == null) {
throw const GitCodeApiException('接口返回为空,请稍后重试');
}
return GitCodeUser.fromJson(data);
case 401:
throw const GitCodeApiException('未授权,请检查 access token 或权限');
case 404:
if (allowSearchFallback &&
personalToken != null &&
personalToken.isNotEmpty) {
// 优先通过搜索接口尝试“昵称 -> 登录名”的映射,提升用户输入容错度。
final fallbackLogin = await _searchLoginByKeyword(
trimmed,
personalToken: personalToken,
);
if (fallbackLogin != null && fallbackLogin != trimmed) {
// 一旦拿到真实 login,关闭二次 fallback,以免造成递归。
return fetchUser(
fallbackLogin,
personalToken: personalToken,
allowSearchFallback: false,
);
}
}
throw GitCodeApiException(
'未找到用户 $trimmed,若输入的是展示昵称,请改用登录名或携带 token 搜索。',
);
default:
throw GitCodeApiException(
'查询失败 (HTTP $statusCode),请稍后重试',
);
}
} on DioException catch (error) {
if (error.type == DioExceptionType.connectionTimeout ||
error.type == DioExceptionType.receiveTimeout) {
throw const GitCodeApiException('请求超时,请检查网络后重试');
}
if (error.type == DioExceptionType.badResponse) {
// 服务器已响应,但状态码 >= 400,由于 validateStatus 只放行 < 500,此处意味着 4xx。
throw GitCodeApiException(
'请求异常:HTTP ${error.response?.statusCode ?? '-'}',
);
}
// 其它类型(取消、未知等)直接透传人类可读信息。
throw GitCodeApiException(error.message ?? '未知网络错误');
}
}
/// 构造通用请求头,必要时附加 Bearer token。
Map<String, String> _buildHeaders(String? personalToken) {
return {
if (personalToken != null && personalToken.isNotEmpty)
'Authorization': 'Bearer $personalToken',
};
}
/// 当用户输入昵称时,通过搜索接口尝试获取真实 login。
Future<String?> _searchLoginByKeyword(
String keyword, {
required String personalToken,
}) async {
try {
final response = await _dio.get<List<dynamic>>(
'/search/users',
queryParameters: {
'q': keyword,
'per_page': 1,
'access_token': personalToken,
},
options: Options(
headers: _buildHeaders(personalToken),
responseType: ResponseType.json,
validateStatus: (status) => status != null && status < 500,
),
);
if ((response.statusCode ?? 0) == 200) {
final list = response.data;
if (list == null || list.isEmpty) {
return null;
}
final first = list.first;
if (first is Map<String, dynamic>) {
// 只取第一个候选项的 login,命中率通常最高。
return first['login'] as String?;
}
} else if ((response.statusCode ?? 0) == 401) {
// Token 不合法时立即抛出,提示用户调整配置。
throw const GitCodeApiException('搜索需要有效的 access token');
}
} on DioException {
return null;
}
return null;
}
/// 调用 `/search/users`,返回符合关键字的用户简要信息。
Future<List<GitCodeSearchUser>> searchUsers({
required String keyword,
required String personalToken,
int perPage = 10,
int page = 1,
}) async {
// 用户搜索同样需要去除前后空格,避免无效查询。
final trimmed = keyword.trim();
if (trimmed.isEmpty) {
throw const GitCodeApiException('请输入搜索关键字');
}
try {
// 先获取动态类型响应
final response = await _dio.get<dynamic>(
'/search/users',
queryParameters: <String, dynamic>{
'q': trimmed,
'access_token': personalToken,
// clamp 可以阻止业务层传入不合法的分页参数,避免后端报错。
'per_page': perPage.clamp(1, 50),
'page': page.clamp(1, 100),
},
options: Options(
headers: _buildHeaders(personalToken),
responseType: ResponseType.json,
validateStatus: (status) => status != null && status < 500,
),
);
final statusCode = response.statusCode ?? 0;
if (statusCode == 401) {
throw const GitCodeApiException('Token 无效或权限不足,无法搜索用户');
}
if (statusCode != 200) {
throw GitCodeApiException('搜索用户失败 (HTTP $statusCode)');
}
// 处理空响应
if (response.data == null) {
return [];
}
// 处理不同的响应类型
final data = response.data;
List<dynamic> usersList = [];
if (data is List<dynamic>) {
// 正常情况:直接返回列表
usersList = data;
} else if (data is Map<String, dynamic>) {
// 尝试多种可能的字段名
final possibleFields = ['items', 'users', 'data', 'results'];
for (var field in possibleFields) {
if (data.containsKey(field)) {
final fieldData = data[field];
if (fieldData is List<dynamic>) {
usersList = fieldData;
break;
}
}
}
// 如果没有找到有效的列表字段,返回空列表
if (usersList.isEmpty) {
return [];
}
}
// 安全地转换数据
try {
return usersList
.where((item) => item is Map<String, dynamic>)
.map((item) =>
GitCodeSearchUser.fromJson(item as Map<String, dynamic>))
.toList();
} catch (e) {
// 数据解析错误,返回空列表
return [];
}
} on DioException catch (error) {
// 更详细的错误处理
if (error.response != null) {
throw GitCodeApiException(
'搜索用户失败 (HTTP ${error.response?.statusCode}): ${error.response?.data}');
} else if (error.type == DioExceptionType.connectionTimeout ||
error.type == DioExceptionType.receiveTimeout) {
throw const GitCodeApiException('网络超时,请检查网络连接后重试');
} else {
throw GitCodeApiException('搜索用户失败: ${error.message}');
}
} catch (e) {
// 捕获所有其他异常
throw GitCodeApiException('搜索用户时发生未知错误: ${e.toString()}');
}
}
/// 调用 `/search/repositories`,支持语言、排序等可选参数。
Future<List<GitCodeRepository>> searchRepositories({
required String keyword,
required String personalToken,
String? language,
String? sort,
String? order,
int perPage = 10,
int page = 1,
}) async {
final trimmed = keyword.trim();
if (trimmed.isEmpty) {
throw const GitCodeApiException('请输入搜索关键字');
}
final queryParameters = <String, dynamic>{
'q': trimmed,
'access_token': personalToken,
'per_page': perPage.clamp(1, 50),
'page': page.clamp(1, 100),
// 以下三个参数均为可选过滤项,后端若为空会忽略。
if (language != null && language.isNotEmpty) 'language': language,
if (sort != null && sort.isNotEmpty) 'sort': sort,
if (order != null && order.isNotEmpty) 'order': order,
};
try {
// 先获取动态类型响应
final response = await _dio.get<dynamic>(
'/search/repositories',
queryParameters: queryParameters,
options: Options(
headers: _buildHeaders(personalToken),
responseType: ResponseType.json,
validateStatus: (status) => status != null && status < 500,
),
);
final statusCode = response.statusCode ?? 0;
if (statusCode == 401) {
throw const GitCodeApiException('Token 无效或权限不足,无法搜索仓库');
}
if (statusCode != 200) {
throw GitCodeApiException('搜索仓库失败 (HTTP $statusCode)');
}
// 处理空响应
if (response.data == null) {
return [];
}
// 处理不同的响应类型
final data = response.data;
List<dynamic> repositoriesList = [];
if (data is List<dynamic>) {
// 正常情况:直接返回列表
repositoriesList = data;
} else if (data is Map<String, dynamic>) {
// 尝试多种可能的字段名
final possibleFields = [
'items',
'repositories',
'repos',
'data',
'results'
];
for (var field in possibleFields) {
if (data.containsKey(field)) {
final fieldData = data[field];
if (fieldData is List<dynamic>) {
repositoriesList = fieldData;
break;
}
}
}
// 如果没有找到有效的列表字段,返回空列表
if (repositoriesList.isEmpty) {
return [];
}
}
// 安全地转换数据
try {
return repositoriesList
.where((item) => item is Map<String, dynamic>)
.map((item) =>
GitCodeRepository.fromJson(item as Map<String, dynamic>))
.toList();
} catch (e) {
// 数据解析错误,返回空列表
return [];
}
} on DioException catch (error) {
// 更详细的错误处理
if (error.response != null) {
throw GitCodeApiException(
'搜索仓库失败 (HTTP ${error.response?.statusCode}): ${error.response?.data}');
} else if (error.type == DioExceptionType.connectionTimeout ||
error.type == DioExceptionType.receiveTimeout) {
throw const GitCodeApiException('网络超时,请检查网络连接后重试');
} else {
throw GitCodeApiException('搜索仓库失败: ${error.message}');
}
} catch (e) {
// 捕获所有其他异常
throw GitCodeApiException('搜索仓库时发生未知错误: ${e.toString()}');
}
}
/// 获取用户的组织列表
Future<List<GitCodeOrganization>> getOrganizations({
required String username,
required String personalToken,
int perPage = 10,
int page = 1,
}) async {
final trimmed = username.trim();
if (trimmed.isEmpty) {
throw const GitCodeApiException('用户名不能为空');
}
try {
// 先获取动态类型响应
final response = await _dio.get<dynamic>(
'/users/${Uri.encodeComponent(trimmed)}/orgs',
queryParameters: <String, dynamic>{
'access_token': personalToken,
'per_page': perPage.clamp(1, 50),
'page': page.clamp(1, 100),
},
options: Options(
headers: _buildHeaders(personalToken),
responseType: ResponseType.json,
validateStatus: (status) => status != null && status < 500,
),
);
final statusCode = response.statusCode ?? 0;
if (statusCode == 401) {
throw const GitCodeApiException('Token 无效或权限不足,无法获取组织');
}
if (statusCode != 200) {
// 针对400错误提供更友好的提示
if (statusCode == 400) {
throw GitCodeApiException('获取组织列表失败 (参数错误),请检查请求参数是否正确');
}
throw GitCodeApiException('获取组织列表失败 (HTTP $statusCode)');
}
// 处理空响应
if (response.data == null) {
return [];
}
// 处理不同的响应类型
final data = response.data;
List<dynamic> organizationsList = [];
if (data is List<dynamic>) {
// 正常情况:直接返回列表
organizationsList = data;
} else if (data is Map<String, dynamic>) {
// 尝试多种可能的字段名
final possibleFields = [
'items',
'organizations',
'orgs',
'data',
'results'
];
for (var field in possibleFields) {
if (data.containsKey(field)) {
final fieldData = data[field];
if (fieldData is List<dynamic>) {
organizationsList = fieldData;
break;
}
}
}
// 如果没有找到有效的列表字段,返回空列表
if (organizationsList.isEmpty) {
return [];
}
}
// 安全地转换数据
try {
return organizationsList
.where((item) => item is Map<String, dynamic>)
.map((item) =>
GitCodeOrganization.fromJson(item as Map<String, dynamic>))
.toList();
} catch (e) {
// 数据解析错误,返回空列表
return [];
}
} on DioException catch (error) {
// 更详细的错误处理
if (error.response != null) {
throw GitCodeApiException(
'获取组织列表失败 (HTTP ${error.response?.statusCode}): ${error.response?.data}');
} else if (error.type == DioExceptionType.connectionTimeout ||
error.type == DioExceptionType.receiveTimeout) {
throw const GitCodeApiException('网络超时,请检查网络连接后重试');
} else {
throw GitCodeApiException('获取组织列表失败: ${error.message}');
}
} catch (e) {
// 捕获所有其他异常
throw GitCodeApiException('获取组织列表时发生未知错误: ${e.toString()}');
}
}
/// 获取用户的仓库列表
Future<List<GitCodeRepository>> getUserRepositories({
required String username,
required String personalToken,
String? sort,
String? direction,
int perPage = 10,
int page = 1,
}) async {
final trimmed = username.trim();
if (trimmed.isEmpty) {
throw const GitCodeApiException('用户名不能为空');
}
final queryParameters = <String, dynamic>{
'access_token': personalToken,
'per_page': perPage.clamp(1, 50),
'page': page.clamp(1, 100),
if (sort != null && sort.isNotEmpty) 'sort': sort,
if (direction != null && direction.isNotEmpty) 'direction': direction,
};
try {
// 先获取动态类型响应
final response = await _dio.get<dynamic>(
'/users/${Uri.encodeComponent(trimmed)}/repos',
queryParameters: queryParameters,
options: Options(
headers: _buildHeaders(personalToken),
responseType: ResponseType.json,
validateStatus: (status) => status != null && status < 500,
),
);
final statusCode = response.statusCode ?? 0;
if (statusCode == 401) {
throw const GitCodeApiException('Token 无效或权限不足,无法获取仓库');
}
if (statusCode != 200) {
throw GitCodeApiException('获取仓库列表失败 (HTTP $statusCode)');
}
// 处理空响应
if (response.data == null) {
return [];
}
// 处理不同的响应类型
final data = response.data;
List<dynamic> repositoriesList = [];
if (data is List<dynamic>) {
// 正常情况:直接返回列表
repositoriesList = data;
} else if (data is Map<String, dynamic>) {
// 尝试多种可能的字段名
final possibleFields = [
'items',
'repositories',
'repos',
'data',
'results'
];
for (var field in possibleFields) {
if (data.containsKey(field)) {
final fieldData = data[field];
if (fieldData is List<dynamic>) {
repositoriesList = fieldData;
break;
}
}
}
// 如果没有找到有效的列表字段,尝试将整个Map作为单个仓库处理
if (repositoriesList.isEmpty) {
// 检查是否包含仓库特征字段
if (data.containsKey('name') ||
data.containsKey('full_name') ||
data.containsKey('fullName')) {
repositoriesList = [data];
} else {
// 无法识别的响应格式,返回空列表而不是抛出异常
return [];
}
}
}
// 安全地转换数据
try {
return repositoriesList
.where((item) => item is Map<String, dynamic>)
.map((item) =>
GitCodeRepository.fromJson(item as Map<String, dynamic>))
.toList();
} catch (e) {
// 数据解析错误,返回空列表
return [];
}
} on DioException catch (error) {
// 更详细的错误处理
if (error.response != null) {
throw GitCodeApiException(
'获取仓库列表失败 (HTTP ${error.response?.statusCode}): ${error.response?.data}');
} else if (error.type == DioExceptionType.connectionTimeout ||
error.type == DioExceptionType.receiveTimeout) {
throw const GitCodeApiException('网络超时,请检查网络连接后重试');
} else {
throw GitCodeApiException('获取仓库列表失败: ${error.message}');
}
} catch (e) {
// 捕获所有其他异常
throw GitCodeApiException('获取仓库列表时发生未知错误: ${e.toString()}');
}
}
}
class GitCodeUser {
GitCodeUser({
required this.login,
required this.avatarUrl,
this.name,
this.bio,
this.htmlUrl,
this.publicRepos,
this.followers,
this.following,
this.createdAt,
});
factory GitCodeUser.fromJson(Map<String, dynamic> json) {
return GitCodeUser(
login: json['login'] as String? ?? '',
avatarUrl: json['avatar_url'] as String? ?? '',
name: json['name'] as String?,
bio: json['bio'] as String?,
htmlUrl: json['html_url'] as String?,
publicRepos: _safeInt(json['public_repos']),
followers: _safeInt(json['followers']),
following: _safeInt(json['following']),
createdAt: json['created_at'] as String?,
);
}
/// GitCode 唯一登录名,可用于后续接口请求。
final String login;
/// 头像的完整 URL,用于展示用户头像。
final String avatarUrl;
/// 用户在个人资料中填写的展示昵称,可能为空。
final String? name;
/// 个人简介或签名信息。
final String? bio;
/// 用户主页链接,通常指向 GitCode Web。
final String? htmlUrl;
/// 用户公开仓库的数量。
final int? publicRepos;
/// 粉丝(followers)数量。
final int? followers;
/// 关注(following)数量。
final int? following;
/// 账号创建时间,ISO 时间字符串。
final String? createdAt;
}
/// 将接口返回的动态数值转换为 int,兼容字符串与数字。
int? _safeInt(dynamic value) {
if (value == null) {
return null;
}
if (value is int) {
return value;
}
if (value is String) {
// 有些字段可能以字符串形式返回整型,此处尝试解析。
return int.tryParse(value);
}
return null;
}
class GitCodeApiException implements Exception {
const GitCodeApiException(this.message);
final String message;
@override
String toString() => 'GitCodeApiException: $message';
}
class GitCodeSearchUser {
GitCodeSearchUser({
required this.login,
required this.avatarUrl,
this.name,
this.htmlUrl,
this.createdAt,
});
factory GitCodeSearchUser.fromJson(Map<String, dynamic> json) {
return GitCodeSearchUser(
login: json['login'] as String? ?? '',
avatarUrl: json['avatar_url'] as String? ?? '',
name: json['name'] as String?,
htmlUrl: json['html_url'] as String?,
createdAt: json['created_at'] as String?,
);
}
/// 搜索结果中的登录名。
final String login;
/// 搜索结果中的头像地址。
final String avatarUrl;
/// 搜索结果中的展示名称。
final String? name;
/// 用户主页链接。
final String? htmlUrl;
/// 用户创建时间。
final String? createdAt;
}
class GitCodeOrganization {
GitCodeOrganization({
required this.login,
required this.avatarUrl,
this.name,
this.description,
this.htmlUrl,
this.membersCount,
});
factory GitCodeOrganization.fromJson(Map<String, dynamic> json) {
return GitCodeOrganization(
login: json['login'] as String? ?? '',
avatarUrl: json['avatar_url'] as String? ?? '',
name: json['name'] as String?,
description: json['description'] as String?,
htmlUrl: json['html_url'] as String?,
membersCount: _safeInt(json['members_count']),
);
}
/// 组织的唯一登录名
final String login;
/// 组织头像的URL
final String avatarUrl;
/// 组织显示名称
final String? name;
/// 组织描述
final String? description;
/// 组织主页URL
final String? htmlUrl;
/// 成员数量
final int? membersCount;
}
class GitCodeRepository {
GitCodeRepository({
required this.fullName,
required this.webUrl,
this.description,
this.language,
this.updatedAt,
this.stars,
this.forks,
this.watchers,
this.ownerLogin,
this.isPrivate,
});
factory GitCodeRepository.fromJson(Map<String, dynamic> json) {
final owner = json['owner'];
return GitCodeRepository(
fullName: json['full_name'] as String? ?? '',
webUrl: json['web_url'] as String? ?? '',
description: json['description'] as String?,
language: json['language'] as String?,
updatedAt: json['updated_at'] as String?,
stars:
_safeInt(json['stargazers_count']) ?? _safeInt(json['stars_count']),
forks: _safeInt(json['forks_count']),
watchers: _safeInt(json['watchers_count']),
ownerLogin: owner is Map<String, dynamic>
// 兼容不同字段命名(name/path),以防接口字段发生差异。
? owner['name'] as String? ?? owner['path'] as String?
: null,
isPrivate: _safeBool(json['private']),
);
}
/// 仓库的全名,形如 "owner/repo"。
final String fullName;
/// 仓库在 GitCode 上的访问 URL。
final String webUrl;
/// 仓库描述,可能为空。
final String? description;
/// 主要编程语言。
final String? language;
/// 最近一次更新时间。
final String? updatedAt;
/// Stargazers 数量,优先读取 `stargazers_count`。
final int? stars;
/// Fork 数量。
final int? forks;
/// Watchers 数量。
final int? watchers;
/// 仓库所有者的登录名或路径。
final String? ownerLogin;
/// 是否私有仓库。
final bool? isPrivate;
}
/// GitCode 接口可能返回 0/1、'true'/'false',统一转成 bool。
bool? _safeBool(dynamic value) {
if (value == null) {
return null;
}
if (value is bool) {
return value;
}
if (value is int) {
// GitCode 某些布尔字段会用 0/1 表示。
return value != 0;
}
if (value is String) {
if (value == '1' || value.toLowerCase() == 'true') {
return true;
}
if (value == '0' || value.toLowerCase() == 'false') {
return false;
}
}
return null;
}
| 2401_82544706/gitcode_pocket_tool | lib/core/gitcode_api.dart | Dart | unknown | 25,784 |
import 'package:flutter/material.dart';
import 'core/app_config.dart';
import 'core/gitcode_api.dart';
import 'pages/main_navigation.dart';
import 'core/app_theme.dart';
/// 区分搜索模式:用户 或 仓库。
enum QueryMode { user, repository }
void main() {
runApp(const GitCodePocketToolApp());
}
class GitCodePocketToolApp extends StatelessWidget {
const GitCodePocketToolApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'GitCode 口袋工具',
theme: AppTheme.lightTheme,
home: const MainNavigation(),
);
}
}
class GitCodePocketToolPage extends StatefulWidget {
const GitCodePocketToolPage({super.key});
@override
State<GitCodePocketToolPage> createState() => _GitCodePocketToolPageState();
}
class _GitCodePocketToolPageState extends State<GitCodePocketToolPage> {
_GitCodePocketToolPageState() {
_tokenController.text = AppConfig.demoToken;
}
/// 输入框控制器、表单 key、API 客户端等 UI 层状态。
final _keywordController = TextEditingController();
final _tokenController = TextEditingController();
final _formKey = GlobalKey<FormState>();
final _client = GitCodeApiClient();
QueryMode _mode = QueryMode.user;
List<GitCodeSearchUser> _userResults = const [];
List<GitCodeRepository> _repoResults = const [];
String? _errorMessage;
bool _isLoading = false;
bool _obscureToken = true;
@override
void dispose() {
_keywordController.dispose();
_tokenController.dispose();
super.dispose();
}
/// 统一的搜索入口:根据模式调用不同接口,并处理通用的 Loading / Error 逻辑。
Future<void> _performSearch() async {
if (_isLoading) return;
if (!_formKey.currentState!.validate()) return;
FocusScope.of(context).unfocus();
setState(() {
_isLoading = true;
_errorMessage = null;
_userResults = const [];
_repoResults = const [];
});
final token = _tokenController.text.trim();
try {
// 根据当前模式执行对应的 API 请求。
if (_mode == QueryMode.user) {
final users = await _client.searchUsers(
keyword: _keywordController.text,
personalToken: token,
perPage: 8,
);
setState(() {
_userResults = users;
});
} else {
final repos = await _client.searchRepositories(
keyword: _keywordController.text,
personalToken: token,
perPage: 8,
);
setState(() {
_repoResults = repos;
});
}
} on GitCodeApiException catch (error) {
setState(() {
_errorMessage = error.message;
});
} catch (error) {
setState(() {
_errorMessage = '未知错误:$error';
});
} finally {
if (mounted) {
setState(() {
_isLoading = false;
});
}
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('GitCode 口袋工具'),
),
body: SafeArea(
child: SingleChildScrollView(
padding: const EdgeInsets.all(20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_buildIntro(),
const SizedBox(height: 20),
_buildFormCard(),
const SizedBox(height: 20),
_buildResultSection(),
],
),
),
),
);
}
Widget _buildIntro() {
return const Text(
'输入关键字 + access token,立即查询 GitCode 用户或仓库(搜索接口需授权)。',
style: TextStyle(fontSize: 15, fontWeight: FontWeight.w500),
);
}
Widget _buildFormCard() {
return Card(
elevation: 0,
clipBehavior: Clip.antiAlias,
child: Padding(
padding: const EdgeInsets.all(20),
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_buildModeSwitcher(),
const SizedBox(height: 12),
TextFormField(
controller: _keywordController,
textInputAction: TextInputAction.search,
decoration: const InputDecoration(
labelText: '搜索关键字',
hintText: '例如:iflytek / spark',
prefixIcon: Icon(Icons.search),
),
validator: (value) {
if (value == null || value.trim().isEmpty) {
return '请输入关键字';
}
return null;
},
onFieldSubmitted: (_) => _performSearch(),
),
const SizedBox(height: 12),
TextFormField(
controller: _tokenController,
decoration: InputDecoration(
labelText: 'Access Token',
hintText: 'GitCode 个人设置 > Access Token',
prefixIcon: const Icon(Icons.vpn_key_outlined),
suffixIcon: IconButton(
icon: Icon(
_obscureToken
? Icons.visibility_off_outlined
: Icons.visibility_outlined,
),
onPressed: () {
setState(() {
_obscureToken = !_obscureToken;
});
},
),
),
obscureText: _obscureToken,
validator: (value) {
if (value == null || value.trim().isEmpty) {
return '搜索接口需提供 access token';
}
return null;
},
),
const SizedBox(height: 16),
FilledButton.icon(
onPressed: _isLoading ? null : _performSearch,
icon: _isLoading
? const SizedBox(
width: 18,
height: 18,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Icon(Icons.play_arrow_rounded),
label: Text(_isLoading ? '查询中...' : '查询'),
),
],
),
),
),
);
}
Widget _buildResultSection() {
if (_isLoading) {
return const Center(child: CircularProgressIndicator());
}
if (_errorMessage != null) {
// 统一信息展示组件,既可以显示错误也能展示提示。
return _InfoBanner(
icon: Icons.error_outline,
background: Colors.red.withValues(alpha: 0.08),
textColor: Colors.red.shade700,
message: _errorMessage!,
);
}
if (_mode == QueryMode.user) {
return _buildUserResults();
}
return _buildRepositoryResults();
}
Widget _buildModeSwitcher() {
return SegmentedButton<QueryMode>(
segments: const [
ButtonSegment(
value: QueryMode.user,
icon: Icon(Icons.person_outline),
label: Text('用户'),
),
ButtonSegment(
value: QueryMode.repository,
icon: Icon(Icons.bookmark_outline),
label: Text('仓库'),
),
],
selected: <QueryMode>{_mode},
onSelectionChanged: (selection) {
final next = selection.first;
if (next != _mode) {
// 切换模式时及时清理旧结果,避免跨模式串数据。
setState(() {
_mode = next;
_errorMessage = null;
_userResults = const [];
_repoResults = const [];
});
}
},
);
}
Widget _buildUserResults() {
if (_userResults.isEmpty) {
return const _InfoBanner(
icon: Icons.info_outline,
background: Color(0xFFEFF4FF),
textColor: Color(0xFF1A237E),
message: '暂无数据,输入关键字并点击“查询”试试。',
);
}
return Column(
children: _userResults.map(_UserTile.new).toList(),
);
}
Widget _buildRepositoryResults() {
if (_repoResults.isEmpty) {
return const _InfoBanner(
icon: Icons.info_outline,
background: Color(0xFFEFF4FF),
textColor: Color(0xFF1A237E),
message: '还没有结果,输入关键字并点击查询即可获取仓库列表。',
);
}
return Column(
children: _repoResults.map(_RepoTile.new).toList(),
);
}
}
class _InfoBanner extends StatelessWidget {
const _InfoBanner({
required this.icon,
required this.background,
required this.textColor,
required this.message,
});
final IconData icon;
final Color background;
final Color textColor;
final String message;
@override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: background,
borderRadius: BorderRadius.circular(12),
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(icon, color: textColor),
const SizedBox(width: 12),
Expanded(
child: Text(
message,
style: Theme.of(context)
.textTheme
.bodyMedium
?.copyWith(color: textColor),
),
),
],
),
);
}
}
class _UserTile extends StatelessWidget {
const _UserTile(this.user);
final GitCodeSearchUser user;
@override
Widget build(BuildContext context) {
final title = user.name?.isNotEmpty == true ? user.name! : user.login;
final subtitleParts = <String>[
'@${user.login}',
if (user.createdAt != null) '注册 ${user.createdAt}',
];
return Card(
elevation: 0,
margin: const EdgeInsets.only(bottom: 12),
child: ListTile(
leading: CircleAvatar(
// GitCode 头像 URL 直接展示,失败时忽略错误防止闪退。
backgroundImage: NetworkImage(user.avatarUrl),
onBackgroundImageError: (_, __) {},
),
title: Text(title, style: const TextStyle(fontWeight: FontWeight.w600)),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
subtitleParts.join(' · '),
style: const TextStyle(fontSize: 12),
),
if (user.htmlUrl != null)
Text(
user.htmlUrl!,
style: const TextStyle(fontSize: 12, color: Colors.blue),
),
],
),
),
);
}
}
class _RepoTile extends StatelessWidget {
const _RepoTile(this.repo);
final GitCodeRepository repo;
@override
Widget build(BuildContext context) {
return Card(
elevation: 0,
margin: const EdgeInsets.only(bottom: 12),
child: ListTile(
leading: const Icon(Icons.folder_outlined),
title: Text(repo.fullName,
style: const TextStyle(fontWeight: FontWeight.w600)),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (repo.description?.isNotEmpty == true)
Padding(
padding: const EdgeInsets.only(bottom: 4),
child: Text(
repo.description!,
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
),
Wrap(
spacing: 8,
runSpacing: 4,
children: [
// 语言、Star、Fork 三种常见指标,Chip 形式展示。
if (repo.language != null)
_StatChip(label: '语言', valueLabel: repo.language),
_StatChip(label: 'Star', value: repo.stars),
_StatChip(label: 'Fork', value: repo.forks),
],
),
const SizedBox(height: 4),
Text(
'更新 ${repo.updatedAt ?? '-'}',
style: const TextStyle(fontSize: 12),
),
Text(
repo.webUrl,
style: const TextStyle(fontSize: 12, color: Colors.blue),
),
],
),
),
);
}
}
class _StatChip extends StatelessWidget {
const _StatChip({
required this.label,
this.value,
this.valueLabel,
});
final String label;
final int? value;
final String? valueLabel;
@override
Widget build(BuildContext context) {
final textTheme = Theme.of(context).textTheme;
final display = valueLabel ?? (value ?? 0).toString();
// 将指标抽象成独立 Chip,方便未来增加更多字段。
return Chip(
label: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
display,
style: textTheme.titleMedium,
),
Text(label, style: textTheme.bodySmall),
],
),
);
}
}
| 2401_82544706/gitcode_pocket_tool | lib/main.dart | Dart | unknown | 13,295 |
import 'package:flutter/material.dart';
import '../core/gitcode_api.dart';
import '../core/app_config.dart';
import '../core/app_theme.dart';
import 'dart:async';
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
final _keywordController = TextEditingController();
final _tokenController = TextEditingController();
final _formKey = GlobalKey<FormState>();
final _client = GitCodeApiClient();
QueryMode _mode = QueryMode.user;
List<GitCodeSearchUser> _userResults = const [];
List<GitCodeRepository> _repoResults = const [];
String? _errorMessage;
bool _isLoading = false;
bool _isLoadingMore = false;
int _currentPage = 1;
bool _hasMore = true;
@override
void initState() {
super.initState();
_tokenController.text = AppConfig.demoToken;
}
@override
void dispose() {
_keywordController.dispose();
_tokenController.dispose();
super.dispose();
}
Future<void> _performSearch() async {
if (_isLoading) return;
if (!_formKey.currentState!.validate()) return;
FocusScope.of(context).unfocus();
setState(() {
_isLoading = true;
_errorMessage = null;
_userResults = const [];
_repoResults = const [];
_currentPage = 1;
_hasMore = true;
});
final token = _tokenController.text.trim();
try {
if (_mode == QueryMode.user) {
final users = await _client.searchUsers(
keyword: _keywordController.text,
personalToken: token,
perPage: 8,
page: 1,
);
setState(() {
_userResults = users;
_hasMore = users.length == 8;
_currentPage = 2;
});
} else {
final repos = await _client.searchRepositories(
keyword: _keywordController.text,
personalToken: token,
perPage: 8,
page: 1,
);
setState(() {
_repoResults = repos;
_hasMore = repos.length == 8;
_currentPage = 2;
});
}
} on GitCodeApiException catch (error) {
setState(() {
_errorMessage = error.message;
});
} catch (error) {
setState(() {
_errorMessage = '未知错误:$error';
});
} finally {
if (mounted) {
setState(() {
_isLoading = false;
});
}
}
}
Future<void> _loadMore() async {
if (_isLoadingMore || !_hasMore || _keywordController.text.trim().isEmpty) {
return;
}
setState(() {
_isLoadingMore = true;
});
final token = _tokenController.text.trim();
try {
if (_mode == QueryMode.user) {
final moreUsers = await _client.searchUsers(
keyword: _keywordController.text,
personalToken: token,
perPage: 8,
page: _currentPage,
);
setState(() {
_userResults.addAll(moreUsers);
_hasMore = moreUsers.length == 8;
_currentPage++;
});
} else {
final moreRepos = await _client.searchRepositories(
keyword: _keywordController.text,
personalToken: token,
perPage: 8,
page: _currentPage,
);
setState(() {
_repoResults.addAll(moreRepos);
_hasMore = moreRepos.length == 8;
_currentPage++;
});
}
} on GitCodeApiException catch (error) {
setState(() {
_errorMessage = error.message;
});
} catch (error) {
setState(() {
_errorMessage = '未知错误:$error';
});
} finally {
if (mounted) {
setState(() {
_isLoadingMore = false;
});
}
}
}
Future<void> _refresh() async {
// 重置搜索状态
setState(() {
_userResults = const [];
_repoResults = const [];
_isLoading = false;
_isLoadingMore = false;
_errorMessage = null;
_keywordController.clear();
_currentPage = 1;
_hasMore = true;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('GitCode 口袋工具'),
elevation: 4,
),
body: RefreshIndicator(
onRefresh: _refresh,
child: SafeArea(
child: SingleChildScrollView(
padding: const EdgeInsets.all(20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_buildIntro(),
const SizedBox(height: 20),
_buildFormCard(),
const SizedBox(height: 20),
_buildResultSection(),
],
),
),
),
),
);
}
Widget _buildIntro() {
return const Text(
'输入关键字 + access token,立即查询 GitCode 用户或仓库(搜索接口需授权)。',
style: TextStyle(fontSize: 15, fontWeight: FontWeight.w500),
);
}
Widget _buildFormCard() {
return Card(
elevation: 0,
clipBehavior: Clip.antiAlias,
child: Padding(
padding: const EdgeInsets.all(20),
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_buildModeSwitcher(),
const SizedBox(height: 12),
TextFormField(
controller: _keywordController,
textInputAction: TextInputAction.search,
decoration: InputDecoration(
labelText: '搜索关键字',
hintText: '例如:iflytek / spark',
prefixIcon: const Icon(Icons.search),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(24),
),
filled: true,
fillColor: Colors.white,
contentPadding:
const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(24),
borderSide: const BorderSide(
color: AppTheme.primaryColor, width: 2),
),
),
validator: (value) {
if (value == null || value.trim().isEmpty) {
return '请输入关键字';
}
return null;
},
onFieldSubmitted: (_) => _performSearch(),
),
const SizedBox(height: 12),
TextFormField(
controller: _tokenController,
decoration: InputDecoration(
labelText: 'Access Token',
hintText: 'GitCode 个人设置 > Access Token',
prefixIcon: const Icon(Icons.vpn_key_outlined),
),
obscureText: true,
validator: (value) {
if (value == null || value.trim().isEmpty) {
return '搜索接口需提供 access token';
}
return null;
},
),
const SizedBox(height: 16),
FilledButton.icon(
onPressed: _isLoading ? null : _performSearch,
icon: _isLoading
? const SizedBox(
width: 18,
height: 18,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Icon(Icons.play_arrow_rounded),
label: Text(_isLoading ? '查询中...' : '查询'),
),
],
),
),
),
);
}
Widget _buildResultSection() {
if (_isLoading) {
return const Center(child: CircularProgressIndicator());
}
if (_errorMessage != null) {
return ListView(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
children: [
Center(
child: Padding(
padding: const EdgeInsets.all(32),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(Icons.error_outline,
size: 48, color: AppTheme.errorColor),
const SizedBox(height: 16),
Text(
_errorMessage!,
textAlign: TextAlign.center,
style: TextStyle(color: AppTheme.textSecondary),
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: _performSearch,
child: const Text('重试'),
),
],
),
),
),
],
);
}
if (_mode == QueryMode.user) {
return _buildUserResults();
}
return _buildRepositoryResults();
}
Widget _buildModeSwitcher() {
return SegmentedButton<QueryMode>(
segments: const [
ButtonSegment(
value: QueryMode.user,
icon: Icon(Icons.person_outline),
label: Text('用户'),
),
ButtonSegment(
value: QueryMode.repository,
icon: Icon(Icons.bookmark_outline),
label: Text('仓库'),
),
],
selected: <QueryMode>{_mode},
onSelectionChanged: (selection) {
final next = selection.first;
if (next != _mode) {
setState(() {
_mode = next;
_errorMessage = null;
_userResults = const [];
_repoResults = const [];
});
}
},
style: ButtonStyle(
backgroundColor: MaterialStateProperty.resolveWith<Color>((states) {
if (states.contains(MaterialState.selected)) {
return AppTheme.primaryColor;
}
return Colors.white;
}),
foregroundColor: MaterialStateProperty.resolveWith<Color>((states) {
if (states.contains(MaterialState.selected)) {
return Colors.white;
}
return AppTheme.textSecondary;
}),
shape: MaterialStateProperty.all(
RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
),
),
);
}
Widget _buildUserResults() {
if (_userResults.isEmpty) {
return const _InfoBanner(
icon: Icons.info_outline,
background: Color(0xFFEFF4FF),
textColor: Color(0xFF1A237E),
message: '暂无数据,输入关键字并点击“查询”试试。',
);
}
return NotificationListener<ScrollNotification>(
onNotification: (notification) {
if (notification is ScrollEndNotification &&
notification.metrics.extentAfter == 0 &&
_hasMore &&
!_isLoadingMore) {
_loadMore();
}
return true;
},
child: SingleChildScrollView(
physics: const AlwaysScrollableScrollPhysics(),
child: Column(
children: [
..._userResults.map(_UserTile.new),
if (_hasMore)
_isLoadingMore
? const Padding(
padding: EdgeInsets.all(16),
child: CircularProgressIndicator(),
)
: const SizedBox()
],
),
),
);
}
Widget _buildRepositoryResults() {
if (_repoResults.isEmpty) {
return const _InfoBanner(
icon: Icons.info_outline,
background: Color(0xFFEFF4FF),
textColor: Color(0xFF1A237E),
message: '还没有结果,输入关键字并点击查询即可获取仓库列表。',
);
}
return NotificationListener<ScrollNotification>(
onNotification: (notification) {
if (notification is ScrollEndNotification &&
notification.metrics.extentAfter == 0 &&
_hasMore &&
!_isLoadingMore) {
_loadMore();
}
return true;
},
child: SingleChildScrollView(
physics: const AlwaysScrollableScrollPhysics(),
child: Column(
children: [
..._repoResults.map(_RepoTile.new),
if (_hasMore)
_isLoadingMore
? const Padding(
padding: EdgeInsets.all(16),
child: CircularProgressIndicator(),
)
: const SizedBox()
],
),
),
);
}
}
enum QueryMode { user, repository }
class _InfoBanner extends StatelessWidget {
const _InfoBanner({
required this.icon,
required this.background,
required this.textColor,
required this.message,
});
final IconData icon;
final Color background;
final Color textColor;
final String message;
@override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: background,
borderRadius: BorderRadius.circular(12),
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(icon, color: textColor),
const SizedBox(width: 12),
Expanded(
child: Text(
message,
style: Theme.of(context)
.textTheme
.bodyMedium
?.copyWith(color: textColor),
),
),
],
),
);
}
}
class _UserTile extends StatelessWidget {
const _UserTile(this.user);
final GitCodeSearchUser user;
@override
Widget build(BuildContext context) {
final title = user.name?.isNotEmpty == true ? user.name! : user.login;
final subtitleParts = <String>[
'@${user.login}',
if (user.createdAt != null) '注册 ${user.createdAt}',
];
return Card(
margin: const EdgeInsets.only(bottom: 12),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
elevation: 2,
shadowColor: const Color.fromRGBO(0, 0, 0, 0.1),
child: ListTile(
leading: CircleAvatar(
backgroundImage: NetworkImage(user.avatarUrl),
onBackgroundImageError: (_, __) {},
backgroundColor: AppTheme.surfaceColor,
radius: 24,
),
title: Text(title, style: const TextStyle(fontWeight: FontWeight.bold)),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
subtitleParts.join(' · '),
style: const TextStyle(fontSize: 12),
),
if (user.htmlUrl != null)
Text(
user.htmlUrl!,
style: const TextStyle(fontSize: 12, color: Colors.blue),
),
],
),
contentPadding:
const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
),
);
}
}
class _RepoTile extends StatelessWidget {
const _RepoTile(this.repo);
final GitCodeRepository repo;
@override
Widget build(BuildContext context) {
return Card(
margin: const EdgeInsets.only(bottom: 12),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
elevation: 2,
shadowColor: const Color.fromRGBO(0, 0, 0, 0.1),
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: const Color(0x1A4361EE),
borderRadius: BorderRadius.circular(8),
),
child: const Icon(Icons.folder_outlined,
size: 24, color: AppTheme.primaryColor),
),
const SizedBox(width: 12),
Expanded(
child: Text(
repo.fullName,
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 16,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
],
),
const SizedBox(height: 8),
if (repo.description?.isNotEmpty == true)
Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Text(
repo.description!,
style: TextStyle(color: AppTheme.textSecondary),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
),
Wrap(
spacing: 8,
runSpacing: 4,
children: [
if (repo.language != null)
_StatChip(label: '语言', valueLabel: repo.language),
_StatChip(label: 'Star', value: repo.stars),
_StatChip(label: 'Fork', value: repo.forks),
],
),
const SizedBox(height: 8),
Text(
'更新 ${repo.updatedAt ?? '-'}',
style: const TextStyle(fontSize: 12),
),
Text(
repo.webUrl,
style: const TextStyle(fontSize: 12, color: Colors.blue),
),
],
),
),
);
}
}
class _StatChip extends StatelessWidget {
const _StatChip({
required this.label,
this.value,
this.valueLabel,
});
final String label;
final int? value;
final String? valueLabel;
@override
Widget build(BuildContext context) {
final textTheme = Theme.of(context).textTheme;
final display = valueLabel ?? (value ?? 0).toString();
return Chip(
label: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
display,
style: textTheme.titleMedium,
),
Text(label, style: textTheme.bodySmall),
],
),
);
}
}
| 2401_82544706/gitcode_pocket_tool | lib/pages/home_page.dart | Dart | unknown | 18,535 |
import 'package:flutter/material.dart';
import 'package:gitcode_pocket_tool/pages/home_page.dart';
import 'package:gitcode_pocket_tool/pages/repositories_page.dart';
import 'package:gitcode_pocket_tool/pages/organizations_page.dart';
import 'package:gitcode_pocket_tool/pages/profile_page.dart';
class MainNavigation extends StatefulWidget {
const MainNavigation({super.key});
@override
State<MainNavigation> createState() => _MainNavigationState();
}
class _MainNavigationState extends State<MainNavigation> {
int _currentIndex = 0;
final List<Widget> _pages = [
const HomePage(),
const RepositoriesPage(),
const OrganizationsPage(),
const ProfilePage(),
];
final List<BottomNavigationBarItem> _items = [
const BottomNavigationBarItem(
icon: Icon(Icons.home_outlined),
activeIcon: Icon(Icons.home),
label: '首页',
),
const BottomNavigationBarItem(
icon: Icon(Icons.code_outlined),
activeIcon: Icon(Icons.code),
label: '仓库',
),
const BottomNavigationBarItem(
icon: Icon(Icons.people_outline),
activeIcon: Icon(Icons.people),
label: '组织',
),
const BottomNavigationBarItem(
icon: Icon(Icons.person_outline),
activeIcon: Icon(Icons.person),
label: '我的',
),
];
void _onItemTapped(int index) {
setState(() {
_currentIndex = index;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: _pages[_currentIndex],
bottomNavigationBar: BottomNavigationBar(
items: _items,
currentIndex: _currentIndex,
onTap: _onItemTapped,
selectedItemColor: Colors.blue,
unselectedItemColor: Colors.grey,
showSelectedLabels: true,
showUnselectedLabels: true,
type: BottomNavigationBarType.fixed,
backgroundColor: Colors.white,
elevation: 8,
),
);
}
} | 2401_82544706/gitcode_pocket_tool | lib/pages/main_navigation.dart | Dart | unknown | 1,931 |
import 'package:flutter/material.dart';
import 'package:gitcode_pocket_tool/core/gitcode_api.dart';
import 'package:gitcode_pocket_tool/core/app_theme.dart';
import 'dart:async';
import 'package:gitcode_pocket_tool/core/app_config.dart';
class OrganizationsPage extends StatefulWidget {
const OrganizationsPage({super.key});
@override
State<OrganizationsPage> createState() => _OrganizationsPageState();
}
class _OrganizationsPageState extends State<OrganizationsPage> {
final GitCodeApiClient _apiClient = GitCodeApiClient();
List<GitCodeOrganization> _organizations = [];
bool _isLoading = false;
String? _errorMessage;
int _currentPage = 1;
bool _hasMore = true;
@override
void initState() {
super.initState();
_loadOrganizations();
}
Future<void> _loadOrganizations() async {
if (_isLoading || (!_hasMore && _currentPage > 1)) return;
setState(() {
_isLoading = true;
_errorMessage = null;
});
try {
// 使用新的API方法获取gitcode用户所属的组织列表
final newOrganizations = await _apiClient.getOrganizations(
username: 'gitcode', // 获取gitcode用户所属的组织
personalToken: AppConfig.demoToken,
perPage: 10,
page: _currentPage,
);
setState(() {
if (_currentPage == 1) {
_organizations = newOrganizations;
} else {
_organizations.addAll(newOrganizations);
}
_hasMore = newOrganizations.length == 10;
_currentPage++;
});
} catch (e) {
setState(() {
_errorMessage = e.toString();
});
} finally {
setState(() {
_isLoading = false;
});
}
}
Widget _buildOrganizationItem(GitCodeOrganization org) {
return Card(
margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
elevation: 2,
shadowColor: const Color.fromRGBO(0, 0, 0, 0.1),
child: Padding(
padding: const EdgeInsets.all(16),
child: Row(
children: [
CircleAvatar(
backgroundImage: NetworkImage(org.avatarUrl),
radius: 32,
backgroundColor: AppTheme.surfaceColor,
),
const SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
org.login,
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 16,
),
),
if (org.name != null && org.name!.isNotEmpty) ...[
Text(
org.name!,
style: TextStyle(color: AppTheme.textSecondary),
),
],
if (org.description != null) ...[
const SizedBox(height: 8),
Text(
org.description!,
style: TextStyle(
color: AppTheme.textSecondary, fontSize: 14),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
],
if (org.membersCount != null) ...[
const SizedBox(height: 8),
Text(
'${org.membersCount} 名成员',
style: TextStyle(
color: AppTheme.textSecondary, fontSize: 14),
),
],
],
),
),
const Icon(Icons.chevron_right, color: AppTheme.textSecondary),
],
),
),
);
}
Future<void> _refresh() async {
// 重置状态并重新加载数据
setState(() {
_currentPage = 1;
_hasMore = true;
_organizations = [];
});
await _loadOrganizations();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('组织'),
elevation: 4,
),
body: RefreshIndicator(
onRefresh: _refresh,
child: _isLoading
? const Center(child: CircularProgressIndicator())
: _errorMessage != null
? ListView(
children: [
Center(
child: Padding(
padding: const EdgeInsets.all(32),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(Icons.error_outline,
size: 48, color: AppTheme.errorColor),
const SizedBox(height: 16),
Text(
_errorMessage!,
textAlign: TextAlign.center,
style: TextStyle(color: AppTheme.textSecondary),
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: _refresh,
child: const Text('重试'),
),
],
),
),
),
],
)
: _organizations.isEmpty
? ListView(
children: [
Center(
child: Padding(
padding: const EdgeInsets.all(32),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(Icons.group_off,
size: 48, color: AppTheme.textSecondary),
const SizedBox(height: 16),
Text(
'暂无组织数据',
style: TextStyle(
color: AppTheme.textSecondary),
),
],
),
),
),
],
)
: NotificationListener<ScrollNotification>(
onNotification: (notification) {
if (notification is ScrollEndNotification &&
notification.metrics.extentAfter == 0 &&
_hasMore &&
!_isLoading) {
_loadOrganizations();
}
return true;
},
child: ListView.builder(
itemCount: _organizations.length + (_hasMore ? 1 : 0),
itemBuilder: (context, index) {
if (index == _organizations.length) {
return _isLoading
? const Center(
child: CircularProgressIndicator())
: const SizedBox();
}
return _buildOrganizationItem(
_organizations[index]);
},
),
),
),
);
}
}
| 2401_82544706/gitcode_pocket_tool | lib/pages/organizations_page.dart | Dart | unknown | 7,935 |
import 'package:flutter/material.dart';
import 'package:gitcode_pocket_tool/core/gitcode_api.dart';
import 'package:gitcode_pocket_tool/core/app_config.dart';
class ProfilePage extends StatefulWidget {
const ProfilePage({super.key});
@override
State<ProfilePage> createState() => _ProfilePageState();
}
class _ProfilePageState extends State<ProfilePage> {
final GitCodeApiClient _apiClient = GitCodeApiClient();
GitCodeUser? _currentUser;
bool _isLoading = true;
@override
void initState() {
super.initState();
_loadUserProfile();
}
Future<void> _loadUserProfile() async {
setState(() {
_isLoading = true;
});
try {
// 为了演示,我们使用一个模拟的用户名
final user = await _apiClient.fetchUser(
'demo_user',
personalToken: AppConfig.demoToken,
);
setState(() {
_currentUser = user;
});
} catch (e) {
setState(() {
// 如果获取失败,使用模拟数据
_currentUser = GitCodeUser(
login: 'demo_user',
avatarUrl: 'https://via.placeholder.com/150',
name: '演示用户',
bio: '这是一个演示账号',
publicRepos: 12,
followers: 56,
following: 42,
);
});
} finally {
setState(() {
_isLoading = false;
});
}
}
Future<void> _refreshUserProfile() async {
await _loadUserProfile();
}
Widget _buildUserInfoSection() {
return Column(
children: [
Center(
child: Stack(
children: [
CircleAvatar(
backgroundImage: NetworkImage(_currentUser!.avatarUrl),
radius: 50,
),
Positioned(
bottom: 0,
right: 0,
child: Container(
decoration: const BoxDecoration(
color: Colors.white,
shape: BoxShape.circle,
),
padding: const EdgeInsets.all(4),
child: const Icon(Icons.camera_alt, color: Colors.grey),
),
),
],
),
),
const SizedBox(height: 16),
Text(
_currentUser!.name ?? _currentUser!.login,
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20,
),
),
Text(
'@${_currentUser!.login}',
style: const TextStyle(color: Colors.grey),
),
if (_currentUser!.bio != null && _currentUser!.bio!.isNotEmpty) ...[
const SizedBox(height: 12),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 32),
child: Text(
_currentUser!.bio!,
textAlign: TextAlign.center,
style: const TextStyle(fontSize: 14),
),
),
],
const SizedBox(height: 24),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Column(
children: [
Text(
_currentUser!.publicRepos?.toString() ?? '0',
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20,
),
),
const Text('仓库'),
],
),
Column(
children: [
Text(
_currentUser!.followers?.toString() ?? '0',
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20,
),
),
const Text('粉丝'),
],
),
Column(
children: [
Text(
_currentUser!.following?.toString() ?? '0',
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20,
),
),
const Text('关注'),
],
),
],
),
],
);
}
Widget _buildMenuSection() {
final menuItems = [
{
'icon': Icons.person_outline,
'title': '个人资料',
'onTap': () {},
},
{
'icon': Icons.settings_outlined,
'title': '设置',
'onTap': () {},
},
{
'icon': Icons.help_outline,
'title': '帮助与反馈',
'onTap': () {},
},
{
'icon': Icons.info_outline,
'title': '关于',
'onTap': () {},
},
];
return ListView.separated(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
itemCount: menuItems.length,
separatorBuilder: (context, index) => const Divider(),
itemBuilder: (context, index) {
final item = menuItems[index];
return ListTile(
leading: Icon(item['icon'] as IconData),
title: Text(item['title'] as String),
trailing: const Icon(Icons.chevron_right),
onTap: item['onTap'] as VoidCallback,
);
},
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('我的'),
),
body: RefreshIndicator(
onRefresh: _refreshUserProfile,
child: _isLoading
? const Center(child: CircularProgressIndicator())
: _currentUser != null
? SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: Column(
children: [
_buildUserInfoSection(),
const SizedBox(height: 32),
Card(
child: _buildMenuSection(),
),
const SizedBox(height: 24),
ElevatedButton(
onPressed: () {},
style: ElevatedButton.styleFrom(
backgroundColor: Colors.red,
minimumSize: const Size(double.infinity, 48),
),
child: const Text('退出登录'),
),
],
),
)
: const Center(child: Text('无法加载用户信息')),
),
);
}
}
| 2401_82544706/gitcode_pocket_tool | lib/pages/profile_page.dart | Dart | unknown | 6,577 |
import 'package:flutter/material.dart';
import 'package:gitcode_pocket_tool/core/gitcode_api.dart';
import 'package:gitcode_pocket_tool/core/app_theme.dart';
import 'dart:async';
import 'package:gitcode_pocket_tool/core/app_config.dart';
class RepositoriesPage extends StatefulWidget {
const RepositoriesPage({super.key});
@override
State<RepositoriesPage> createState() => _RepositoriesPageState();
}
class _RepositoriesPageState extends State<RepositoriesPage> {
final GitCodeApiClient _apiClient = GitCodeApiClient();
List<GitCodeRepository> _repositories = [];
bool _isLoading = false;
String? _errorMessage;
int _currentPage = 1;
bool _hasMore = true;
@override
void initState() {
super.initState();
_loadRepositories();
}
Future<void> _loadRepositories() async {
if (_isLoading || (!_hasMore && _currentPage > 1)) return;
setState(() {
_isLoading = true;
_errorMessage = null;
});
try {
// 使用新的API方法获取gitcode用户的仓库列表
final newRepositories = await _apiClient.getUserRepositories(
username: 'gitcode', // 获取gitcode官方用户的仓库
personalToken: AppConfig.demoToken,
sort: 'updated',
direction: 'desc',
perPage: 10,
page: _currentPage,
);
setState(() {
if (_currentPage == 1) {
_repositories = newRepositories;
} else {
_repositories.addAll(newRepositories);
}
// 如果没有更多数据了,设置_hasMore为false
_hasMore = newRepositories.length == 10;
_currentPage++;
});
} catch (e) {
setState(() {
_errorMessage = e.toString();
});
} finally {
setState(() {
_isLoading = false;
});
}
}
Widget _buildRepositoryItem(GitCodeRepository repo) {
return Card(
margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
elevation: 2,
shadowColor: const Color.fromRGBO(0, 0, 0, 0.1),
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: const Color(0x1A4361EE),
borderRadius: BorderRadius.circular(8),
),
child: const Icon(Icons.code,
size: 24, color: AppTheme.primaryColor),
),
const SizedBox(width: 12),
Expanded(
child: Text(
'仓库名称',
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 16,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
],
),
const SizedBox(height: 8),
if (repo.description != null) ...[
Text(
repo.description!,
style: TextStyle(color: AppTheme.textSecondary),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
const SizedBox(height: 8),
],
Row(
children: [
const Icon(Icons.star, size: 16, color: Colors.amber),
const SizedBox(width: 4),
Text(
'${repo.stars ?? '0'}',
style: TextStyle(fontSize: 14, color: AppTheme.textSecondary),
),
const SizedBox(width: 16),
const Icon(Icons.visibility,
size: 16, color: AppTheme.textSecondary),
const SizedBox(width: 4),
Text(
'${repo.watchers ?? '0'}',
style: TextStyle(fontSize: 14, color: AppTheme.textSecondary),
),
const SizedBox(width: 16),
if (repo.language != null) ...[
Container(
width: 12,
height: 12,
decoration: BoxDecoration(
color: Colors.blue,
borderRadius: BorderRadius.circular(6),
),
),
const SizedBox(width: 4),
Text(
repo.language!,
style:
TextStyle(fontSize: 14, color: AppTheme.textSecondary),
),
],
],
),
],
),
),
);
}
Future<void> _refresh() async {
// 重置状态并重新加载数据
setState(() {
_currentPage = 1;
_hasMore = true;
_repositories = [];
});
await _loadRepositories();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('仓库'),
elevation: 4,
),
body: RefreshIndicator(
onRefresh: _refresh,
child: _isLoading && _currentPage == 1
? const Center(child: CircularProgressIndicator())
: _errorMessage != null
? ListView(
children: [
Center(
child: Padding(
padding: const EdgeInsets.all(32),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(Icons.error_outline,
size: 48, color: AppTheme.errorColor),
const SizedBox(height: 16),
Text(
_errorMessage!,
textAlign: TextAlign.center,
style: TextStyle(color: AppTheme.textSecondary),
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: _refresh,
child: const Text('重试'),
),
],
),
),
),
],
)
: _repositories.isEmpty
? ListView(
children: [
Center(
child: Padding(
padding: const EdgeInsets.all(32),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(Icons.code_off,
size: 48, color: AppTheme.textSecondary),
const SizedBox(height: 16),
Text(
'暂无仓库数据',
style: TextStyle(
color: AppTheme.textSecondary),
),
],
),
),
),
],
)
: NotificationListener<ScrollNotification>(
onNotification: (notification) {
if (notification is ScrollEndNotification &&
notification.metrics.extentAfter == 0 &&
_hasMore &&
!_isLoading) {
_loadRepositories();
}
return true;
},
child: ListView.builder(
itemCount: _repositories.length + (_hasMore ? 1 : 0),
itemBuilder: (context, index) {
if (index == _repositories.length) {
return _isLoading
? const Center(
child: CircularProgressIndicator())
: const SizedBox();
}
return _buildRepositoryItem(_repositories[index]);
},
),
),
),
);
}
}
| 2401_82544706/gitcode_pocket_tool | lib/pages/repositories_page.dart | Dart | unknown | 8,932 |
// Script for compiling build behavior. It is built in the build plug-in and cannot be modified currently.
import { hapTasks } from '@ohos/hvigor-ohos-plugin';
export default {
system: hapTasks, /* Built-in plugin of Hvigor. It cannot be modified. */
plugins: [] /* Custom plugin to extend the functionality of Hvigor. */
}
| 2401_82544706/gitcode_pocket_tool | ohos/entry/hvigorfile.ts | TypeScript | unknown | 341 |
import hilog from '@ohos.hilog';
import TestRunner from '@ohos.application.testRunner';
import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry';
var abilityDelegator = undefined
var abilityDelegatorArguments = undefined
async function onAbilityCreateCallback() {
hilog.info(0x0000, 'testTag', '%{public}s', 'onAbilityCreateCallback');
}
async function addAbilityMonitorCallback(err: any) {
hilog.info(0x0000, 'testTag', 'addAbilityMonitorCallback : %{public}s', JSON.stringify(err) ?? '');
}
export default class OpenHarmonyTestRunner implements TestRunner {
constructor() {
}
onPrepare() {
hilog.info(0x0000, 'testTag', '%{public}s', 'OpenHarmonyTestRunner OnPrepare ');
}
async onRun() {
hilog.info(0x0000, 'testTag', '%{public}s', 'OpenHarmonyTestRunner onRun run');
abilityDelegatorArguments = AbilityDelegatorRegistry.getArguments()
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator()
var testAbilityName = abilityDelegatorArguments.bundleName + '.TestAbility'
let lMonitor = {
abilityName: testAbilityName,
onAbilityCreate: onAbilityCreateCallback,
};
abilityDelegator.addAbilityMonitor(lMonitor, addAbilityMonitorCallback)
var cmd = 'aa start -d 0 -a TestAbility' + ' -b ' + abilityDelegatorArguments.bundleName
var debug = abilityDelegatorArguments.parameters['-D']
if (debug == 'true')
{
cmd += ' -D'
}
hilog.info(0x0000, 'testTag', 'cmd : %{public}s', cmd);
abilityDelegator.executeShellCommand(cmd,
(err: any, d: any) => {
hilog.info(0x0000, 'testTag', 'executeShellCommand : err : %{public}s', JSON.stringify(err) ?? '');
hilog.info(0x0000, 'testTag', 'executeShellCommand : data : %{public}s', d.stdResult ?? '');
hilog.info(0x0000, 'testTag', 'executeShellCommand : data : %{public}s', d.exitCode ?? '');
})
hilog.info(0x0000, 'testTag', '%{public}s', 'OpenHarmonyTestRunner onRun end');
}
} | 2401_82544706/gitcode_pocket_tool | ohos/entry/src/ohosTest/ets/testrunner/OpenHarmonyTestRunner.ts | TypeScript | unknown | 2,120 |
import path from 'path'
import { injectNativeModules } from 'flutter-hvigor-plugin';
injectNativeModules(__dirname, path.dirname(__dirname)) | 2401_82544706/gitcode_pocket_tool | ohos/hvigorconfig.ts | TypeScript | unknown | 141 |
import path from 'path'
import { appTasks } from '@ohos/hvigor-ohos-plugin';
import { flutterHvigorPlugin } from 'flutter-hvigor-plugin';
export default {
system: appTasks, /* Built-in plugin of Hvigor. It cannot be modified. */
plugins:[flutterHvigorPlugin(path.dirname(__dirname))] /* Custom plugin to extend the functionality of Hvigor. */
} | 2401_82544706/gitcode_pocket_tool | ohos/hvigorfile.ts | TypeScript | unknown | 362 |
// This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility in the flutter_test package. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter_test/flutter_test.dart';
import 'package:gitcode_pocket_tool/main.dart';
void main() {
testWidgets('展示查询表单与初始提示', (WidgetTester tester) async {
await tester.pumpWidget(const GitCodePocketToolApp());
expect(find.textContaining('输入关键字 + access token'), findsOneWidget);
expect(find.text('搜索关键字'), findsOneWidget);
expect(find.text('查询'), findsOneWidget);
});
}
| 2401_82544706/gitcode_pocket_tool | test/widget_test.dart | Dart | unknown | 815 |
package com.yf.common.command;
import com.yf.common.entity.PoolInfo;
import com.yf.core.partition.Impl.LinkedBlockingQ;
import com.yf.core.partition.Partition;
import com.yf.core.rejectstrategy.impl.CallerRunsStrategy;
import com.yf.core.resource_manager.PartiResourceManager;
import com.yf.core.resource_manager.RSResourceManager;
import com.yf.core.rejectstrategy.RejectStrategy;
import com.yf.core.threadpool.ThreadPool;
import com.yf.core.tp_regulator.UnifiedTPRegulator;
import com.yf.core.workerfactory.WorkerFactory;
import java.io.Console;
import java.util.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
/**
* @author yyf
* @description 统一线程池命令行工具(适配UnifiedTPRegulator)
* 核心变更:支持多线程池管控,所有操作通过UnifiedTPRegulator统一调度
* 命令格式调整:所有涉及线程池的操作需指定「线程池名称」(部分查询命令支持省略查全部)
*/
public class PoolCommandHandler {
// 命令历史记录(最多100条)
private final BlockingQueue<String> commandHistory = new LinkedBlockingDeque<>(100);
private int historyIndex = -1;
private volatile boolean isRunning;
private Thread commandThread;
// 命令提示符
private static final String PROMPT = "yf:unified-pool> ";
// 帮助信息常量
private static final String HELP_HEADER = "\n======= 统一线程池命令行工具 v2.0 =======";
private static final String HELP_FOOTER = "=======================================\n";
public PoolCommandHandler() {
this.isRunning = false;
}
/**
* 启动命令行工具
*/
public void start() {
if (isRunning) {
System.out.println("命令行工具已在运行中");
return;
}
isRunning = true;
commandThread = new Thread(this::commandLoop, "UnifiedPool-Command-Thread");
commandThread.setDaemon(true);
commandThread.start();
printWelcomeMessage();
}
/**
* 停止命令行工具
*/
public void stop() {
isRunning = false;
if (commandThread != null) {
commandThread.interrupt();
commandThread = null;
}
System.out.println("\n统一线程池命令行工具已停止");
}
/**
* 打印欢迎信息
*/
private void printWelcomeMessage() {
System.out.println("\n=== 统一线程池命令行工具已启动 ===");
System.out.println("提示1: 输入 'yf help' 查看所有可用命令");
System.out.println("提示2: 使用上下方向键查看命令历史");
System.out.println("提示3: 可用线程池列表: " + getAvailableThreadPoolNames());
System.out.print(PROMPT);
System.out.flush();
}
/**
* 命令循环(核心:处理输入与命令分发)
*/
private void commandLoop() {
Console console = System.console();
if (console == null) {
System.err.println("无法获取控制台,切换至简单输入模式");
simpleInputMode();
return;
}
try {
while (isRunning) {
// 读取带历史记录的命令
String command = readCommandWithHistory(console);
if (command == null || command.trim().isEmpty()) {
System.out.print(PROMPT);
System.out.flush();
continue;
}
// 保存非空命令到历史
commandHistory.offer(command);
historyIndex = -1;
// 处理命令
processCommand(command);
System.out.print(PROMPT);
System.out.flush();
}
} catch (Exception e) {
if (isRunning) {
System.err.println("\n命令处理异常: " + e.getMessage());
System.out.print(PROMPT);
System.out.flush();
}
}
}
/**
* 带历史记录的命令读取(上下键切换)
*/
private String readCommandWithHistory(Console console) {
StringBuilder input = new StringBuilder();
List<String> historyList = new ArrayList<>(commandHistory);
Collections.reverse(historyList); // 反转:最新命令在最前
while (true) {
int c;
try {
c = System.in.read();
} catch (Exception e) {
return isRunning ? input.toString() : null;
}
// Ctrl+C 退出
if (c == 3) {
System.out.println("\n接收到中断信号,退出工具");
stop();
return null;
}
// 回车确认
if (c == '\n' || c == '\r') {
System.out.println();
return input.toString();
}
// 退格删除
if (c == 127) {
if (input.length() > 0) {
input.deleteCharAt(input.length() - 1);
System.out.print("\b \b"); // 清除控制台字符
}
continue;
}
// 上下箭头(历史记录)
if (c == 27) {
try {
if (System.in.read() == 91) {
int key = System.in.read();
// 上箭头:上一条历史
if (key == 65) {
if (historyIndex < historyList.size() - 1) {
historyIndex++;
clearCurrentInput(input.length());
input.setLength(0);
if (historyIndex < historyList.size()) {
String historyCmd = historyList.get(historyIndex);
input.append(historyCmd);
System.out.print(historyCmd);
}
}
}
// 下箭头:下一条历史
else if (key == 66) {
if (historyIndex >= 0) {
historyIndex--;
clearCurrentInput(input.length());
input.setLength(0);
if (historyIndex >= 0) {
String historyCmd = historyList.get(historyIndex);
input.append(historyCmd);
System.out.print(historyCmd);
}
}
}
}
} catch (Exception e) {
// 忽略控制字符读取错误
}
continue;
}
// 普通字符输入
input.append((char) c);
System.out.print((char) c);
}
}
/**
* 清除当前输入内容(退格时用)
*/
private void clearCurrentInput(int length) {
for (int i = 0; i < length; i++) {
System.out.print("\b \b");
}
}
/**
* 简单输入模式(Console不可用时降级)
*/
private void simpleInputMode() {
Scanner scanner = new Scanner(System.in);
while (isRunning) {
try {
System.out.print(PROMPT);
System.out.flush();
if (!scanner.hasNextLine()) {
break;
}
String command = scanner.nextLine().trim();
if (!command.isEmpty()) {
commandHistory.offer(command);
}
processCommand(command);
} catch (Exception e) {
if (isRunning) {
System.err.println("命令处理异常: " + e.getMessage());
}
}
}
scanner.close();
}
/**
* 命令核心处理逻辑
*/
private void processCommand(String command) {
if (command == null || command.trim().isEmpty()) {
return;
}
// 命令必须以 "yf " 开头
if (!command.startsWith("yf ")) {
System.out.println("❌ 命令格式错误!请以 'yf ' 开头(示例:yf info pool)");
System.out.println(" 输入 'yf help' 查看完整命令列表");
return;
}
// 分割命令(移除前缀 "yf ")
String[] parts = command.substring(3).trim().split("\\s+");
if (parts.length == 0) {
System.out.println("❌ 请输入具体命令!输入 'yf help' 查看帮助");
return;
}
try {
switch (parts[0]) {
case "info":
handleInfoCommand(parts);
break;
case "change":
handleChangeCommand(parts);
break;
case "help":
printHelp();
break;
case "exit":
System.out.println("✅ 正在退出命令行工具...");
stop();
break;
default:
System.out.println("❌ 未知命令: " + parts[0]);
System.out.println(" 输入 'yf help' 查看所有可用命令");
}
} catch (NumberFormatException e) {
System.out.println("❌ 数字格式错误: " + e.getMessage());
} catch (IllegalArgumentException e) {
System.out.println("❌ 参数错误: " + e.getMessage());
} catch (Exception e) {
System.err.println("❌ 命令执行失败: " + e.getMessage());
}
}
// ============================= 信息查询命令处理 =============================
private void handleInfoCommand(String[] parts) {
if (parts.length < 2) {
System.out.println("❌ info命令需指定查询类型!可用类型:pool, worker, taskNum, partitionTaskNum");
System.out.println(" 示例:yf info pool(查所有线程池)、yf info worker tp1(查tp1的线程状态)");
return;
}
// 解析查询类型和线程池名称(可选)
String infoType = parts[1];
String tpName = parts.length >= 3 ? parts[2] : null;
// 校验线程池名称(如果指定)
if (tpName != null && !UnifiedTPRegulator.getAllThreadPoolNames().contains(tpName)) {
throw new IllegalArgumentException("线程池名称不存在!可用线程池:" + getAvailableThreadPoolNames());
}
switch (infoType) {
case "pool":
printThreadPoolInfo(tpName); // 查线程池基本信息(tpName为null查所有)
break;
case "worker":
if (tpName == null) {
throw new IllegalArgumentException("查询线程状态需指定线程池名称!示例:yf info worker tp1");
}
printThreadsInfo(tpName); // 查指定线程池的线程状态
break;
case "taskNum":
printTaskNums(tpName); // 查队列总任务数(tpName为null查所有)
break;
case "partitionTaskNum":
if (tpName == null) {
throw new IllegalArgumentException("查询分区任务数需指定线程池名称!示例:yf info partitionTaskNum tp1");
}
printPartitionTaskNums(tpName); // 查指定线程池的分区任务数
break;
default:
System.out.println("❌ 未知的info查询类型: " + infoType);
System.out.println(" 可用类型:pool, worker, taskNum, partitionTaskNum");
}
}
// 打印线程池基本信息(支持单池/所有)
private void printThreadPoolInfo(String tpName) {
System.out.println("\n================ 线程池基本信息 ================");
List<PoolInfo> poolInfos = tpName == null
? UnifiedTPRegulator.getAllThreadPoolInfo()
: Collections.singletonList(UnifiedTPRegulator.getThreadPoolInfo(tpName));
if (poolInfos.isEmpty()) {
System.out.println("⚠️ 无已注册的线程池");
System.out.println("===============================================");
return;
}
for (PoolInfo info : poolInfos) {
System.out.println("线程池类型:"+info.getType());
System.out.println("线程池名称: " + info.getPoolName());
System.out.println("核心线程数: " + info.getCoreNums());
System.out.println("最大线程数: " + info.getMaxNums());
System.out.println("线程存活时间: " + info.getAliveTime() + "ms");
System.out.println("线程名称: " + info.getThreadName());
System.out.println("是否允许核心线程销毁: " + info.isCoreDestroy());
System.out.println("是否守护线程: " + info.isDaemon());
System.out.println("使用队列: " + info.getQueueName());
System.out.println("拒绝策略: " + info.getRejectStrategyName());
System.out.println("-----------------------------------------------");
}
System.out.println("===============================================");
}
// 打印指定线程池的线程状态(核心/额外线程分开)
private void printThreadsInfo(String tpName) {
System.out.println("\n================ " + tpName + " 线程状态 ================");
Map<String, Map<Thread.State, Integer>> threadsInfo = UnifiedTPRegulator.getThreadsInfo(tpName);
// 打印核心线程状态
System.out.println("【核心线程】");
printThreadStateMap(threadsInfo.get("CORE"));
// 打印额外线程状态
System.out.println("【额外线程】");
printThreadStateMap(threadsInfo.get("EXTRA"));
System.out.println("=================================================");
}
// 辅助:打印线程状态统计(State -> 数量)
private void printThreadStateMap(Map<Thread.State, Integer> stateMap) {
if (stateMap == null || stateMap.isEmpty()) {
System.out.println(" 无活跃线程");
return;
}
for (Map.Entry<Thread.State, Integer> entry : stateMap.entrySet()) {
System.out.println(" " + entry.getKey() + ": " + entry.getValue() + "个");
}
}
// 打印队列总任务数(支持单池/所有)
private void printTaskNums(String tpName) {
System.out.println("\n================ 队列任务数统计 ================");
List<String> tpNames = tpName == null
? UnifiedTPRegulator.getAllThreadPoolNames()
: Collections.singletonList(tpName);
if (tpNames.isEmpty()) {
System.out.println("⚠️ 无已注册的线程池");
System.out.println("===============================================");
return;
}
for (String name : tpNames) {
int taskNum = UnifiedTPRegulator.getTaskNums(name);
System.out.println(name + ": " + taskNum + "个任务");
}
System.out.println("===============================================");
}
// 打印指定线程池的分区任务数
private void printPartitionTaskNums(String tpName) {
System.out.println("\n================ " + tpName + " 分区任务数 ================");
Map<Integer, Integer> partitionTaskMap = UnifiedTPRegulator.getPartitionTaskNums(tpName);
if (partitionTaskMap.isEmpty()) {
System.out.println("⚠️ 无分区任务数据");
System.out.println("=================================================");
return;
}
int total = 0;
for (Map.Entry<Integer, Integer> entry : partitionTaskMap.entrySet()) {
System.out.println("分区" + entry.getKey() + ": " + entry.getValue() + "个任务");
total += entry.getValue();
}
System.out.println("-----------------------------------------------");
System.out.println("总任务数: " + total + "个");
System.out.println("=================================================");
}
// ============================= 配置修改命令处理 =============================
private void handleChangeCommand(String[] parts) throws Exception {
if (parts.length < 2) {
System.out.println("❌ change命令需指定修改类型!可用类型:worker, queue, rejectstrategy");
System.out.println(" 示例:yf change worker tp1 -coreNums 5、yf change queue tp1 linked");
return;
}
String changeType = parts[1];
// 所有修改命令必须指定线程池名称(parts[2])
if (parts.length < 3) {
throw new IllegalArgumentException("修改命令需指定线程池名称!示例:yf change " + changeType + " tp1 ...");
}
String tpName = parts[2];
// 校验线程池名称
if (!UnifiedTPRegulator.getAllThreadPoolNames().contains(tpName)) {
throw new IllegalArgumentException("线程池名称不存在!可用线程池:" + getAvailableThreadPoolNames());
}
switch (changeType) {
case "worker":
handleChangeWorker(tpName, parts); // 修改线程参数
break;
case "queue":
handleChangeQueue(tpName, parts); // 修改队列
break;
case "rejectstrategy":
handleChangeRejectStrategy(tpName, parts); // 修改拒绝策略
break;
default:
System.out.println("❌ 未知的change修改类型: " + changeType);
System.out.println(" 可用类型:worker, queue, rejectstrategy");
}
}
// 修改线程池Worker参数(核心数、最大数等)
private void handleChangeWorker(String tpName, String[] parts) {
// 参数格式:yf change worker tp1 -coreNums 5 -maxNums 10
if (parts.length < 4) {
throw new IllegalArgumentException("需指定至少一个Worker参数!示例:yf change worker " + tpName + " -coreNums 5");
}
// 解析参数(-key value 格式)
Map<String, String> params = parseWorkerParams(parts, 3); // 从索引3开始是参数(parts[0]=change,1=worker,2=tpName)
// 转换参数类型
Integer coreNums = parseIntegerParam(params, "coreNums");
Integer maxNums = parseIntegerParam(params, "maxNums");
Boolean coreDestroy = parseBooleanParam(params, "coreDestroy");
Integer aliveTime = parseIntegerParam(params, "aliveTime");
Boolean isDaemon = parseBooleanParam(params, "isUseDaemonThread");
// 检查是否有有效参数
if (coreNums == null && maxNums == null && coreDestroy == null && aliveTime == null && isDaemon == null) {
throw new IllegalArgumentException("未识别到有效参数!可用参数:-coreNums, -maxNums, -coreDestroy, -aliveTime, -isUseDaemonThread");
}
// 调用UnifiedTPRegulator修改
boolean success = UnifiedTPRegulator.changeWorkerParams(tpName, coreNums, maxNums, coreDestroy, aliveTime, isDaemon);
if (success) {
System.out.println("✅ " + tpName + " 线程参数修改成功!");
} else {
System.err.println("❌ " + tpName + " 线程参数修改失败(可能参数不合法,如maxNums < coreNums)");
}
}
// 修改线程池队列
private void handleChangeQueue(String tpName, String[] parts) throws Exception {
// 参数格式:yf change queue tp1 linked
if (parts.length < 4) {
throw new IllegalArgumentException("需指定队列名称!示例:yf change queue " + tpName + " linked");
}
String queueName = parts[3];
// 校验队列名称
if (!UnifiedTPRegulator.getAllQueueName().contains(queueName)) {
throw new IllegalArgumentException("队列名称不存在!可用队列:" + getAvailableQueues());
}
// 创建新队列实例(复用原队列容量)
Partition<?> oldPartition = UnifiedTPRegulator.getResource(tpName).getPartition();
Class<?> queueClass = PartiResourceManager.getResources().get(queueName);
Partition<Runnable> newQueue = (Partition<Runnable>) queueClass.getConstructor(Integer.class).newInstance(oldPartition.getCapacity());
// 调用UnifiedTPRegulator修改
boolean success = UnifiedTPRegulator.changeQueue(tpName, newQueue);
if (success) {
System.out.println("✅ " + tpName + " 队列修改成功!新队列:" + queueName);
} else {
System.err.println("❌ " + tpName + " 队列修改失败!");
}
}
// 修改线程池拒绝策略
private void handleChangeRejectStrategy(String tpName, String[] parts) throws Exception {
// 参数格式:yf change rejectstrategy tp1 callerRuns
if (parts.length < 4) {
throw new IllegalArgumentException("需指定拒绝策略名称!示例:yf change rejectstrategy " + tpName + " callerRuns");
}
String strategyName = parts[3];
// 校验拒绝策略名称
if (!UnifiedTPRegulator.getAllRejectStrategyName().contains(strategyName)) {
throw new IllegalArgumentException("拒绝策略不存在!可用策略:" + getAvailableRejectStrategies());
}
// 创建新拒绝策略实例
Class<?> strategyClass = RSResourceManager.getResources().get(strategyName);
RejectStrategy newStrategy = (RejectStrategy) strategyClass.getConstructor().newInstance();
// 调用UnifiedTPRegulator修改
boolean success = UnifiedTPRegulator.changeRejectStrategy(tpName, newStrategy, strategyName);
if (success) {
System.out.println("✅ " + tpName + " 拒绝策略修改成功!新策略:" + strategyName);
} else {
System.err.println("❌ " + tpName + " 拒绝策略修改失败!");
}
}
// ============================= 辅助工具方法 =============================
// 解析Worker参数(-key value格式)
private Map<String, String> parseWorkerParams(String[] parts, int startIndex) {
Map<String, String> params = new HashMap<>();
for (int i = startIndex; i < parts.length; i += 2) {
// 检查是否有完整的key-value
if (i + 1 >= parts.length) {
System.out.println("⚠️ 参数 " + parts[i] + " 缺少值,已忽略");
break;
}
String key = parts[i].startsWith("-") ? parts[i].substring(1) : parts[i];
String value = parts[i + 1];
// 校验参数合法性
if (!Arrays.asList("coreNums", "maxNums", "coreDestroy", "aliveTime", "isUseDaemonThread").contains(key)) {
System.out.println("⚠️ 未知参数 " + parts[i] + ",已忽略");
continue;
}
params.put(key, value);
}
return params;
}
// 解析整数参数(如coreNums、maxNums)
private Integer parseIntegerParam(Map<String, String> params, String key) {
if (!params.containsKey(key)) {
return null;
}
try {
int value = Integer.parseInt(params.get(key));
if (value < 0) {
System.out.println("⚠️ 参数 " + key + " 不能为负数,已忽略");
return null;
}
return value;
} catch (NumberFormatException e) {
System.out.println("⚠️ 参数 " + key + " 必须是整数,已忽略");
return null;
}
}
// 解析布尔参数(如coreDestroy、isUseDaemonThread)
private Boolean parseBooleanParam(Map<String, String> params, String key) {
if (!params.containsKey(key)) {
return null;
}
String value = params.get(key).toLowerCase();
if (value.equals("true") || value.equals("false")) {
return Boolean.parseBoolean(value);
}
System.out.println("⚠️ 参数 " + key + " 必须是 true/false,已忽略");
return null;
}
// 获取可用线程池名称(逗号分隔)
private String getAvailableThreadPoolNames() {
List<String> tpNames = UnifiedTPRegulator.getAllThreadPoolNames();
return tpNames.isEmpty() ? "无" : String.join(", ", tpNames);
}
// 获取可用队列名称(逗号分隔)
private String getAvailableQueues() {
List<String> queueNames = UnifiedTPRegulator.getAllQueueName();
return queueNames.isEmpty() ? "无" : String.join(", ", queueNames);
}
// 获取可用拒绝策略名称(逗号分隔)
private String getAvailableRejectStrategies() {
List<String> strategyNames = UnifiedTPRegulator.getAllRejectStrategyName();
return strategyNames.isEmpty() ? "无" : String.join(", ", strategyNames);
}
// ============================= 帮助信息 =============================
private void printHelp() {
StringBuilder help = new StringBuilder();
help.append(HELP_HEADER).append("\n");
help.append("说明:所有命令需以 'yf ' 开头,线程池名称可通过 'yf info pool' 查看\n\n");
// 1. 信息查询命令
help.append("【1. 信息查询命令】\n");
help.append(" yf info pool [tpName] - 查看线程池基本信息(无tpName查所有)\n");
help.append(" 示例:yf info pool、yf info pool tp1\n");
help.append(" yf info worker <tpName> - 查看指定线程池的线程状态(核心/额外线程)\n");
help.append(" 示例:yf info worker tp1\n");
help.append(" yf info taskNum [tpName] - 查看队列总任务数(无tpName查所有)\n");
help.append(" 示例:yf info taskNum、yf info taskNum tp1\n");
help.append(" yf info partitionTaskNum <tpName> - 查看指定线程池的分区任务数\n");
help.append(" 示例:yf info partitionTaskNum tp1\n\n");
// 2. 配置修改命令
help.append("【2. 配置修改命令】\n");
help.append(" yf change worker <tpName> [参数] - 修改线程参数(参数可选,至少一个)\n");
help.append(" 参数:-coreNums [数字](核心线程数)\n");
help.append(" -maxNums [数字](最大线程数)\n");
help.append(" -coreDestroy [true/false](核心线程是否可销毁)\n");
help.append(" -aliveTime [数字](线程存活时间,ms)\n");
help.append(" -isUseDaemonThread [true/false](是否守护线程)\n");
help.append(" 示例:yf change worker tp1 -coreNums 5 -maxNums 10\n");
help.append("\n");
help.append(" yf change queue <tpName> <queueName> - 修改指定线程池的队列\n");
help.append(" 可用队列:").append(getAvailableQueues()).append("\n");
help.append(" 示例:yf change queue tp1 linked\n");
help.append("\n");
help.append(" yf change rejectstrategy <tpName> <strategyName> - 修改指定线程池的拒绝策略\n");
help.append(" 可用策略:").append(getAvailableRejectStrategies()).append("\n");
help.append(" 示例:yf change rejectstrategy tp1 callerRuns\n\n");
// 3. 其他命令
help.append("【3. 其他命令】\n");
help.append(" yf help - 显示此帮助信息\n");
help.append(" yf exit - 退出命令行工具\n");
help.append(" 上下方向键 - 查看命令历史记录\n");
help.append(HELP_FOOTER);
System.out.print(help.toString());
}
public static void main(String[] args) throws InterruptedException {
ThreadPool pool = new ThreadPool(
5,
10,
"GC-ThreadPool",
new WorkerFactory("", false, true, 10),
new LinkedBlockingQ<Runnable>(50),
new CallerRunsStrategy()
);
new PoolCommandHandler().start();
Thread.sleep(100000000000000L);
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/common/command/PoolCommandHandler.java | Java | mit | 29,474 |
package com.yf.common.constant;
//worker相关的常量
/**
* @author yyf
* @description
*/
public class Constant {
//线程相关
public final static String CORE = "core";//核心线程
public final static String EXTRA = "extra";//非核心线程
public final static String VIRTUAL = "virtual:";//虚拟线程
public final static String PLATFORM = "platform:";//平台线程
//线程池相关
public final static String LITTLE_CHIEF = "littleChief";//轻量级GC线程池
public final static String IO = "io";
public final static String CPU = "cpu";
//gc任务相关---有关调度规则的类型
public final static String OFFER = "offer:";
public final static String POLL = "poll:";
public final static String REMOVE = "remove:";
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/common/constant/Constant.java | Java | mit | 793 |
package com.yf.common.constant;
import lombok.extern.slf4j.Slf4j;
import java.lang.ref.SoftReference;
/**
* @author yyf
* @date 2025/9/19 11:03
* @description 使用软引用管理的Logo常量类(过度设计了 ha~ha~ (>_<) )
*/
@Slf4j
public class Logo {
//禁止实例化
private Logo() {
}
private static SoftReference<StringBuilder> START_LOGO = new SoftReference<>(
new StringBuilder("\033[34m")
.append("""
|==============================╔═══════════════════════════════════════╗==============================|
l e t ' s * * w ██████╗ ████████╗ ██████╗ w * b e c o m e
|==============================║ ██╔══██╗ ╚══██╔══╝ ██╔══██╗ ║==============================|
║ ██║ ██║ * ██║ * ██████╔╝ ║
|==============================║ ██║ ██║ ██║ ██╔═══╝ ║==============================|
b e t t e r * w ██████╔╝ * ██║ * ██║ w * * a n d * *
|==============================║ ╚═════╝ ╚═╝ ╚═╝ ║==============================|
║ dynamic high-performance ║
|==============================║ * thread pool * ║==============================|
b e t t e r * w written by yf w * —— @ y y f *
|==============================╚═══════════════════════════════════════╝==============================|
FASTER AND STABLER
""" )
.append("\033[0m")
);
public static final String LOG_LOGO = "\033[34mYF:D--T--P===>\033[0m";
public static String startLogo() {
StringBuilder logo = START_LOGO.get();
if(logo==null){
//清除引用
START_LOGO=null;
log.info(LOG_LOGO+"START_LOGO已经被清除,如果还有使用则被替换成了:"+LOG_LOGO);
return LOG_LOGO;
}
return logo.toString();
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/common/constant/Logo.java | Java | mit | 2,723 |
package com.yf.common.entity;
import lombok.Data;
/**
* @author yyf
* @description
*/
@Data
public class PoolInfo {
private String type;
private boolean useVirtualThread;//是否使用虚拟线程
private Integer coreNums;//核心线程数
private Integer maxNums;//最大线程数
private String poolName;//线程池名称
private String threadName;//线程名称
private boolean isDaemon;//是否守护线程
private boolean coreDestroy;//核心线程是否可销毁
private Integer aliveTime;//线程空闲时间
private String queueName;//队列名称
private String rejectStrategyName;//拒绝策略名称
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/common/entity/PoolInfo.java | Java | mit | 664 |
package com.yf.common.entity;
import lombok.Data;
/**
* @author yyf
* @date 2025/9/19 13:27
* @description
*/
@Data
public class QueueInfo {
// 是否分区化(如果是false,只需要读取capacity和queueName)
private boolean partitioning;
// 分区数量
private Integer partitionNum;
// 队列容量(null表示无界)
private Integer capacity;
// 队列名称
private String queueName;
// 入队策略
private String offerPolicy;
// 出队策略
private String pollPolicy;
// 移除策略
private String removePolicy;
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/common/entity/QueueInfo.java | Java | mit | 599 |
package com.yf.common.exception;
/**
* @author yyf
* @date 2025/10/6 0:09
* @description 用来解决队列切换不能被线程及时感知,线程无法及时切换队列的问题,抛出异常就是用来让线程感知到队列的切换
*/
public class SwitchedException extends RuntimeException{
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/common/exception/SwitchedException.java | Java | mit | 311 |
package com.yf.common.task;
import com.yf.core.partition.Partition;
import com.yf.core.threadpool.ThreadPool;
import lombok.Getter;
import lombok.Setter;
/**
* @author yyf
* @date 2025/10/6 15:34
* @description
*/
@Getter
@Setter
public abstract class GCTask implements Runnable{
ThreadPool threadPool;
Partition<?> partition;
public GCTask build(ThreadPool tp,Partition<?> partition){
setThreadPool(tp);
setPartition(partition);
return this;
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/common/task/GCTask.java | Java | mit | 493 |
package com.yf.common.task;
/**
* @author yyf
* @date 2025/10/5 14:11
* @description
*/
public interface Priority {
int getPriority();
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/common/task/Priority.java | Java | mit | 146 |
package com.yf.common.task;
import lombok.Getter;
import lombok.Setter;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
@Setter
@Getter
public class PriorityTask<V> extends FutureTask<V> implements Comparable<PriorityTask<V>>, Priority {
private int priority = 0;
public PriorityTask(Callable<V> callable, int priority) {
super(callable);
this.priority = priority;
}
public PriorityTask(Runnable runnable, int priority) {
// 无返回值时,result 传 null,且泛型固定为 Void
super(runnable, null);
this.priority = priority;
}
@Override
public int compareTo(PriorityTask<V> other) {
if (other == null) {
return -1;
}
return Integer.compare(other.getPriority(), this.getPriority());
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/common/task/PriorityTask.java | Java | mit | 838 |
package com.yf.common.task.impl;
import com.yf.common.task.GCTask;
import com.yf.core.threadpool.ThreadPool;
import com.yf.core.tp_regulator.UnifiedTPRegulator;
import com.yf.core.worker.Worker;
import java.util.Set;
/**
* @author yyf
* @date 2025/10/6 15:47
* @description
*/
public class TBPollCleaningTask extends GCTask {
@Override
public void run() {//队列切换后所做的事情:销毁所有线程
ThreadPool threadPool = getThreadPool();
Set<Worker> coreList = threadPool.getCoreList();
Set<Worker> extraList = threadPool.getExtraList();
UnifiedTPRegulator.destroyWorkers(threadPool.getName(),coreList.size(),extraList.size());
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/common/task/impl/TBPollCleaningTask.java | Java | mit | 696 |
package com.yf.core.partition.Impl;
import com.yf.common.exception.SwitchedException;
import com.yf.core.partition.Partition;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author yyf
* @date 2025/8/8 23:13
* @description 优化后的分区,性能接近LinkedBlockingQueue
*/
@Getter
@Setter
public class LinkedBlockingQ<T> extends Partition<T> {
@Data
static class Node <T>{
private T value;
private Node<T> next;
public Node(T value) {
this.value = value;
}
public Node() {
}
}
private final Lock headLock = new ReentrantLock(false);
private final Lock tailLock = new ReentrantLock(false);
private final Condition notEmpty = headLock.newCondition();
private Node<T> head = new Node<>();
private Node<T> tail = head;
private final AtomicInteger size = new AtomicInteger(0);
private Integer capacity;
private volatile boolean switched = false;//是否被切换的标记
public LinkedBlockingQ(Integer capacity) {
this.capacity = capacity;
}
public LinkedBlockingQ() {
}
/**
* 当队列有界且已满时返回false
*/
public boolean offer(T element) {
if (element == null) {
throw new NullPointerException("元素不能为null");
}
// 有界队列且已满时直接返回false
if (capacity != null && size.get() == capacity) {
return false;
}
final int c;
Node<T> newNode = new Node<>(element);
tailLock.lock();
try {
if(switched){
throw new SwitchedException();
}
// 再次检查容量,防止在获取锁前队列已被填满
if (size.get() == capacity)
return false;
enqueue(newNode);
c = size.getAndIncrement();
} finally {
tailLock.unlock();
}
// 如果队列之前为空,唤醒等待的消费者
if (c == 0) {
signalWaitForNotEmpty();
}
return true;
}
@Override
public T poll(Integer waitTime) throws InterruptedException {
T x = null;
final int c;
headLock.lock();
try {
if(switched){
throw new SwitchedException();
}
// 队列为空时等待
long nanos = 0;
while (size.get() == 0) {
if (waitTime == null) {
notEmpty.await();
} else {
if (nanos == 0) {
nanos = TimeUnit.MILLISECONDS.toNanos(waitTime);
if (nanos <= 0) {
return null;
}
}
nanos = notEmpty.awaitNanos(nanos);
if (nanos <= 0) {
return null;
}
}
}
x = dequeue();
c = size.getAndDecrement();
// 如果还有元素,唤醒其他可能等待的消费者
if (c > 1) {
notEmpty.signal();
}
} finally {
headLock.unlock();
}
return x;
}
@Override
public void lockGlobally() {
tailLock.lock();
headLock.lock();
}
@Override
public void unlockGlobally() {
tailLock.unlock();
headLock.unlock();
}
@Override
public void markAsSwitched() {
switched = true;
}
/**
* 从队列获取元素,支持超时
*/
public T removeEle() {
T ele = null;
// 无锁快速失败:空队列直接返回
if (size.get() == 0) {
return ele;
}
int c = -1;
headLock.lock();
try {
if(switched){
throw new SwitchedException();
}
if (size.get() > 0) {
ele = dequeue();// 复用poll中的节点删除逻辑
c = size.getAndDecrement();
// 队列仍有元素:唤醒下一个消费者
if (c > 1) {
notEmpty.signal();
}
} else {
return null;
}
} finally {
headLock.unlock();
}
return ele;
}
public int getEleNums() {
return size.get();
}
/**
* 将节点加入队列尾部
*/
private void enqueue(Node<T> node) {
tail.setNext(node);
tail = node;
}
/**
* 从队列头部移除节点
*/
private T dequeue() {
Node<T> h = head;
Node<T> first = h.getNext();
h.setNext(h); // 帮助垃圾回收
head = first;
T x = first.getValue();
first.setValue(null);
return x;
}
/**
* 唤醒等待非空条件的线程
*/
private void signalWaitForNotEmpty() {
headLock.lock();
try {
notEmpty.signal();
} finally {
headLock.unlock();
}
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/core/partition/Impl/LinkedBlockingQ.java | Java | mit | 5,392 |
package com.yf.core.partition.Impl;
import com.yf.common.exception.SwitchedException;
import com.yf.core.partition.Partition;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author yyf
* @date 2025/8/8 23:13
* @description 优化后的分区队列,出队操作使用CAS实现
*/
@Getter
@Setter
public class LinkedBlockingQS<T> extends Partition<T> {
@Data
static class Node <T>{
private volatile T value;
private volatile Node<T> next;
public Node(T value) {
this.value = value;
}
public Node() {
}
}
private final Lock tailLock = new ReentrantLock(false);
private final Lock headLock = new ReentrantLock(false);
private final Condition notEmpty = headLock.newCondition();
private final AtomicReference<Node<T>> head = new AtomicReference<>(new Node<>());
private volatile Node<T> tail = head.get();
private final AtomicInteger size = new AtomicInteger(0);
private Integer capacity;
private volatile boolean switched = false;
public LinkedBlockingQS(Integer capacity) {
this.capacity = capacity;
}
public LinkedBlockingQS() {
this.capacity = null;
}
/**
* 当队列有界且已满时返回false
* 教训:能直接返回明确的结果就直接返回,否则即使逻辑正确,也有可能由于各种奇葩的原因导致错误
* 例如下方我原本是将c设置为-1,在最后return c != -1,其实逻辑没问题,但是就是会出现问题。
*/
public boolean offer(T element) {
if (element == null) {
throw new NullPointerException("元素不能为null");
}
// 有界队列且已满时直接返回false
if (capacity != null && size.get() == capacity) {
return false;
}
final int c;
Node<T> newNode = new Node<>(element);
tailLock.lock();
try {
if(switched){
throw new SwitchedException();
}
// 再次检查容量,防止在获取锁前队列已被填满
if (size.get() == capacity)
return false;
enqueue(newNode);
c = size.getAndIncrement();
} finally {
tailLock.unlock();
}
// 如果队列之前为空,唤醒等待的消费者
if (c == 0) {
signalWaitForNotEmpty();
}
return true;
}
@Override
public T poll(Integer waitTime) throws InterruptedException {
if(switched){
throw new SwitchedException();
}
long nanos = waitTime != null ? TimeUnit.MILLISECONDS.toNanos(waitTime) : 0;
Node<T> h, first;
// 先尝试有限次CAS出队,减少锁竞争
h = head.get();
first = h.next;
if (first != null) {
// CAS替换头节点
if (head.compareAndSet(h, first)) {
T result = first.value;
first.value = null;
h.next = h;
int c = size.getAndDecrement();
// 还有元素时唤醒其他消费者
if (c > 1) {
signalWaitForNotEmpty();
}
return result;
}
}
// 队列空或CAS失败次数过多,进入锁等待逻辑
headLock.lock();
try {
if(switched){
throw new SwitchedException();
}
while (true) {
h = head.get();
first = h.next;
if (first != null) {
// 再次尝试CAS(此时竞争已减轻)
if (head.compareAndSet(h, first)) {
T result = first.value;
first.value = null;
h.next = h;
int c = size.getAndDecrement();
if (c > 1) {
notEmpty.signal(); // 唤醒其他等待线程
}
return result;
}
continue; // CAS失败,重新检查
}
// 队列为空,处理等待
if (waitTime != null) {
if (nanos <= 0) {
return null; // 超时返回
}
nanos = notEmpty.awaitNanos(nanos);
} else {
notEmpty.await(); // 无限等待
}
}
} finally {
headLock.unlock();
}
}
@Override
public void lockGlobally() {
tailLock.lock();
headLock.lock();
}
@Override
public void unlockGlobally() {
headLock.unlock();
tailLock.unlock();
}
@Override
public void setCapacity(Integer capacity) {
this.capacity = capacity;
}
@Override
public void markAsSwitched() {
switched = true;
}
public T removeEle() {
// 无锁快速失败:空队列直接返回
if (size.get() == 0) {
return null;
}
int c = -1;
// 使用CAS操作出队
Node<T> h, first;
do {
if(switched){
throw new SwitchedException();
}
h = head.get();
first = h.getNext();
// 如果没有元素,返回失败
if (first == null) {
return null;
}
} while (!head.compareAndSet(h, first));
first.setValue(null); // 帮助GC
// 注意:不再设置h.next = h,因为这会导致GC问题
c = size.getAndDecrement();
// 队列仍有元素:唤醒下一个消费者
if (c > 1) {
signalWaitForNotEmpty();
}
return first.getValue();
}
public int getEleNums() {
return size.get();
}
/**
* 将节点加入队列尾部
*/
private void enqueue(Node<T> node) {
tail.setNext(node);
tail = node;
}
/**
* 唤醒等待非空条件的线程
*/
private void signalWaitForNotEmpty() {
headLock.lock();
try {
notEmpty.signal();
} finally {
headLock.unlock();
}
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/core/partition/Impl/LinkedBlockingQS.java | Java | mit | 6,666 |
package com.yf.core.partition.Impl;
import com.yf.common.exception.SwitchedException;
import com.yf.core.partition.Partition;
import lombok.Getter;
import lombok.Setter;
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.*;
@Setter
@Getter
public class PriorityBlockingQ<T> extends Partition<T> {
private final Lock lock = new ReentrantLock( false);
private final Condition notEmpty = lock.newCondition(); // 仅用于出队等待
private volatile Integer capacity;
private final PriorityQueue<T> q;
private boolean switched = false;
public PriorityBlockingQ(Integer capacity) {
this.q = new PriorityQueue<>(capacity);
this.capacity = capacity;
}
public PriorityBlockingQ() {
this.q = new PriorityQueue<>();
}
/**
* 添加任务,将普通任务封装为优先级任务
*/
public boolean offer(T task) {
if (task == null) {
throw new NullPointerException("元素不能为null");
}
// 第一次检查容量(带锁的精确检查在内部)
if (capacity != null && getEleNums() >= capacity) {
return false;
}
lock.lock();
try {
if(switched){
throw new SwitchedException();
}
// 二次检查容量(锁内确保准确性)
if (capacity != null && q.size() >= capacity) {
return false;
}
boolean added = q.add(task);
notEmpty.signal(); // 唤醒等待出队的线程
return added;
} finally {
lock.unlock();
}
}
/**
* 阻塞获取任务(保留出队等待逻辑)
*/
@Override
public T poll(Integer waitTime) throws InterruptedException {
lock.lock();
try {
if(switched){
throw new SwitchedException();
}
while (q.isEmpty()) {
if (waitTime != null) {
// 限时等待
boolean await = notEmpty.await(waitTime, TimeUnit.MILLISECONDS);
if (!await) { // 超时
return null;
}
} else {
notEmpty.await(); // 无限等待
}
}
return q.poll(); // 获取并移除优先级最高的任务(队列头部)
} finally {
lock.unlock();
}
}
@Override
public T removeEle() {
lock.lock();
try{
if(switched){
throw new SwitchedException();
}
if(q.isEmpty()){
return null;
}else{
return q.remove();
}
} finally {
lock.unlock();
}
}
@Override
public int getEleNums() {
return q.size();
}
@Override
public void lockGlobally() {
lock.lock();
}
@Override
public void unlockGlobally() {
lock.unlock();
}
@Override
public void markAsSwitched() {
switched = true;
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/core/partition/Impl/PriorityBlockingQ.java | Java | mit | 3,226 |
package com.yf.core.partition;
import lombok.Getter;
import lombok.Setter;
/**
* @author yyf
* @description
*/
/**
* 实现类需要保证线程安全
*/
public abstract class Partition<T> {
/**
* 添加
*
* @param t@return
*/
public abstract boolean offer(T t);
/**
* 获取
* @return
*/
public abstract T poll(Integer waitTime) throws InterruptedException;
/**
* 移除任务(用于丢弃策略)
*/
public abstract T removeEle();
/**
* 获取任务数量
*/
public abstract int getEleNums();//获取任务数量,无锁
/**
* 获取全局锁
* @return
*/
public abstract void lockGlobally();
public abstract void unlockGlobally();
public abstract Integer getCapacity();
public abstract void setCapacity(Integer capacity);
/**
*这是用来保证队列在切换后的队列感知问题
* 标记为被切换
*/
public abstract void markAsSwitched();
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/core/partition/Partition.java | Java | mit | 1,019 |
package com.yf.core.partitioning;
import com.yf.core.partitioning.schedule_policy.OfferPolicy;
import com.yf.core.partitioning.schedule_policy.PollPolicy;
import com.yf.core.partitioning.schedule_policy.RemovePolicy;
import com.yf.core.partition.Partition;
/**
* @author yyf
* @date 2025/10/5 11:15
* @description 分区化队列的接口,用来判断队列是否为分区队列
*/
public interface Partitioning<E> {
Partition<E>[] getPartitions();
OfferPolicy getOfferPolicy();
PollPolicy getPollPolicy();
RemovePolicy getRemovePolicy();
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/core/partitioning/Partitioning.java | Java | mit | 566 |
package com.yf.core.partitioning.impl;
import com.yf.common.exception.SwitchedException;
import com.yf.core.partitioning.Partitioning;
import com.yf.core.resource_manager.PartiResourceManager;
import com.yf.core.partition.Impl.LinkedBlockingQ;
import com.yf.core.partitioning.schedule_policy.OfferPolicy;
import com.yf.core.partitioning.schedule_policy.PollPolicy;
import com.yf.core.partitioning.schedule_policy.RemovePolicy;
import com.yf.core.partitioning.schedule_policy.impl.offer_policy.RoundRobinOffer;
import com.yf.core.partitioning.schedule_policy.impl.poll_policy.RoundRobinPoll;
import com.yf.core.partitioning.schedule_policy.impl.remove_policy.RoundRobinRemove;
import com.yf.core.partition.Partition;
import lombok.Getter;
import lombok.Setter;
import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author yyf
* @date 2025/8/8 17:20
* @description
* 分区队列:多队列、细粒度、高性能
* 可选任务入队策略:轮询、随机、hash、填谷、优先级
* 可选任务出队策略:轮询、随机、削峰、线程绑定、优先级
* 可选移除任务策略:轮询、随机、削峰、优先级
*
* 《分区流-动态分区队列》
* 这是一款综合的分区队列:支持出入队调度策略执行后轮询,因而类名结尾为"Flow",当然也可以自行设置调度策略是否支持轮询,
* 其中线程绑定出队策略是默认不支持的,其他都是默认支持轮询
*/
@Setter
@Getter
public class PartiFlow<T> extends Partition<T> implements Partitioning<T> {
private Partition<T>[] partitions;
private OfferPolicy offerPolicy = new RoundRobinOffer();
private PollPolicy pollPolicy = new RoundRobinPoll();
private RemovePolicy removePolicy = new RoundRobinRemove();
private AtomicInteger offerRound = new AtomicInteger(0);
private AtomicInteger pollRound = new AtomicInteger(0);
private AtomicInteger removeRound = new AtomicInteger(0);
private volatile Integer capacity;
private Integer DEFAULT_PARTITION_NUM = 5;
private static final Integer DEFAULT_WAIT_TIME = 100;
public PartiFlow(Integer partitionNum, Integer capacity, String QName, OfferPolicy offerPolicy, PollPolicy pollPolicy, RemovePolicy removePolicy) {
this(partitionNum, capacity,QName);
this.offerPolicy = offerPolicy;
this.pollPolicy = pollPolicy;
this.removePolicy = removePolicy;
}
public PartiFlow(Integer partitionNum, Integer capacity,String QName) {
//先获取队列类型
Class<?> qClass = PartiResourceManager.getResources().get(QName);
partitions = new Partition[partitionNum];
this.capacity = capacity;
if (capacity != null) {//不为null,轮询分配
final int baseCapacity = capacity / partitionNum;
final int remainder = capacity % partitionNum;
for (int i = 0; i < partitionNum; i++) {
int partitionCapacity = baseCapacity + (i < remainder ? 1 : 0);
try {
partitions[i] = (Partition<T>) qClass.getConstructor().newInstance();
partitions[i].setCapacity(partitionCapacity);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
} else {//为null,都为无界队列
for (int i = 0; i < partitionNum; i++) {
try {
partitions[i] = (Partition<T>) qClass.getConstructor().newInstance();
partitions[i].setCapacity(null);
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
}
}
public PartiFlow() {
partitions = new Partition[DEFAULT_PARTITION_NUM];
for (int i = 0; i < DEFAULT_PARTITION_NUM; i++) {
partitions[i] = new LinkedBlockingQ<>();
}
}
public boolean offer(T element) {
try {
if (!offerPolicy.getRoundRobin()) {//不轮询
return partitions[offerPolicy.selectPartition(partitions, element)].offer(element);
}
//轮询
int index = offerPolicy.selectPartition(partitions, element);
Boolean suc = false;
for (int i = 0; i < partitions.length && !suc; i++) {
suc = partitions[index].offer(element);
index = (index + 1) % partitions.length;
}
return suc;
} catch (SwitchedException e) {
return false;
}
}
@Override
public T poll(Integer waitTime) throws InterruptedException {
try {
if (!pollPolicy.getRoundRobin()) {//不轮询
return partitions[pollPolicy.selectPartition(partitions)].poll(waitTime);
}
//轮询
T element = null;
int partitionIndex = pollPolicy.selectPartition(partitions);
if (waitTime == null) {//说明无限等待
int emptyCount = 0;
while (element == null) {
element = partitions[partitionIndex].poll(DEFAULT_WAIT_TIME);
if (element == null) {
emptyCount++;
//所有分区为空count清零
if (emptyCount >= partitions.length) {
emptyCount = 0;
}
}
partitionIndex = (partitionIndex + 1) % partitions.length;
}
return element;
} else {//说明有等待时间
for (int i = 0; i < partitions.length && element == null; i++) {
element = partitions[partitionIndex].poll(waitTime / partitions.length);
partitionIndex = (partitionIndex + 1) % partitions.length;
}
return element;
}
} catch (SwitchedException e) {
return null;
}
}
@Override
public T removeEle() {
try {
return partitions[removePolicy.selectPartition(partitions)].removeEle();
} catch (SwitchedException e) {
return null;
}
}
@Override
public int getEleNums() {
int sum = 0;
for (Partition partition : partitions) {
sum += partition.getEleNums();
}
return sum;
}
public void lockGlobally(){
for(Partition partition : partitions) {
partition.lockGlobally();
}
}
public void unlockGlobally(){
for(Partition partition : partitions) {
partition.unlockGlobally();
}
}
@Override
public void markAsSwitched() {
for(Partition partition : partitions) {
partition.markAsSwitched();
}
}
public void setCapacity(Integer capacity) {
if(partitions==null){
throw new RuntimeException("还未初始化各个分区!");
}
int rest = capacity % partitions.length;
capacity/=partitions.length;
for(int i=0;i<partitions.length;i++){
partitions[i].setCapacity(capacity+ (i<rest?1:0));
}
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/core/partitioning/impl/PartiFlow.java | Java | mit | 7,959 |
package com.yf.core.partitioning.impl;
import com.yf.common.exception.SwitchedException;
import com.yf.core.partition.Impl.LinkedBlockingQ;
import com.yf.core.partitioning.Partitioning;
import com.yf.core.partitioning.schedule_policy.OfferPolicy;
import com.yf.core.partitioning.schedule_policy.PollPolicy;
import com.yf.core.partitioning.schedule_policy.RemovePolicy;
import com.yf.core.partitioning.schedule_policy.impl.offer_policy.RoundRobinOffer;
import com.yf.core.partitioning.schedule_policy.impl.poll_policy.RoundRobinPoll;
import com.yf.core.partitioning.schedule_policy.impl.remove_policy.RoundRobinRemove;
import com.yf.core.partition.Partition;
import com.yf.core.resource_manager.PartiResourceManager;
import lombok.Getter;
import lombok.Setter;
import java.lang.reflect.InvocationTargetException;
/**
* @author yyf
* @date 2025/9/23 16:02
* @description
*
*《静态分区队列》
* 这是一款不支持调度规则执行后轮询的分区队列,无论调度策略是否设置支持轮询都没用,因而结尾为Still,代表着静态
* 也正是由于这个特性,他的性能会比PartiFlow更好一些。
*/
@Getter
@Setter
public class PartiStill<T> extends Partition<T> implements Partitioning<T> {
private Partition<T>[] partitions;
private OfferPolicy offerPolicy = new RoundRobinOffer();
private PollPolicy pollPolicy = new RoundRobinPoll();
private RemovePolicy removePolicy = new RoundRobinRemove();
private volatile Integer capacity;
private Integer DEFAULT_PARTITION_NUM = 5;
public PartiStill(Integer partitionNum, Integer capacity, String QName, OfferPolicy offerPolicy, PollPolicy pollPolicy, RemovePolicy removePolicy) {
this(partitionNum, capacity,QName);
this.offerPolicy = offerPolicy;
this.pollPolicy = pollPolicy;
this.removePolicy = removePolicy;
}
public PartiStill(Integer partitionNum, Integer capacity, String QName) {
//先获取队列类型
Class<?> qClass = PartiResourceManager.getResources().get(QName);
partitions = new Partition[partitionNum];
this.capacity = capacity;
if (capacity != null) {//不为null,轮询分配容量
final int baseCapacity = capacity / partitionNum;
final int remainder = capacity % partitionNum;
for (int i = 0; i < partitionNum; i++) {
int partitionCapacity = baseCapacity + (i < remainder ? 1 : 0);
try {
partitions[i] = (Partition<T>) qClass.getConstructor().newInstance();
partitions[i].setCapacity(partitionCapacity);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
} else {//为null,都为无界队列
for (int i = 0; i < partitionNum; i++) {
try {
partitions[i] = (Partition<T>) qClass.getConstructor().newInstance();
partitions[i].setCapacity(null);
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
}
}
public PartiStill() {
partitions = new Partition[DEFAULT_PARTITION_NUM];
for (int i = 0; i < DEFAULT_PARTITION_NUM; i++) {
partitions[i] = new LinkedBlockingQ<>();
}
}
public boolean offer(T element) {
try {
return partitions[offerPolicy.selectPartition(partitions, element)].offer(element);
} catch (SwitchedException e) {
return false;
}
}
@Override
public T poll(Integer waitTime) throws InterruptedException {
try {
return partitions[pollPolicy.selectPartition(partitions)].poll(waitTime);
} catch (SwitchedException e) {
return null;
}
}
@Override
public T removeEle() {
try {
return partitions[removePolicy.selectPartition(partitions)].removeEle();
} catch (SwitchedException e) {
return null;
}
}
@Override
public int getEleNums() {
int sum = 0;
for (Partition partition : partitions) {
sum += partition.getEleNums();
}
return sum;
}
public void lockGlobally(){
for(Partition partition : partitions) {
partition.lockGlobally();
}
}
public void unlockGlobally(){
for(Partition partition : partitions) {
partition.unlockGlobally();
}
}
@Override
public void markAsSwitched() {
for(Partition partition : partitions) {
partition.markAsSwitched();
}
}
public void setCapacity(Integer capacity) {
if(partitions==null){
throw new RuntimeException("还未初始化各个分区!");
}
int rest = capacity % partitions.length;
capacity/=partitions.length;
for(int i=0;i<partitions.length;i++){
partitions[i].setCapacity(capacity+ (i<rest?1:0));
}
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/core/partitioning/impl/PartiStill.java | Java | mit | 5,745 |
package com.yf.core.partitioning.schedule_policy;
import com.yf.core.partition.Partition;
/**
* @author yyf
* @date 2025/9/20 21:04
* @description
*/
public abstract class OfferPolicy implements SchedulePolicy{
/**
* 选择分区
* @param partitions:分区数组
* @param object:元素
* @return 分区索引
*/
public abstract int selectPartition(Partition[] partitions, Object object);
/**
* 获取是否轮询
* @return
*/
public abstract boolean getRoundRobin();
/**
* 设置是否轮询
* @param roundRobin
*/
public abstract void setRoundRobin(boolean roundRobin);
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/core/partitioning/schedule_policy/OfferPolicy.java | Java | mit | 662 |
package com.yf.core.partitioning.schedule_policy;
import com.yf.core.partition.Partition;
/**
* @author yyf
* @date 2025/9/20 21:19
* @description
*/
public abstract class PollPolicy implements SchedulePolicy{
public int selectPartition(Partition[] partitions,Object o){
return selectPartition(partitions);
}
public abstract int selectPartition(Partition[] partitions);
public abstract boolean getRoundRobin();
public abstract void setRoundRobin(boolean roundRobin);
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/core/partitioning/schedule_policy/PollPolicy.java | Java | mit | 503 |
package com.yf.core.partitioning.schedule_policy;
import com.yf.core.partition.Partition;
/**
* @author yyf
* @date 2025/9/20 21:24
* @description
*/
public abstract class RemovePolicy implements SchedulePolicy{
public int selectPartition(Partition[] partitions){
return selectPartition(partitions,null);
}
public abstract int selectPartition(Partition[] partitions,Object o);
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/core/partitioning/schedule_policy/RemovePolicy.java | Java | mit | 405 |
package com.yf.core.partitioning.schedule_policy;
import com.yf.core.partition.Partition;
/**
* @author yyf
* @date 2025/10/6 14:12
* @description 调度规则的顶级接口,由于分区队列需要调度规则选择分区,而大部分调度规则会运用到取余这一计算,所以为了保证性能,
* 建议分区数量为2的幂次数,这样取余运算性能会高一些。
*/
public interface SchedulePolicy {
int selectPartition(Partition[] partitions,Object o);
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/core/partitioning/schedule_policy/SchedulePolicy.java | Java | mit | 494 |
package com.yf.core.partitioning.schedule_policy.impl.offer_policy;
import com.yf.core.partitioning.schedule_policy.OfferPolicy;
import com.yf.core.partition.Partition;
/**
* @author yyf
* @date 2025/10/4 22:11
* @description 借鉴了hashmap的hash计算逻辑,优化了哈希分布,以减少hash冲突
*/
public class BalancedHashOffer extends OfferPolicy {
private volatile boolean roundRobin = false;
@Override
public int selectPartition(Partition[] partitions, Object element) {
int ps = partitions.length;
int h = hash(element);
if ((ps & (ps - 1)) == 0) {
// 分区数量为2的幂时,用&运算
return h & (ps - 1);
} else {
return (h & 0x7FFFFFFF) % ps;
}
}
/**
* 哈希搅动方法:混合高低位信息,优化哈希分布
*/
private int hash(Object element) {
if (element == null) {
return 0;
}
int h = element.hashCode();
// 核心搅动:高16位与低16位异或,混合高低位信息
h ^= h >>> 16;
return h;
}
@Override
public boolean getRoundRobin() {
return roundRobin;
}
@Override
public void setRoundRobin(boolean roundRobin) {
this.roundRobin = roundRobin;
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/core/partitioning/schedule_policy/impl/offer_policy/BalancedHashOffer.java | Java | mit | 1,319 |
package com.yf.core.partitioning.schedule_policy.impl.offer_policy;
import com.yf.core.partitioning.schedule_policy.OfferPolicy;
import com.yf.core.partition.Partition;
/**
* @author yyf
* @date 2025/9/21 0:00
* @description
*/
public class PlainHashOffer extends OfferPolicy {
private volatile boolean roundRobin = true;
@Override
public int selectPartition(Partition[] partitions, Object element) {
int ps = partitions.length;
int h = element.hashCode();
if ((ps & (ps - 1)) == 0) {
// 分区数量为2的幂时,用&运算
return h & (ps - 1);
} else {
// 处理负数:通过 & 0x7FFFFFFF 清除符号位(保证结果为非负)
return (h & 0x7FFFFFFF) % ps;
}
}
@Override
public boolean getRoundRobin() {
return roundRobin;
}
@Override
public void setRoundRobin(boolean roundRobin) {
this.roundRobin = roundRobin;
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/core/partitioning/schedule_policy/impl/offer_policy/PlainHashOffer.java | Java | mit | 981 |
package com.yf.core.partitioning.schedule_policy.impl.offer_policy;
import com.yf.common.task.Priority;
import com.yf.core.partition.Partition;
import com.yf.core.partitioning.schedule_policy.OfferPolicy;
/**
* @author yyf
* @date 2025/10/5 13:50
* @description 优先级调度规则:先使用优先级调度,如果非优先级实例或者优先级不和理则降级为轮询
*/
public class PriorityOffer extends OfferPolicy {
private boolean roundRobin = true;
private volatile RoundRobinOffer roundRobinOffer;
@Override
public int selectPartition(Partition[] partitions, Object object) {
if(object instanceof Priority){
int priority = ((Priority) object).getPriority();
for(;priority<partitions.length;priority++){
if(partitions[priority].getEleNums()<partitions[priority].getCapacity()){
return priority;
}
}
}
//如果并非优先级实例则降级为轮询(double check的饿汉型单例模式)
if(roundRobinOffer==null) {
synchronized (this) {
if (roundRobinOffer == null) {
roundRobinOffer = new RoundRobinOffer();
}
}
}
return roundRobinOffer.selectPartition(partitions,object);
}
@Override
public boolean getRoundRobin() {
return roundRobin;
}
@Override
public void setRoundRobin(boolean roundRobin) {
this.roundRobin = roundRobin;
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/core/partitioning/schedule_policy/impl/offer_policy/PriorityOffer.java | Java | mit | 1,536 |
package com.yf.core.partitioning.schedule_policy.impl.offer_policy;
import com.yf.core.partitioning.schedule_policy.OfferPolicy;
import com.yf.core.partition.Partition;
/**
* @author yyf
* @date 2025/9/20 23:49
* @description
*/
public class RandomOffer extends OfferPolicy {
private volatile boolean roundRobin = true;
@Override
public int selectPartition(Partition[] partitions, Object object) {
return (int) (Math.random() * partitions.length);
}
@Override
public boolean getRoundRobin() {
return roundRobin;
}
@Override
public void setRoundRobin(boolean roundRobin) {
this.roundRobin = roundRobin;
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/core/partitioning/schedule_policy/impl/offer_policy/RandomOffer.java | Java | mit | 679 |
package com.yf.core.partitioning.schedule_policy.impl.offer_policy;
import com.yf.core.partitioning.schedule_policy.OfferPolicy;
import com.yf.core.partition.Partition;
import java.util.concurrent.atomic.AtomicLong;
/**
* @author yyf
* @date 2025/9/20 23:47
* @description
*/
public class RoundRobinOffer extends OfferPolicy {
private volatile boolean roundRobin = true;
final AtomicLong round = new AtomicLong(0);
@Override
public int selectPartition(Partition[] partitions, Object object) {
int ps = partitions.length;
int r = (int)round.getAndIncrement()%partitions.length;
if ((ps & (ps - 1)) == 0) {
// 分区数量为2的幂时,用&运算
return r & (ps - 1);
} else {
return r % ps;
}
}
@Override
public boolean getRoundRobin() {
return roundRobin;
}
@Override
public void setRoundRobin(boolean roundRobin) {
this.roundRobin = roundRobin;
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/core/partitioning/schedule_policy/impl/offer_policy/RoundRobinOffer.java | Java | mit | 999 |
package com.yf.core.partitioning.schedule_policy.impl.offer_policy;
import com.yf.core.partitioning.schedule_policy.OfferPolicy;
import com.yf.core.partition.Partition;
/**
* @author yyf
* @date 2025/9/21 0:02
* @description
*/
public class ValleyFillingOffer extends OfferPolicy {
private volatile boolean roundRobin = true;
@Override
public int selectPartition(Partition[] partitions,Object object) {
int minIndex = 0;
for(int i = 0; i < partitions.length; i++){
if(partitions[i].getEleNums() < partitions[minIndex].getEleNums()){
minIndex = i;
}
}
return minIndex;
}
@Override
public boolean getRoundRobin() {
return roundRobin;
}
@Override
public void setRoundRobin(boolean roundRobin) {
this.roundRobin = roundRobin;
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/core/partitioning/schedule_policy/impl/offer_policy/ValleyFillingOffer.java | Java | mit | 863 |
package com.yf.core.partitioning.schedule_policy.impl.poll_policy;
import com.yf.core.partitioning.schedule_policy.PollPolicy;
import com.yf.core.partition.Partition;
/**
* @author yyf
* @date 2025/9/21 0:07
* @description
*/
public class PeekShavingPoll extends PollPolicy {
private volatile boolean roundRobin = true;
@Override
public int selectPartition(Partition[] partitions) {
int maxIndex = 0;
for(int i = 0; i < partitions.length; i++){
if(partitions[i].getEleNums() > partitions[maxIndex].getEleNums()){
maxIndex = i;
}
}
return maxIndex;
}
@Override
public boolean getRoundRobin() {
return roundRobin;
}
@Override
public void setRoundRobin(boolean roundRobin) {
this.roundRobin = roundRobin;
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/core/partitioning/schedule_policy/impl/poll_policy/PeekShavingPoll.java | Java | mit | 843 |
package com.yf.core.partitioning.schedule_policy.impl.poll_policy;
import com.yf.core.partition.Partition;
import com.yf.core.partitioning.schedule_policy.PollPolicy;
/**
* @author yyf
* @date 2025/10/5 14:03
* @description
*/
public class PriorityPoll extends PollPolicy {
private boolean roundRobin = true;
private volatile RoundRobinPoll roundRobinPoll;
@Override
public int selectPartition(Partition[] partitions) {
for(int i =0;i<partitions.length;i++){
if(partitions[i].getEleNums()>0){
return i;
}
}
if(roundRobinPoll==null) {
synchronized (this) {
if (roundRobinPoll == null) {
roundRobinPoll = new RoundRobinPoll();
}
}
}
return roundRobinPoll.selectPartition(partitions);
}
@Override
public boolean getRoundRobin() {
return roundRobin;
}
@Override
public void setRoundRobin(boolean roundRobin) {
this.roundRobin = roundRobin;
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/core/partitioning/schedule_policy/impl/poll_policy/PriorityPoll.java | Java | mit | 1,064 |
package com.yf.core.partitioning.schedule_policy.impl.poll_policy;
import com.yf.core.partitioning.schedule_policy.PollPolicy;
import com.yf.core.partition.Partition;
/**
* @author yyf
* @date 2025/9/21 0:06
* @description
*/
public class RandomPoll extends PollPolicy {
private volatile boolean roundRobin = true;
@Override
public int selectPartition(Partition[] partitions) {
return (int) (Math.random() * partitions.length);
}
@Override
public boolean getRoundRobin() {
return roundRobin;
}
@Override
public void setRoundRobin(boolean roundRobin) {
this.roundRobin = roundRobin;
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/core/partitioning/schedule_policy/impl/poll_policy/RandomPoll.java | Java | mit | 659 |
package com.yf.core.partitioning.schedule_policy.impl.poll_policy;
import com.yf.core.partitioning.schedule_policy.PollPolicy;
import com.yf.core.partition.Partition;
import java.util.concurrent.atomic.AtomicLong;
/**
* @author yyf
* @date 2025/9/21 0:05
* @description
*/
public class RoundRobinPoll extends PollPolicy {
private volatile boolean roundRobin = true;
final AtomicLong round = new AtomicLong(0);
@Override
public int selectPartition(Partition[] partitions) {
int ps = partitions.length;
int r = (int)round.getAndIncrement()%partitions.length;
if ((ps & (ps - 1)) == 0) {
// 分区数量为2的幂时,用&运算
return r & (ps - 1);
} else {
return r % ps;
}
}
@Override
public boolean getRoundRobin() {
return roundRobin;
}
@Override
public void setRoundRobin(boolean roundRobin) {
this.roundRobin = roundRobin;
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/core/partitioning/schedule_policy/impl/poll_policy/RoundRobinPoll.java | Java | mit | 979 |
package com.yf.core.partitioning.schedule_policy.impl.poll_policy;
import com.yf.core.partitioning.schedule_policy.PollPolicy;
import com.yf.core.partition.Partition;
import java.util.concurrent.atomic.AtomicLong;
/**
* @author yyf
* @date 2025/9/21 0:08
* @description 线程绑定策略,使得每个线程能够固定消费各自的分区,所以默认关闭轮询
*/
public class ThreadBindingPoll extends PollPolicy {
private volatile boolean roundRobin = false;
final AtomicLong round = new AtomicLong(0);
private final ThreadLocal<Integer> threadLocal = new ThreadLocal<>();
@Override
public int selectPartition(Partition[] partitions) {
if(threadLocal.get()==null){
threadLocal.set((int)round.getAndIncrement()%partitions.length);
}
return threadLocal.get();
}
@Override
public boolean getRoundRobin() {
return roundRobin;
}
@Override
public void setRoundRobin(boolean roundRobin) {
this.roundRobin = roundRobin;
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/core/partitioning/schedule_policy/impl/poll_policy/ThreadBindingPoll.java | Java | mit | 1,039 |
package com.yf.core.partitioning.schedule_policy.impl.remove_policy;
import com.yf.core.partitioning.schedule_policy.RemovePolicy;
import com.yf.core.partition.Partition;
/**
* @author yyf
* @date 2025/9/21 0:07
* @description
*/
public class PeekShavingRemove extends RemovePolicy {
@Override
public int selectPartition(Partition[] partitions,Object o) {
int maxIndex = 0;
for (int i = 0; i < partitions.length; i++) {
if (partitions[i].getEleNums() > partitions[maxIndex].getEleNums()) {
maxIndex = i;
}
}
return maxIndex;
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/core/partitioning/schedule_policy/impl/remove_policy/PeekShavingRemove.java | Java | mit | 620 |
package com.yf.core.partitioning.schedule_policy.impl.remove_policy;
import com.yf.core.partition.Partition;
import com.yf.core.partitioning.schedule_policy.RemovePolicy;
/**
* @author yyf
* @date 2025/10/5 14:06
* @description
*/
public class PriorityRemove extends RemovePolicy {
@Override
public int selectPartition(Partition[] partitions,Object o) {
for(int i = partitions.length-1; i >=0; i--){
if(partitions[i].getEleNums()>0){
return i;
}
}
return partitions.length-1;
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/core/partitioning/schedule_policy/impl/remove_policy/PriorityRemove.java | Java | mit | 562 |
package com.yf.core.partitioning.schedule_policy.impl.remove_policy;
import com.yf.core.partitioning.schedule_policy.RemovePolicy;
import com.yf.core.partition.Partition;
/**
* @author yyf
* @date 2025/9/21 0:06
* @description
*/
public class RandomRemove extends RemovePolicy {
@Override
public int selectPartition(Partition[] partitions,Object o) {
return (int) (Math.random() * partitions.length);
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/core/partitioning/schedule_policy/impl/remove_policy/RandomRemove.java | Java | mit | 432 |
package com.yf.core.partitioning.schedule_policy.impl.remove_policy;
import com.yf.core.partitioning.schedule_policy.RemovePolicy;
import com.yf.core.partition.Partition;
import java.util.concurrent.atomic.AtomicLong;
/**
* @author yyf
* @date 2025/9/21 0:05
* @description
*/
public class RoundRobinRemove extends RemovePolicy {
final AtomicLong round = new AtomicLong(0);
@Override
public int selectPartition(Partition[] partitions,Object o) {
int ps = partitions.length;
int r = (int)round.getAndIncrement()%partitions.length;
if ((ps & (ps - 1)) == 0) {
// 分区数量为2的幂时,用&运算
return r & (ps - 1);
} else {
return r % ps;
}
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/core/partitioning/schedule_policy/impl/remove_policy/RoundRobinRemove.java | Java | mit | 751 |
package com.yf.core.rejectstrategy;
import com.yf.core.threadpool.ThreadPool;
/**
* @author yyf
* @description
*/
public abstract class RejectStrategy {
public abstract void reject (ThreadPool threadPool,Runnable task);//处理普通任务的
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/core/rejectstrategy/RejectStrategy.java | Java | mit | 259 |
package com.yf.core.rejectstrategy.impl;
import com.yf.common.constant.Logo;
import com.yf.core.rejectstrategy.RejectStrategy;
import com.yf.core.threadpool.ThreadPool;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.RejectedExecutionException;
/**
* @author yyf
* @date 2025/10/1 14:20
* @description
*/
@Slf4j
public class AbortStrategy extends RejectStrategy {
@Override
public void reject(ThreadPool threadPool, Runnable task) {
throw new RejectedExecutionException(Logo.LOG_LOGO +"任务被拒绝:" + task);
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/core/rejectstrategy/impl/AbortStrategy.java | Java | mit | 560 |
package com.yf.core.rejectstrategy.impl;
import com.yf.core.rejectstrategy.RejectStrategy;
import com.yf.core.threadpool.ThreadPool;
/**
* @author yyf
* @description
*/
public class CallerRunsStrategy extends RejectStrategy {
@Override
public void reject(ThreadPool threadPool,Runnable task) {
task.run();
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/core/rejectstrategy/impl/CallerRunsStrategy.java | Java | mit | 335 |
package com.yf.core.rejectstrategy.impl;
import com.yf.core.rejectstrategy.RejectStrategy;
import com.yf.core.threadpool.ThreadPool;
import java.util.concurrent.FutureTask;
/**
* @author yyf
* @date 2025/8/2 23:13
* @description 丢弃最老的任务或者丢弃优先级最小的任务(由队列的remove方法决定)
*/
public class DiscardOldestStrategy extends RejectStrategy {
@Override
public void reject(ThreadPool threadPool,Runnable task) {
Runnable runnable = threadPool.getPartition().removeEle();
if(runnable instanceof FutureTask){
((FutureTask<?>) runnable).cancel(false);
}
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/core/rejectstrategy/impl/DiscardOldestStrategy.java | Java | mit | 653 |
package com.yf.core.rejectstrategy.impl;
import com.yf.core.rejectstrategy.RejectStrategy;
import com.yf.core.threadpool.ThreadPool;
import java.util.concurrent.FutureTask;
/**
* @author yyf
* @date 2025/8/2 23:24
* @description
*/
public class DiscardStrategy extends RejectStrategy {
@Override
public void reject(ThreadPool threadPool,Runnable task) {
if(task instanceof FutureTask){
((FutureTask<?>) task).cancel(true);
}
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/core/rejectstrategy/impl/DiscardStrategy.java | Java | mit | 478 |
package com.yf.core.resource_manager;
import com.yf.common.constant.Constant;
import com.yf.common.task.GCTask;
import com.yf.common.task.impl.TBPollCleaningTask;
import com.yf.core.partition.Impl.LinkedBlockingQ;
import com.yf.core.partition.Partition;
import com.yf.core.partitioning.Partitioning;
import com.yf.core.partitioning.schedule_policy.SchedulePolicy;
import com.yf.core.partitioning.schedule_policy.impl.poll_policy.ThreadBindingPoll;
import com.yf.core.rejectstrategy.impl.CallerRunsStrategy;
import com.yf.core.threadpool.ThreadPool;
import com.yf.core.workerfactory.WorkerFactory;
import lombok.extern.slf4j.Slf4j;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
/**
* @author yyf
* @date 2025/10/6 14:57
* @description 用来垃圾清理的以及异步操作的小线程池
*
* 虽然在利用了全局锁+标记+抛出异常三个步骤能解决大部分问题,但是依旧可能存在一部分无法优雅解决的问题,例如:
* 1 ThreadBinding策略的ThreadLocal对应的value无法被正确回收,会造成内存泄漏问题。(也有其他解决方案,只是这种更加的具有扩展性)
* 2 倘若有入队队列用无锁操作,那么就会出现旧队列元素残留问题,用这种方式能够最大限度的解决(不能说100%)
*/
@Slf4j
public class GCTaskManager {
private static volatile ThreadPool littleChief;
private final static Map<Class<? extends SchedulePolicy>,Class<? extends GCTask>> SCHEDULE_TASK_MAP = new HashMap<>();
private final static Map<Class<? extends Partition<?>>,Class<? extends GCTask>> PARTI_TASK_MAP = new HashMap<>();
static {
register(ThreadBindingPoll.class, TBPollCleaningTask.class);
}
public static void register(Class resourceClazz, Class<? extends GCTask> taskClass){
if(resourceClazz.getSuperclass() == SchedulePolicy.class) {
SCHEDULE_TASK_MAP.put(resourceClazz, taskClass);
}
if(resourceClazz.getSuperclass() == Partition.class){
PARTI_TASK_MAP.put(resourceClazz, taskClass);
}
}
public static void clean(ThreadPool tp, Partition<?> oldPartition) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
if(oldPartition instanceof Partitioning<?>){//调度规则相关的清理策略
//获取清理任务
GCTask offerTask = SCHEDULE_TASK_MAP.get(((Partitioning<?>) oldPartition).getOfferPolicy().getClass())
.getConstructor(ThreadPool.class).newInstance().build (tp, oldPartition);
GCTask pollTask = SCHEDULE_TASK_MAP.get(((Partitioning<?>) oldPartition).getPollPolicy().getClass())
.getConstructor(ThreadPool.class).newInstance().build(tp, oldPartition);
GCTask removeTask = SCHEDULE_TASK_MAP.get(((Partitioning<?>) oldPartition).getRemovePolicy().getClass())
.getConstructor(ThreadPool.class).newInstance().build(tp, oldPartition);
//执行
execute(offerTask);
execute(pollTask);
execute(removeTask);
GCTask task = PARTI_TASK_MAP.get(((Partitioning<?>) oldPartition).getPartitions()[0].getClass())
.getConstructor(ThreadPool.class).newInstance().build(tp, oldPartition);
execute(task);
}else{//分区相关的清理策略
GCTask task = PARTI_TASK_MAP.get(oldPartition.getClass())
.getConstructor(ThreadPool.class).newInstance().build(tp, oldPartition);
execute(task);
}
}
public static void execute(Runnable task){
if(task == null){
return;
}
if (littleChief == null) {
synchronized (GCTaskManager.class) {
if (littleChief == null) {
littleChief = new ThreadPool(
Constant.LITTLE_CHIEF,
5,
10,
Constant.LITTLE_CHIEF,
new WorkerFactory("", false, true, 10),
new LinkedBlockingQ<Runnable>(50),
new CallerRunsStrategy()
);
}
}
}
littleChief.execute(task);
}
public static synchronized void setLittleChief(ThreadPool tp) {
if(littleChief!=null) return;
littleChief = tp;
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/core/resource_manager/GCTaskManager.java | Java | mit | 4,531 |
package com.yf.core.resource_manager;
import com.yf.core.partition.Impl.LinkedBlockingQ;
import com.yf.core.partition.Impl.LinkedBlockingQS;
import com.yf.core.partition.Impl.PriorityBlockingQ;
import com.yf.core.partition.Partition;
import java.util.HashMap;
import java.util.Map;
/**
* @author yyf
* @description: 分区资源管理器(PartitionResourceManager)
*/
public class PartiResourceManager {
public final static String LINKED = "linked";//单链表
public final static String PRIORITY = "priority";//优先级队列
public final static String LINKED_S = "linkedS";//cas队列
private final static Map<String, Class<? extends Partition>> TASK_QUEUE_MAP = new HashMap<>();
static {
register(LINKED, LinkedBlockingQ.class);
register(PRIORITY, PriorityBlockingQ.class);
register(LINKED_S, LinkedBlockingQS.class);
}
public static void register(String name, Class<? extends Partition> clazz) {
TASK_QUEUE_MAP.put(name, clazz);
}
public static Class<? extends Partition> getResource(String name) {
return TASK_QUEUE_MAP.get(name);
}
public static Map<String,Class<? extends Partition>> getResources(){
return TASK_QUEUE_MAP;
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/core/resource_manager/PartiResourceManager.java | Java | mit | 1,240 |
package com.yf.core.resource_manager;
import com.yf.core.rejectstrategy.RejectStrategy;
import com.yf.core.rejectstrategy.impl.CallerRunsStrategy;
import com.yf.core.rejectstrategy.impl.DiscardOldestStrategy;
import com.yf.core.rejectstrategy.impl.DiscardStrategy;
import java.util.HashMap;
import java.util.Map;
/**
* @author yyf
* @description : 拒绝策略资源管理器(RejectStrategyResourceManager)
*/
public class RSResourceManager {
public final static String CALLER_RUNS = "callerRuns";//调用当前线程运行
public final static String DISCARD_OLDEST = "discardOldest";//丢弃最老的
public final static String DISCARD = "discard";//直接丢弃
public static final Map<String, Class<? extends RejectStrategy>> REJECT_STRATEGY_MAP = new HashMap<>();
static {
register(CALLER_RUNS, CallerRunsStrategy.class);
register(DISCARD_OLDEST, DiscardOldestStrategy.class);
register(DISCARD, DiscardStrategy.class);
}
public static void register(String rejectStrategyName, Class<? extends RejectStrategy> rejectStrategyClass) {
REJECT_STRATEGY_MAP.put(rejectStrategyName, rejectStrategyClass);
}
public static Class<? extends RejectStrategy> getResource(String name) {
return REJECT_STRATEGY_MAP.get(name);
}
public static Map<String,Class<? extends RejectStrategy>> getResources(){
return REJECT_STRATEGY_MAP;
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/core/resource_manager/RSResourceManager.java | Java | mit | 1,428 |
package com.yf.core.resource_manager;
import com.yf.core.partitioning.schedule_policy.OfferPolicy;
import com.yf.core.partitioning.schedule_policy.PollPolicy;
import com.yf.core.partitioning.schedule_policy.RemovePolicy;
import com.yf.core.partitioning.schedule_policy.SchedulePolicy;
import com.yf.core.partitioning.schedule_policy.impl.offer_policy.*;
import com.yf.core.partitioning.schedule_policy.impl.poll_policy.PeekShavingPoll;
import com.yf.core.partitioning.schedule_policy.impl.poll_policy.RandomPoll;
import com.yf.core.partitioning.schedule_policy.impl.poll_policy.RoundRobinPoll;
import com.yf.core.partitioning.schedule_policy.impl.poll_policy.ThreadBindingPoll;
import com.yf.core.partitioning.schedule_policy.impl.remove_policy.PeekShavingRemove;
import com.yf.core.partitioning.schedule_policy.impl.remove_policy.RoundRobinRemove;
import java.util.HashMap;
import java.util.Map;
/**
* @author yyf
* @date 2025/9/20 21:29
* @description : 调度规则资源管理(SchedulePolicyResourceManager)
*/
public class SPResourceManager {
//以下三个是各自调度规则的map
private static final Map<String,Class<? extends OfferPolicy>> OFFER_POLICY_MAP = new HashMap<>();
private static final Map<String,Class<? extends PollPolicy>> POLL_POLICY_MAP = new HashMap<>();
private static final Map<String,Class<? extends RemovePolicy>> REMOVE_POLICY_MAP = new HashMap<>();
static {
//Offer
register("round_robin", RoundRobinOffer.class);
register("random", RandomOffer.class);
register("plain_hash", PlainHashOffer.class);
register("balanced_hash", BalancedHashOffer.class);
register("valley_filling", ValleyFillingOffer.class);
//poll
register("round_robin", RoundRobinPoll.class);
register("peek_shaving", PeekShavingPoll.class);
register("thread_binding", ThreadBindingPoll.class);
register("random", RandomPoll.class);
//remove
register("round_robin", RoundRobinRemove.class);
register("peek_shaving", PeekShavingRemove.class);
register("random", PeekShavingRemove.class);
}
//调度资源注册
public static void register(String name, Class policyClass) {
if(policyClass.getSuperclass()==OfferPolicy.class) {
OFFER_POLICY_MAP.put(name, policyClass);
}
if(policyClass.getSuperclass()==PollPolicy.class) {
POLL_POLICY_MAP.put(name, policyClass);
}
if (policyClass.getSuperclass() == RemovePolicy.class) {
REMOVE_POLICY_MAP.put(name, policyClass);
}
}
//获取调度资源
public static Class<? extends OfferPolicy> getOfferResource(String name){
return OFFER_POLICY_MAP.get(name);
}
public static Class<? extends PollPolicy> getPollResource(String name){
return POLL_POLICY_MAP.get(name);
}
public static Class<? extends RemovePolicy> getRemoveResource(String name){
return REMOVE_POLICY_MAP.get(name);
}
//获取所有调度资源
public static Map<String,Class<? extends OfferPolicy>> getOfferResources(){
return OFFER_POLICY_MAP;
}
public static Map<String,Class<? extends PollPolicy>> getPollResources(){
return POLL_POLICY_MAP;
}
public static Map<String,Class<? extends RemovePolicy>> getRemoveResources(){
return REMOVE_POLICY_MAP;
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/core/resource_manager/SPResourceManager.java | Java | mit | 3,421 |
package com.yf.core.threadpool;
import com.yf.common.constant.Logo;
import com.yf.common.entity.PoolInfo;
import com.yf.common.entity.QueueInfo;
import com.yf.core.partitioning.impl.PartiFlow;
import com.yf.core.partitioning.Partitioning;
import com.yf.core.resource_manager.PartiResourceManager;
import com.yf.core.resource_manager.RSResourceManager;
import com.yf.core.resource_manager.SPResourceManager;
import com.yf.core.rejectstrategy.RejectStrategy;
import com.yf.core.partition.Partition;
import com.yf.core.tp_regulator.UnifiedTPRegulator;
import com.yf.core.workerfactory.WorkerFactory;
import com.yf.core.worker.Worker;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.atomic.AtomicInteger;
import static com.yf.common.constant.Constant.CORE;
import static com.yf.common.constant.Constant.EXTRA;
/**
* @author yyf
* @description
*/
@Slf4j
@Getter
@Setter
public class ThreadPool {
static {
System.out.println(Logo.startLogo());
}
private String type;
private WorkerFactory workerFactory;//线程工厂
private volatile Partition<Runnable> partition;//线程池的任务队列
private volatile RejectStrategy rejectStrategy;//拒绝策略
private volatile Integer coreNums;//核心线程数
private volatile Integer maxNums;//最大线程数
private Set<Worker> coreList = ConcurrentHashMap.newKeySet();
private Set<Worker> extraList = ConcurrentHashMap.newKeySet();
private final AtomicInteger coreWorkerCount = new AtomicInteger(0); // 核心线程存活数
private final AtomicInteger extraWorkerCount = new AtomicInteger(0); // 额外线程存活数
private String name;//线程池名称
public ThreadPool(
Integer coreNums, Integer maxNums, String name,
WorkerFactory threadFactory, Partition<Runnable> partition,
RejectStrategy rejectStrategy
) {
this.workerFactory = threadFactory;
threadFactory.setThreadName(name + ":" + threadFactory.getThreadName());
threadFactory.setThreadPool(this);
this.partition = partition;
this.rejectStrategy = rejectStrategy;
this.coreNums = coreNums;
this.maxNums = maxNums;
this.name = name;
UnifiedTPRegulator.register(name,this);
log.info(Logo.LOG_LOGO+"线程池"+name+"注册成功");
}
public ThreadPool(
String type, Integer coreNums, Integer maxNums, String name,
WorkerFactory threadFactory, Partition<Runnable> partition,
RejectStrategy rejectStrategy
) {
this(coreNums, maxNums, name, threadFactory, partition, rejectStrategy);
this.type = type;
}
public void execute(Runnable task) {
if(task==null) throw new NullPointerException();
if (coreWorkerCount.get() < coreNums) {
if (addWorker(task,true)) {
return;
}
}
if (partition.offer(task)) {
if(coreNums==0){
addWorker(null,false);
}
return;
}
if (addWorker(task,false)) {
return;
}
rejectStrategy.reject(this,task);
}
public <T> Future<T> submit(Callable<T> callable) {
if (callable == null) throw new NullPointerException();
FutureTask<T> ftask = new FutureTask<>(callable);
execute(ftask);
return ftask;
}
private boolean addWorker(Runnable task, boolean isCore) {
// 循环CAS重试:直到成功或确定无法创建线程
while (true) {
if (isCore) {
int current = coreWorkerCount.get();
if (current >= coreNums) {
return false; // 核心线程达到上限,退出
}
// CAS尝试更新
if (coreWorkerCount.compareAndSet(current, current + 1)) {
break; // CAS成功,即将退出循环创建Worker
}// CAS失败,继续循环重试
} else {
// 额外线程逻辑
int current = extraWorkerCount.get();
int extraMax = maxNums - coreNums;
if (current >= extraMax) {
return false; // 额外线程达到上限,退出
}
if (extraWorkerCount.compareAndSet(current, current + 1)) {
break; // CAS成功,退出循环
}// CAS失败,继续循环重试
}
Thread.yield();
}
Worker worker = null;
try {
worker = workerFactory.createWorker(isCore, task);
if (isCore) {
coreList.add(worker);
} else {
extraList.add(worker);
}
worker.startWorking();
return true;
} catch (Throwable e) {//异常回滚
if (isCore) {
coreWorkerCount.getAndDecrement();
} else {
extraWorkerCount.getAndDecrement();
}
if (worker != null) {
if (isCore) {
coreList.remove(worker);
} else {
extraList.remove(worker);
}
}
return false;
}
}
// =======================================================
// 以下是对于线程池相关参数的读写操作,用来提供监控信息和修改参数,不涉及到线程池运行过程的自动调控,所以读取信息全部无锁
/**
* 获取线程池中线程的信息
*
* @return :String代表线程类别,Thread.State代表线程状态,Integer代表对应类别的状态的数量
*/
public Map<String, Map<Thread.State, Integer>> getThreadsInfo() {
Map<String, Map<Thread.State, Integer>> result = new HashMap<>();
Map<Thread.State, Integer> coreMap = new HashMap<>();
Map<Thread.State, Integer> extraMap = new HashMap<>();
for (Worker worker : coreList) {
Thread.State state = worker.getThreadState();
if (coreMap.containsKey(state)) {
coreMap.put(state, coreMap.get(state) + 1);
} else {
coreMap.put(state, 1);
}
}
for (Worker worker : extraList) {
Thread.State state = worker.getThreadState();
if (extraMap.containsKey(state)) {
extraMap.put(state, extraMap.get(state) + 1);
} else {
extraMap.put(state, 1);
}
}
result.put(CORE, coreMap);
result.put(EXTRA, extraMap);
return result;
}
/**
* 获取线程池信息
*
* @return
*/
public PoolInfo getThreadPoolInfo() {
PoolInfo info = new PoolInfo();
info.setPoolName(name);
info.setAliveTime(workerFactory.getAliveTime());
info.setThreadName(workerFactory.getThreadName());
info.setCoreDestroy(workerFactory.isCoreDestroy());
info.setDaemon(workerFactory.isUseDaemonThread());
info.setMaxNums(maxNums);
info.setCoreNums(coreNums);
//获取当前队列名字
for(Map.Entry entry : PartiResourceManager.getResources().entrySet()){
if (entry.getValue() == partition.getClass()) {
info.setQueueName(entry.getKey().toString());
break;
}
}
for(Map.Entry entry : RSResourceManager.REJECT_STRATEGY_MAP.entrySet()){
if (entry.getValue() == rejectStrategy.getClass()) {
info.setRejectStrategyName(entry.getKey().toString());
break;
}
}
return info;
}
/**
* 获取队列的任务数量
* @return
*/
public int getTaskNums() {
return partition.getEleNums();
}
/**
* 获取每个分区的任务数量
* @return
*/
public Map<Integer,Integer> getPartitionTaskNums(){
Map<Integer,Integer> map = new HashMap<>();
if(!(partition instanceof PartiFlow)){//不是分区队列
map.put(0,partition.getEleNums());
}else {//是分区队列
Partition<Runnable>[] partitions = ((PartiFlow<Runnable>) partition).getPartitions();
for(int i = 0;i<partitions.length;i++){
map.put(i,partitions[i].getEleNums());
}
}
return map;
}
/**
* 获取队列信息
* @return
*/
public QueueInfo getQueueInfo(){
QueueInfo queueInfo = new QueueInfo();
queueInfo.setCapacity(partition.getCapacity());
if(partition instanceof Partitioning<?>){
for(Map.Entry entry : PartiResourceManager.getResources().entrySet()){
if (entry.getValue() == ((Partitioning<Runnable>) partition).getPartitions()[0].getClass()) {
queueInfo.setQueueName(entry.getKey().toString());
break;
}
}
queueInfo.setPartitionNum(((Partitioning<Runnable>) partition).getPartitions().length);
queueInfo.setPartitioning(true);
//找到offer的名字
for(Map.Entry entry : SPResourceManager.getOfferResources().entrySet()){
if (entry.getValue() == ((Partitioning<Runnable>) partition).getOfferPolicy().getClass()) {
queueInfo.setOfferPolicy(entry.getKey().toString());
break;
}
}
//找到poll的名字
for(Map.Entry entry : SPResourceManager.getPollResources().entrySet()){
if (entry.getValue() == ((Partitioning<Runnable>) partition).getPollPolicy().getClass()) {
queueInfo.setPollPolicy(entry.getKey().toString());
break;
}
}
//找到remove的名字
for(Map.Entry entry : SPResourceManager.getRemoveResources().entrySet()){
if (entry.getValue() == ((Partitioning<Runnable>) partition).getRemovePolicy().getClass()) {
queueInfo.setRemovePolicy(entry.getKey().toString());
break;
}
}
}
//获取队列的名字
for(Map.Entry entry : PartiResourceManager.getResources().entrySet()){
if (entry.getValue() == partition.getClass()) {
queueInfo.setQueueName(entry.getKey().toString());
break;
}
}
return queueInfo;
}
/**
* 获取所有的队列的名称
*/
public List<String> getAllQueueName(){
return new ArrayList<>(PartiResourceManager.getResources().keySet());
}
/**
* 获取所有的拒绝策略的名称
*/
public List<String> getAllRejectStrategyName(){
return new ArrayList<>(RSResourceManager.getResources().keySet());
}
/**
* 改变worker相关参数,直接赋值就好,会动态平衡的
*/
public Boolean changeWorkerParams(Integer coreNums, Integer maxNums, Boolean coreDestroy, Integer aliveTime, Boolean isDaemon) {
if (maxNums!=null&&coreNums!=null&&maxNums < coreNums) {
return false;
}
int oldCoreNums = this.coreNums;
int oldMaxNums = this.maxNums;
if(coreNums!=null){
if(maxNums==null){
if(coreNums > oldMaxNums){
return false;
}
}
}else{
if(maxNums!=null&&maxNums < oldCoreNums){
return false;
}
}
if(maxNums!=null) {
this.maxNums = maxNums;//无论如何非核心线程都能直接改变
}
if(coreNums!=null) {
this.coreNums = coreNums;
}
if(coreNums==null){
if(maxNums!=null) {
destroyWorkers(0, (oldMaxNums - oldCoreNums) - (maxNums - coreNums));
}
}else{
if(maxNums==null) {
destroyWorkers(oldCoreNums - coreNums, 0);
}else{
destroyWorkers(oldCoreNums - coreNums, (oldMaxNums - oldCoreNums) - (maxNums - coreNums));
}
}
if (aliveTime != null) {
this.workerFactory.setAliveTime(aliveTime);
}
if (coreDestroy != null) {
this.workerFactory.setCoreDestroy(coreDestroy);
}
if (isDaemon != null && isDaemon != this.workerFactory.isUseDaemonThread()) {
this.workerFactory.setUseDaemonThread(isDaemon);
for (Worker worker : getCoreList()) {
worker.setDaemon(isDaemon);
}
for (Worker worker : getExtraList()) {
worker.setDaemon(isDaemon);
}
}
return true;
}
//销毁线程
public void destroyWorkers(int coreNums, int extraNums) {//销毁的数量
if (coreNums > 0) {
int i = 0;
for (Worker worker : getCoreList()) {
worker.setFlag(false);
worker.lock();//防止任务执行过程中被中断
worker.interruptWorking();
worker.unlock();
i++;
if (i == coreNums) {
break;
}
}
}
if (extraNums > 0) {
int j = 0;
for (Worker worker : getExtraList()) {
worker.setFlag(false);
worker.lock();
worker.interruptWorking();
worker.unlock();
j++;
if (j == extraNums) {
break;
}
}
}
}
/**
* 改变队列
*/
public Boolean changeQueue(Partition<Runnable> q, String qName){
if(q == null|| qName == null){
return false;
}
Partition<Runnable> oldQ = partition;
try {
oldQ.lockGlobally();
if(!(oldQ instanceof Partitioning)) {
//非分区队列
while (oldQ.getEleNums() > 0) {
Runnable task = oldQ.poll(1);
q.offer(task);
}
}else{
//分区队列
for(int i = 0;i < ((Partitioning<Runnable>) oldQ).getPartitions().length;i++){
while(((Partitioning<Runnable>) oldQ).getPartitions()[i].getEleNums() > 0){
Runnable task = ((Partitioning<Runnable>) oldQ).getPartitions()[i].poll(1);
q.offer(task);
}
}
}
this.partition = q;
} catch (Exception e) {
e.printStackTrace();
} finally {
oldQ.unlockGlobally();
}
return true;
}
/**
* 改变拒绝策略,默认与拒绝策略无共享变量需要争抢,所以线程安全,不需要加锁
*/
public Boolean changeRejectStrategy(RejectStrategy rejectStrategy,String rejectStrategyName){
if(rejectStrategy == null|| rejectStrategyName == null){
return false;
}
this.rejectStrategy = rejectStrategy;
return true;
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/core/threadpool/ThreadPool.java | Java | mit | 15,563 |
package com.yf.core.tp_regulator;
import com.yf.common.entity.PoolInfo;
import com.yf.common.entity.QueueInfo;
import com.yf.core.partition.Partition;
import com.yf.core.partitioning.Partitioning;
import com.yf.core.partitioning.impl.PartiFlow;
import com.yf.core.rejectstrategy.RejectStrategy;
import com.yf.core.resource_manager.GCTaskManager;
import com.yf.core.resource_manager.PartiResourceManager;
import com.yf.core.resource_manager.RSResourceManager;
import com.yf.core.resource_manager.SPResourceManager;
import com.yf.core.threadpool.ThreadPool;
import com.yf.core.worker.Worker;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static com.yf.common.constant.Constant.CORE;
import static com.yf.common.constant.Constant.EXTRA;
/**
* @author yyf
* @date 2025/10/5 12:50
* @description :线程池动态调节类,解耦线程池核心逻辑和调节逻辑,未来将实现用单个调节对象统一管控所有的线程池
*/
public class UnifiedTPRegulator {
private final static Map<String,ThreadPool> threadPoolMap = new HashMap<>();
/**
* 注册线程池
* @param name:线程池名字
* @param threadPool: 线程池
*/
public static void register(String name, ThreadPool threadPool) {
threadPoolMap.put(name, threadPool);
}
/**
* 获取线程池
* @param name:线程池名字
* @return 线程池
*/
public static ThreadPool getResource(String name){
return threadPoolMap.get(name);
}
public static Map<String,ThreadPool> getResources(){
return threadPoolMap;
}
// =============================线程池信息和调控====================================
/**
* 新增:获取所有线程池的基本信息列表
*/
public static List<PoolInfo> getAllThreadPoolInfo() {
return threadPoolMap.values().stream()
.map(threadPool -> getThreadPoolInfo(threadPool.getName())) // 复用现有getThreadPoolInfo逻辑
.collect(Collectors.toList());
}
/**
* 新增:获取所有线程池名称
*/
public static List<String> getAllThreadPoolNames() {
return new ArrayList<>(threadPoolMap.keySet());
}
/**
* 获取线程池中线程的信息
*
* @return :String代表线程类别,Thread.State代表线程状态,Integer代表对应类别的状态的数量
*/
public static Map<String, Map<Thread.State, Integer>> getThreadsInfo(String tpName) {
ThreadPool threadPool = threadPoolMap.get(tpName);
Map<String, Map<Thread.State, Integer>> result = new HashMap<>();
Map<Thread.State, Integer> coreMap = new HashMap<>();
Map<Thread.State, Integer> extraMap = new HashMap<>();
for (Worker worker : threadPool.getCoreList()) {
Thread.State state = worker.getThreadState();
if (coreMap.containsKey(state)) {
coreMap.put(state, coreMap.get(state) + 1);
} else {
coreMap.put(state, 1);
}
}
for (Worker worker : threadPool.getExtraList()) {
Thread.State state = worker.getThreadState();
if (extraMap.containsKey(state)) {
extraMap.put(state, extraMap.get(state) + 1);
} else {
extraMap.put(state, 1);
}
}
result.put(CORE, coreMap);
result.put(EXTRA, extraMap);
return result;
}
/**
* 获取线程池信息
*
* @return
*/
public static PoolInfo getThreadPoolInfo(String tpName) {
ThreadPool threadPool = threadPoolMap.get(tpName);
PoolInfo info = new PoolInfo();
info.setType(threadPool.getType());
info.setPoolName(threadPool.getName());
info.setAliveTime(threadPool.getWorkerFactory().getAliveTime());
info.setThreadName(threadPool.getWorkerFactory().getThreadName());
info.setCoreDestroy(threadPool.getWorkerFactory().isCoreDestroy());
info.setDaemon(threadPool.getWorkerFactory().isUseDaemonThread());
info.setMaxNums(threadPool.getMaxNums());
info.setCoreNums(threadPool.getCoreNums());
//获取当前队列名字
for(Map.Entry entry : PartiResourceManager.getResources().entrySet()){
if (entry.getValue() == threadPool.getPartition().getClass()) {
info.setQueueName(entry.getKey().toString());
break;
}
}
for(Map.Entry entry : RSResourceManager.REJECT_STRATEGY_MAP.entrySet()){
if (entry.getValue() == threadPool.getRejectStrategy().getClass()) {
info.setRejectStrategyName(entry.getKey().toString());
break;
}
}
return info;
}
/**
* 获取队列的任务数量
* @return
*/
public static int getTaskNums(String tpName) {
ThreadPool threadPool = threadPoolMap.get(tpName);
return threadPool.getPartition().getEleNums();
}
/**
* 获取每个分区的任务数量
* @return
*/
public static Map<Integer,Integer> getPartitionTaskNums(String tpName){
ThreadPool threadPool = threadPoolMap.get(tpName);
Map<Integer,Integer> map = new HashMap<>();
if(!(threadPool.getPartition() instanceof PartiFlow)){//不是分区队列
map.put(0,threadPool.getPartition().getEleNums());
}else {//是分区队列
Partition<Runnable>[] partitions = ((PartiFlow<Runnable>) threadPool.getPartition()).getPartitions();
for(int i = 0;i<partitions.length;i++){
map.put(i,partitions[i].getEleNums());
}
}
return map;
}
/**
* 获取队列信息
* @return
*/
public static QueueInfo getQueueInfo(String tpName){
ThreadPool threadPool = threadPoolMap.get(tpName);
QueueInfo queueInfo = new QueueInfo();
queueInfo.setCapacity(threadPool.getPartition().getCapacity());
if(threadPool.getPartition() instanceof Partitioning<?>){
Partitioning<Runnable> partition = (Partitioning<Runnable>) threadPool.getPartition();
for(Map.Entry entry : PartiResourceManager.getResources().entrySet()){
if (entry.getValue() == partition.getPartitions()[0].getClass()) {
queueInfo.setQueueName(entry.getKey().toString());
break;
}
}
queueInfo.setPartitionNum(partition.getPartitions().length);
queueInfo.setPartitioning(true);
//找到offer的名字
for(Map.Entry entry : SPResourceManager.getOfferResources().entrySet()){
if (entry.getValue() == partition.getOfferPolicy().getClass()) {
queueInfo.setOfferPolicy(entry.getKey().toString());
break;
}
}
//找到poll的名字
for(Map.Entry entry : SPResourceManager.getPollResources().entrySet()){
if (entry.getValue() == partition.getPollPolicy().getClass()) {
queueInfo.setPollPolicy(entry.getKey().toString());
break;
}
}
//找到remove的名字
for(Map.Entry entry : SPResourceManager.getRemoveResources().entrySet()){
if (entry.getValue() == partition.getRemovePolicy().getClass()) {
queueInfo.setRemovePolicy(entry.getKey().toString());
break;
}
}
}
//获取队列的名字
for(Map.Entry entry : PartiResourceManager.getResources().entrySet()){
if (entry.getValue() == threadPool.getPartition().getClass()) {
queueInfo.setQueueName(entry.getKey().toString());
break;
}
}
return queueInfo;
}
/**
* 获取所有的队列的名称
*/
public static List<String> getAllQueueName(){
return new ArrayList<>(PartiResourceManager.getResources().keySet());
}
/**
* 获取所有的拒绝策略的名称
*/
public static List<String> getAllRejectStrategyName(){
return new ArrayList<>(RSResourceManager.getResources().keySet());
}
/**
* 改变worker相关参数,直接赋值就好,会动态平衡的
*/
public static Boolean changeWorkerParams(String tpName,Integer coreNums, Integer maxNums, Boolean coreDestroy, Integer aliveTime, Boolean isDaemon) {
ThreadPool threadPool = threadPoolMap.get(tpName);
if (maxNums!=null&&coreNums!=null&&maxNums < coreNums) {
return false;
}
int oldCoreNums = threadPool.getCoreNums();
int oldMaxNums = threadPool.getMaxNums();
if(coreNums!=null){
if(maxNums==null){
if(coreNums > oldMaxNums){
return false;
}
}
}else{
if(maxNums!=null&&maxNums < oldCoreNums){
return false;
}
}
if(maxNums!=null) {
threadPool.setMaxNums(maxNums);//无论如何非核心线程都能直接改变
}
if(coreNums!=null) {
threadPool.setCoreNums(coreNums);
}
if(coreNums==null){
if(maxNums!=null) {
destroyWorkers(tpName, 0, (oldMaxNums - oldCoreNums) - (maxNums - coreNums));
}
}else{
if(maxNums==null) {
destroyWorkers(tpName, oldCoreNums - coreNums, 0);
}else{
destroyWorkers(tpName, oldCoreNums - coreNums, (oldMaxNums - oldCoreNums) - (maxNums - coreNums));
}
}
if (aliveTime != null) {
threadPool.getWorkerFactory().setAliveTime(aliveTime);
}
if (coreDestroy != null) {
threadPool.getWorkerFactory().setCoreDestroy(coreDestroy);
}
if (isDaemon != null && isDaemon != threadPool.getWorkerFactory().isUseDaemonThread()) {
threadPool.getWorkerFactory().setUseDaemonThread(isDaemon);
for (Worker worker : threadPool.getCoreList()) {
worker.setDaemon(isDaemon);
}
for (Worker worker : threadPool.getExtraList()) {
worker.setDaemon(isDaemon);
}
}
return true;
}
//销毁worker
public static void destroyWorkers(String tpName,int coreNums, int extraNums) {//销毁的数量
ThreadPool threadPool = threadPoolMap.get(tpName);
if (coreNums > 0) {
int i = 0;
for (Worker worker : threadPool.getCoreList()) {
worker.setFlag(false);
worker.lock();//防止任务执行过程中被中断
worker.interruptWorking();
worker.unlock();
i++;
if (i == coreNums) {
break;
}
}
}
if (extraNums > 0) {
int j = 0;
for (Worker worker : threadPool.getExtraList()) {
worker.setFlag(false);
worker.lock();
worker.interruptWorking();
worker.unlock();
j++;
if (j == extraNums) {
break;
}
}
}
}
/**
* 改变队列容量
*/
public static void changeQueueCapacity(String tpName,int capacity){
threadPoolMap.get(tpName).getPartition().setCapacity( capacity);
}
/**
* 改变队列
*/
public static Boolean changeQueue(String tpName,Partition<Runnable> q){
ThreadPool threadPool = threadPoolMap.get(tpName);
if(q == null){
return false;
}
Partition<Runnable> oldQ = threadPool.getPartition();
try {
oldQ.lockGlobally();//切换队列先加锁以同步入队线程,使得入队线程永远在新队列入队(只能保证作者的队列如此)
oldQ.markAsSwitched();//标记队列已切换
threadPool.setPartition(q);//改变队列
//以上操作可能无法重置调度规则的重置例如:ThreadBinding,或者有些队列无法及时感知,这算是一个补救策略
GCTaskManager.clean(threadPool,oldQ);
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
oldQ.unlockGlobally();
}
try {
if (!(oldQ instanceof Partitioning)) {
//非分区队列
GCTaskManager.execute(()->{
while (oldQ.getEleNums() > 0) {
Runnable task = null;
try {
task = oldQ.poll(1);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
q.offer(task);
}
});
} else {
//分区队列
GCTaskManager.execute(()->{
Partition<Runnable>[] partitions = ((Partitioning<Runnable>) oldQ).getPartitions();
for (Partition<Runnable> partition : partitions) {
while (partition.getEleNums() > 0) {
Runnable task = null;
try {
task = partition.poll(1);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
q.offer(task);
}
}
});
}
} catch (Exception e) {
return false;
}
return true;
}
/**
* 改变拒绝策略,默认与拒绝策略无共享变量需要争抢,所以线程安全,不需要加锁
*/
public static Boolean changeRejectStrategy(String tpName,RejectStrategy rejectStrategy, String rejectStrategyName){
ThreadPool threadPool = threadPoolMap.get(tpName);
if(rejectStrategy == null|| rejectStrategyName == null){
return false;
}
threadPool.setRejectStrategy(rejectStrategy);
return true;
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/core/tp_regulator/UnifiedTPRegulator.java | Java | mit | 14,592 |
package com.yf.core.worker;
import com.yf.common.constant.Logo;
import com.yf.core.threadpool.ThreadPool;
import com.yf.core.workerfactory.WorkerFactory;
import lombok.Getter;
import lombok.Setter;
import lombok.Synchronized;
import lombok.extern.slf4j.Slf4j;
import java.util.Set;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author yyf
* @description
*/
@Slf4j
@Getter
@Setter
public class Worker implements Runnable {
private Thread thread;
private Lock lock = new ReentrantLock();
volatile private boolean flag = true;
volatile private boolean isCore;
private ThreadPool threadPool;
volatile private boolean coreDestroy;//如果非核心线程就设置为null
volatile private Integer aliveTime;//核心线程如果允许销毁则为这个数的两倍
private Runnable onTimeTask;//是指直接提交运行的任务
public Worker(ThreadPool threadPool,Boolean isCore, Boolean coreDestroy, Integer aliveTime, Runnable onTimeTask) {
this.threadPool = threadPool;
this.isCore = isCore;
this.coreDestroy = coreDestroy;
this.aliveTime = aliveTime;
this.onTimeTask = onTimeTask;
}
public void startWorking(){
thread.start();
}
public Thread.State getThreadState(){
return thread.getState();
}
public void setDaemon(boolean isDaemon){
thread.setDaemon(isDaemon);
}
public void interruptWorking(){
thread.interrupt();
}
@Override
public void run() {
try {
if (onTimeTask != null) {
try {
lock.lock();
onTimeTask.run();
} catch (Throwable t) {
log.error("onTimeTask执行异常", t);
} finally {
lock.unlock();
onTimeTask = null; // 无论是否异常,都清空初始任务
}
}
//循环任务
while (flag) {
try {
Runnable runnable;
if(isCore) {
if(coreDestroy) {//核心线程并且允许销毁
runnable = threadPool.getPartition().poll(aliveTime*2);
if(runnable == null){
threadPool.getCoreList().remove(this);
threadPool.getCoreWorkerCount().getAndDecrement();
log.info("核心线程"+thread.getName()+"销毁");
break;
}
}else{//核心线程并且不允许销毁
runnable = threadPool.getPartition().poll(null);
}
}else{//非核心线程
runnable = threadPool.getPartition().poll(aliveTime);
if(runnable == null){
threadPool.getExtraList().remove(this);
threadPool.getExtraWorkerCount().getAndDecrement();
log.info("非核心线程"+thread.getName()+"销毁");
break;
}
}
try {
lock.lock();//获取锁才能执行任务,防止任务中有可以被打断的等待逻辑在等待中被打断
runnable.run();
} catch (Exception e) {
log.error(Logo.LOG_LOGO+"Worker线程执行任务中发生异常", e);
}finally {
lock.unlock();
}
}
catch (InterruptedException e) {
break;
}
catch (Exception e) {
log.error(Logo.LOG_LOGO+"Worker线程执行任务之外发生异常", e);
}
}
} catch (Throwable t) {
log.error("Worker线程异常终止", t);
}
}
public void lock(){
lock.lock();
}
public void unlock(){
lock.unlock();
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/core/worker/Worker.java | Java | mit | 4,225 |
package com.yf.core.workerfactory;
import com.yf.common.constant.Constant;
import com.yf.core.threadpool.ThreadPool;
import com.yf.core.worker.Worker;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
/**
* @author yyf
* @description
*/
@Slf4j
@Data
public class WorkerFactory {
private ThreadPool threadPool;
private String threadName;// 线程名称
private boolean useDaemonThread;//是否守护线程
private boolean coreDestroy;//是否销毁核心线程
private Integer aliveTime;//空闲存活时间 :null代表不销毁
private boolean useVirtualThread;//是否虚拟线程
public WorkerFactory(String threadName, Boolean isDaemon, Boolean coreDestroy, Integer aliveTime){
this.threadName = threadName;
this.useDaemonThread = isDaemon;
this.coreDestroy = coreDestroy;
this.aliveTime = aliveTime;
}
public WorkerFactory(String threadName, Boolean isDaemon, Boolean coreDestroy, Integer aliveTime,boolean useVirtualThread) {
this.threadName = threadName;
this.useDaemonThread = isDaemon;
this.coreDestroy = coreDestroy;
this.aliveTime = aliveTime;
this.useVirtualThread = useVirtualThread;
}
public Worker createWorker(Boolean isCore, Runnable task){
Worker worker = new Worker(threadPool,isCore,coreDestroy,aliveTime,task);
if(useVirtualThread){//创建虚拟线程
Thread thread = Thread.ofVirtual().name(Constant.VIRTUAL +threadName).unstarted( worker);
worker.setThread(thread);
} else{//创建平台线程
Thread thread = new Thread(worker, Constant.PLATFORM+threadName);
thread.setDaemon(useDaemonThread);
worker.setThread(thread);
}
return worker;
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/core/workerfactory/WorkerFactory.java | Java | mit | 1,798 |
package com.yf.springboot_integration.monitor.auto_configuration;
import com.yf.springboot_integration.monitor.controller.MonitorController;
import com.yf.springboot_integration.pool.auto_configuration.LittleChiefAutoConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @author yyf
* @description
*/
@Slf4j
@AutoConfiguration
@AutoConfigureAfter(LittleChiefAutoConfiguration.class)
@ConditionalOnProperty(prefix = "yf.thread-pool.monitor", name = "enabled", havingValue = "true")
public class WebAutoConfiguration implements WebMvcConfigurer{
@Bean
public MonitorController monitorController(ApplicationContext context){
return new MonitorController(context);
}
//开启静态资源映射
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/springboot_integration/monitor/auto_configuration/WebAutoConfiguration.java | Java | mit | 1,377 |
package com.yf.springboot_integration.monitor.auto_configuration;
import com.yf.springboot_integration.monitor.ws.SchedulePushInfoService;
import com.yf.springboot_integration.monitor.ws.ThreadPoolWebSocketHandler;
import com.yf.springboot_integration.pool.auto_configuration.LittleChiefAutoConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
/**
* @author yyf
* @description
*/
@Slf4j
@EnableScheduling
@EnableWebSocket
@AutoConfiguration
@AutoConfigureAfter(LittleChiefAutoConfiguration.class)
@ConditionalOnProperty(prefix = "yf.thread-pool.monitor", name = "enabled", havingValue = "true")
public class WsAutoConfiguration implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new ThreadPoolWebSocketHandler(), "/monitor/threads")
.setAllowedOrigins("*");
}
@Bean
public SchedulePushInfoService schedulePushInfoService(){
return new SchedulePushInfoService();
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/springboot_integration/monitor/auto_configuration/WsAutoConfiguration.java | Java | mit | 1,573 |
package com.yf.springboot_integration.monitor.controller;
import com.yf.core.resource_manager.PartiResourceManager;
import com.yf.core.resource_manager.RSResourceManager;
import com.yf.core.resource_manager.SPResourceManager;
import com.yf.common.entity.PoolInfo;
import com.yf.common.entity.QueueInfo;
import com.yf.core.partitioning.impl.PartiFlow;
import com.yf.core.partitioning.schedule_policy.OfferPolicy;
import com.yf.core.partitioning.schedule_policy.PollPolicy;
import com.yf.core.partitioning.schedule_policy.RemovePolicy;
import com.yf.core.rejectstrategy.RejectStrategy;
import com.yf.core.partition.Partition;
import com.yf.core.threadpool.ThreadPool;
import com.yf.core.tp_regulator.UnifiedTPRegulator;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.*;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;
/**
* @author yyf
* @description
*/
@RestController
@RequestMapping("/monitor")
@AllArgsConstructor
public class MonitorController {
private ApplicationContext context;
/**
* 新增:获取所有线程池基本信息列表
*/
@GetMapping("/pools")
public List<PoolInfo> getAllPools() {
return UnifiedTPRegulator.getAllThreadPoolInfo();
}
/**
* 新增:获取所有线程池名称
*/
@GetMapping("/poolNames")
public List<String> getAllPoolNames() {
return UnifiedTPRegulator.getAllThreadPoolNames();
}
/**
* 获取线程池的信息
* return PoolInfo 线程池信息
*/
@GetMapping("/pool")
public PoolInfo getThreadPoolInfo(@RequestParam(required = true) String tpName) {
ThreadPool threadPool = UnifiedTPRegulator.getResource(tpName);
return threadPool != null ? threadPool.getThreadPoolInfo() : null;
}
/**
* 获取队列中总任务数量
* return int 队列中任务数量
*/
@GetMapping("/tasks")
public int getQueueSize(@RequestParam(required = true) String tpName) {
ThreadPool threadPool = UnifiedTPRegulator.getResource(tpName);
return threadPool != null ? threadPool.getTaskNums() : 0;
}
/**
* 获取各个分区任务数量
* @return
*/
@GetMapping("/partitionTaskNums")
public Map<Integer,Integer> getPartitionTaskNums(@RequestParam(required = true) String tpName) {
ThreadPool threadPool = UnifiedTPRegulator.getResource(tpName);
return threadPool != null ? threadPool.getPartitionTaskNums() : null;
}
/**
* 获取队列信息
*/
@GetMapping("/queue")
public QueueInfo getQueueInfo(@RequestParam(required = true) String tpName) {
ThreadPool threadPool = UnifiedTPRegulator.getResource(tpName);
return threadPool != null ? threadPool.getQueueInfo() : null;
}
/**
* 获取所有队列名称
*/
@GetMapping("/queueName")
public List<String> getAllQueueName(@RequestParam(required = true) String tpName) {
ThreadPool threadPool = UnifiedTPRegulator.getResource(tpName);
return threadPool != null ? threadPool.getAllQueueName() : null;
}
/**
* 获取所有拒绝策略名称
*/
@GetMapping("/rejectStrategyName")
public List<String> getAllRejectStrategyName(@RequestParam(required = true) String tpName) {
ThreadPool threadPool = UnifiedTPRegulator.getResource(tpName);
return threadPool != null ? threadPool.getAllRejectStrategyName() : null;
}
/**
* 更改worker相关的参数
* return true/false 表示成功与否
*/
@PutMapping("/worker")
public Boolean changeWorkerParams(
@RequestParam(required = true) String tpName,
Integer coreNums,
Integer maxNums,
Boolean coreDestroy,
Integer aliveTime,
Boolean isDaemon) {
ThreadPool threadPool = UnifiedTPRegulator.getResource(tpName);
return threadPool != null && threadPool.changeWorkerParams(coreNums, maxNums, coreDestroy, aliveTime, isDaemon);
}
/**
* 改变队列(修复:将Post改为Put,与文档一致)
* return true/false 示成功与否
*/
@PutMapping("/queue")
public Boolean changeQ(
@RequestParam(required = true) String tpName,
@RequestBody QueueInfo queueInfo) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
if (queueInfo.getQueueName() == null || queueInfo.getQueueName().isEmpty()) {
return false;
}
ThreadPool threadPool = UnifiedTPRegulator.getResource(tpName);
if (threadPool == null) {
return false;
}
Partition q;
if (!PartiResourceManager.getResources().containsKey(queueInfo.getQueueName())) {//队列不存在
return false;
} else {//队列存在
if(!queueInfo.isPartitioning()) {//不分区
q = PartiResourceManager.getResources().get(queueInfo.getQueueName()).getConstructor(Integer.class).newInstance(queueInfo.getCapacity());
}else{//分区
q = new PartiFlow(queueInfo.getPartitionNum(), queueInfo.getCapacity(), queueInfo.getQueueName(),
SPResourceManager.getOfferResource(queueInfo.getOfferPolicy()).getConstructor().newInstance(),
SPResourceManager.getPollResource(queueInfo.getPollPolicy()).getConstructor().newInstance(),
SPResourceManager.getRemoveResource(queueInfo.getRemovePolicy()).getConstructor().newInstance());
}
}
return threadPool.changeQueue(q, queueInfo.getQueueName());
}
/**
* 改变拒绝策略
* return true/false 表示成功与否
*/
@PutMapping("/rejectStrategy")
public Boolean changeRS(
@RequestParam(required = true) String tpName,
@RequestParam(required = true) String rsName) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
if (rsName == null || rsName.isEmpty()) {
return false;
}
ThreadPool threadPool = UnifiedTPRegulator.getResource(tpName);
if (threadPool == null) {
return false;
}
RejectStrategy rs;
try {
rs = (RejectStrategy) context.getBean(rsName);
} catch (NoSuchBeanDefinitionException e) {
if (!RSResourceManager.REJECT_STRATEGY_MAP.containsKey(rsName)) {
return false;
} else {
rs = (RejectStrategy) RSResourceManager.REJECT_STRATEGY_MAP.get(rsName).getConstructor().newInstance();
}
}
return threadPool.changeRejectStrategy(rs, rsName);
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/springboot_integration/monitor/controller/MonitorController.java | Java | mit | 6,960 |
package com.yf.springboot_integration.monitor.ws;
import com.yf.core.tp_regulator.UnifiedTPRegulator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
/**
* @author yyf
* @description
*/
@Slf4j
public class SchedulePushInfoService {
/**
*获取worker的信息
* return Map<String, Map<Thread.State, Integer>> worker信息,String只有两个值,第一个是core,第二个是extra,state代表线程状态,Integer代表对应类别的状态的数量
*/
@Scheduled(fixedDelayString = "${yf.thread-pool.monitor.fixedDelay}")
public void pushInfo() {
// 遍历所有线程池,按名称广播
UnifiedTPRegulator.getResources().forEach((tpName, threadPool) -> {
ThreadPoolWebSocketHandler.broadcastThreadPoolInfo(tpName, threadPool.getThreadsInfo());
ThreadPoolWebSocketHandler.broadcastTaskNums(tpName, threadPool.getTaskNums());
ThreadPoolWebSocketHandler.broadcastPartitionTaskNums(tpName, threadPool.getPartitionTaskNums());
});
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/springboot_integration/monitor/ws/SchedulePushInfoService.java | Java | mit | 1,085 |
package com.yf.springboot_integration.monitor.ws;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yf.common.constant.Logo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
/**
* @author yyf
* @description
*/
@Slf4j
public class ThreadPoolWebSocketHandler extends TextWebSocketHandler {
// 存储所有活跃的WebSocket会话
private static final Set<WebSocketSession> sessions = new CopyOnWriteArraySet<>();
private static final ObjectMapper objectMapper = new ObjectMapper();
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
// 新连接建立时添加会话
sessions.add(session);
System.out.println("新的WebSocket连接建立,当前连接数: " + sessions.size());
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
// 连接关闭时移除会话
sessions.remove(session);
System.out.println("WebSocket连接关闭,当前连接数: " + sessions.size());
}
// 新增:按线程池名称广播线程状态
public static void broadcastThreadPoolInfo(String tpName, Map<String, Map<Thread.State, Integer>> threadInfo) {
broadcastWithTpName(tpName, "threadInfo", threadInfo);
}
// 新增:按线程池名称广播任务数量
public static void broadcastTaskNums(String tpName, int nums) {
broadcastWithTpName(tpName, "taskNums", nums);
}
// 新增:按线程池名称广播分区任务数量
public static void broadcastPartitionTaskNums(String tpName, Map<Integer, Integer> partitionNums) {
broadcastWithTpName(tpName, "partitionTaskNums", partitionNums);
}
// 通用广播方法(包装线程池名称)
private static void broadcastWithTpName(String tpName, String type, Object data) {
if (sessions.isEmpty()) return;
try {
Map<String, Object> message = new HashMap<>();
message.put("tpName", tpName);
message.put("type", type);
message.put("data", data);
String json = objectMapper.writeValueAsString(message);
for (WebSocketSession session : sessions) {
if (session.isOpen()) {
session.sendMessage(new TextMessage(json));
}
}
} catch (IOException e) {
log.error("推送线程池[" + tpName + "]信息失败: " + e.getMessage());
}
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/springboot_integration/monitor/ws/ThreadPoolWebSocketHandler.java | Java | mit | 2,878 |
package com.yf.springboot_integration.pool.annotation;
import org.springframework.stereotype.Component;
import java.lang.annotation.*;
/**
* @author yyf
* @date 2025/10/6 17:18
* @description: GCTaskResource:用来标识
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface GCTResource {
String bindingPartiResource() default "";//绑定的分区的名称
String bindingSPResource() default "";//绑定的调度规则的名称
String spType() default "";//绑定的调度规则的类型
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/springboot_integration/pool/annotation/GCTResource.java | Java | mit | 566 |
package com.yf.springboot_integration.pool.annotation;
import org.springframework.stereotype.Component;
import java.lang.annotation.*;
/**
* @author yyf
* @description springboot环境下,扩展组件资源只需要加上当前包的注解就行了。
* 但是注意:虽然这个注解用了@Component但是并不意味着这个类会被spring容器,而是会注册到作者写的对应的各种resource_manager中
* 例如被当前这个注解标注就会自动在PartiResourceManager中注册,其原理是利用@Component注解借助springboot的扫描,使用了
* 工厂bean后处理器,用来获取资源的beanDefinition,然后注册到作者的资源管理器中,并且移除这个beanDefinition,这样springboot
* 就不会去创建和管理这个bean了
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface PartiResource {//分区资源注解
String value();// 队列名称
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/springboot_integration/pool/annotation/PartiResource.java | Java | mit | 976 |
package com.yf.springboot_integration.pool.annotation;
import org.springframework.stereotype.Component;
import java.lang.annotation.*;
/**
* @author yyf
* @description
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface RSResource {//拒绝策略资源注解
String value();//拒绝策略名称
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/springboot_integration/pool/annotation/RSResource.java | Java | mit | 364 |
package com.yf.springboot_integration.pool.annotation;
import org.springframework.stereotype.Component;
import java.lang.annotation.*;
/**
* @author yyf
* @description
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface SPResource {//调度规则资源注解
String value();
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/springboot_integration/pool/annotation/SPResource.java | Java | mit | 343 |
package com.yf.springboot_integration.pool.auto_configuration;
import com.yf.common.constant.Constant;
import com.yf.core.resource_manager.GCTaskManager;
import com.yf.core.resource_manager.PartiResourceManager;
import com.yf.core.resource_manager.RSResourceManager;
import com.yf.core.resource_manager.SPResourceManager;
import com.yf.core.rejectstrategy.RejectStrategy;
import com.yf.core.partitioning.impl.PartiFlow;
import com.yf.core.partition.Partition;
import com.yf.core.workerfactory.WorkerFactory;
import com.yf.core.threadpool.ThreadPool;
import com.yf.springboot_integration.pool.properties.LittleChiefProperties;
import com.yf.springboot_integration.pool.properties.QueueProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
/**
* @author yyf
* @description
*/
@Slf4j
@AutoConfiguration
@EnableConfigurationProperties({LittleChiefProperties.class, QueueProperties.class})
@ConditionalOnProperty(prefix = "yf.thread-pool.little-chief", name = "enabled", havingValue = "true")
public class LittleChiefAutoConfiguration {
/**
* 创建GC管理者中的littleChief
*/
@Bean(Constant.LITTLE_CHIEF)
public ThreadPool threadPool(LittleChiefProperties threadPoolProperties, QueueProperties queueProperties) throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
String queueName = queueProperties.getQueueName();
String rejectStrategyName = threadPoolProperties.getRejectStrategyName();
Partition partition;
RejectStrategy rejectStrategy;
if (!queueProperties.isPartitioning()) {//非分区化
Class<?> taskQueueClass = PartiResourceManager.getResources().get(queueName);
Constructor<?> queueClassConstructor = taskQueueClass.getConstructor();
partition = (Partition) queueClassConstructor.newInstance();
partition.setCapacity(queueProperties.getCapacity());
} else {//分区化
partition = new PartiFlow
(queueProperties.getPartitionNum(), queueProperties.getCapacity(), queueProperties.getQueueName(),
SPResourceManager.getOfferResource(queueProperties.getOfferPolicy()).getConstructor().newInstance(),
SPResourceManager.getPollResource(queueProperties.getPollPolicy()).getConstructor().newInstance(),
SPResourceManager.getRemoveResource(queueProperties.getRemovePolicy()).getConstructor().newInstance());
}
Class<?> rejectStrategyClass = RSResourceManager.REJECT_STRATEGY_MAP.get(rejectStrategyName);
Constructor<?> rejectStrategyClassConstructor = rejectStrategyClass.getConstructor();
rejectStrategy = (RejectStrategy) rejectStrategyClassConstructor.newInstance();
ThreadPool littleChief = new ThreadPool(
Constant.LITTLE_CHIEF,
threadPoolProperties.getCoreNums(),
threadPoolProperties.getMaxNums(),
Constant.LITTLE_CHIEF,
new WorkerFactory(threadPoolProperties.getThreadName(),
threadPoolProperties.isUseDaemon(),
true,//必须支持销毁核心线程
threadPoolProperties.getAliveTime(),
threadPoolProperties.isUseVirtualThread()
),
partition, rejectStrategy);
GCTaskManager.setLittleChief(littleChief);
return littleChief;
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/springboot_integration/pool/auto_configuration/LittleChiefAutoConfiguration.java | Java | mit | 3,849 |
package com.yf.springboot_integration.pool.auto_configuration;
import com.yf.common.constant.Logo;
import com.yf.springboot_integration.pool.post_processor.ResourceRegisterPostProcessor;
import com.yf.springboot_integration.pool.post_processor.TPRegisterPostProcessor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.annotation.Bean;
/**
* @author yyf
* @date 2025/10/6 21:49
* @description
*/
@Slf4j
@AutoConfiguration
public class PostProcessorAutoConfiguration {
@Bean
public ResourceRegisterPostProcessor registerPostProcessor() {
log.info(Logo.LOG_LOGO+"资源扫描器已经装配");
return new ResourceRegisterPostProcessor();
}
@Bean
public TPRegisterPostProcessor tpRegisterPostProcessor(DefaultListableBeanFactory beanFactory) {
log.info(Logo.LOG_LOGO+"线程池扫描器已经装配");
return new TPRegisterPostProcessor(beanFactory);
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/springboot_integration/pool/auto_configuration/PostProcessorAutoConfiguration.java | Java | mit | 1,076 |
package com.yf.springboot_integration.pool.post_processor;
import com.yf.common.constant.Constant;
import com.yf.common.constant.Logo;
import com.yf.core.partitioning.schedule_policy.OfferPolicy;
import com.yf.core.partitioning.schedule_policy.SchedulePolicy;
import com.yf.core.resource_manager.GCTaskManager;
import com.yf.core.resource_manager.PartiResourceManager;
import com.yf.core.resource_manager.RSResourceManager;
import com.yf.core.resource_manager.SPResourceManager;
import com.yf.core.partition.Partition;
import com.yf.core.rejectstrategy.RejectStrategy;
import com.yf.springboot_integration.pool.annotation.GCTResource;
import com.yf.springboot_integration.pool.annotation.PartiResource;
import com.yf.springboot_integration.pool.annotation.RSResource;
import com.yf.springboot_integration.pool.annotation.SPResource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import java.util.ArrayList;
import java.util.List;
/**
* @author yyf
* @description: 用来处理被作者定义的注解所标注的开发者扩展资源
*/
@Slf4j
public class ResourceRegisterPostProcessor implements BeanDefinitionRegistryPostProcessor {
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
// 1. 获取Spring扫描到的所有Bean名称(复用Spring自身的扫描结果)
String[] beanDefinitionNames = registry.getBeanDefinitionNames();
List<String> gctBeanNames = new ArrayList<>();
for (String beanName : beanDefinitionNames) {
BeanDefinition beanDefinition = registry.getBeanDefinition(beanName);
String className = beanDefinition.getBeanClassName();
if (className == null) continue;
try {
// 2. 加载类,判断是否被@PartitionBean注解
Class<?> clazz = Class.forName(className);
PartiResource partiResource = clazz.getAnnotation(PartiResource.class);
RSResource RSResource = clazz.getAnnotation(RSResource.class);
SPResource SPResource = clazz.getAnnotation(SPResource.class);
GCTResource gctResource = clazz.getAnnotation(GCTResource.class);
if (partiResource != null) {//分区资源
// 3. 注册到自定义中心
PartiResourceManager.register(partiResource.value(), clazz.asSubclass(Partition.class));
log.info(Logo.LOG_LOGO +"开发者自定义队列:"+ partiResource.value()+"注册成功!");
// 4. 从Spring容器中移除该Bean定义
registry.removeBeanDefinition(beanName);
}
else if (RSResource != null) {//拒绝策略资源
// 3. 注册到自定义中心
RSResourceManager.register(RSResource.value(), clazz.asSubclass(RejectStrategy.class));
log.info(Logo.LOG_LOGO +"开发者自定义拒绝策略:"+ RSResource.value()+"注册成功!");
// 4. 从Spring容器中移除该Bean定义
registry.removeBeanDefinition(beanName);
} else if (SPResource !=null) {//调度规则资源
// 3. 注册到自定义中心
SPResourceManager.register(SPResource.value(), clazz);
log.info(Logo.LOG_LOGO +"开发者自定义调度规则:"+ SPResource.value()+"注册成功!");
registry.removeBeanDefinition(beanName);
} else if (gctResource != null){//GC任务资源
//放到list中等到所有的bean扫描完了再处理
gctBeanNames.add(beanName);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
for (String gctBeanName : gctBeanNames) {
BeanDefinition beanDefinition = registry.getBeanDefinition(gctBeanName);
String className = beanDefinition.getBeanClassName();
if (className == null) continue;
Class<?> clazz = null;
try {
clazz = Class.forName(className);
GCTResource gctResource = clazz.getAnnotation(GCTResource.class);
//得到绑定资源的名称
String partiName = gctResource.bindingPartiResource();
String spName = gctResource.bindingSPResource();
//从自定义中心中获取对应的资源类
Class<? extends Partition> parti = PartiResourceManager.getResource(partiName);
Class<? extends SchedulePolicy> spResource;
if(gctResource.spType().equals(Constant.POLL)){
spResource = SPResourceManager.getPollResource(spName);
} else if (gctResource.spType().equals(Constant.OFFER)) {
spResource= SPResourceManager.getOfferResource(spName);
}else{
spResource = SPResourceManager.getRemoveResource(spName);
}
registerGCExecutorManager(spResource,clazz,spName);
registerGCExecutorManager(parti,clazz,partiName);
registry.removeBeanDefinition(gctBeanName);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
}
public void registerGCExecutorManager(Class resource, Class taskClazz,String name){
if(resource ==null){
return;
}
GCTaskManager.register(resource,taskClazz);
log.info(Logo.LOG_LOGO +"开发者自定义任务注册成功,绑定资源:"+name);
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/springboot_integration/pool/post_processor/ResourceRegisterPostProcessor.java | Java | mit | 6,190 |
package com.yf.springboot_integration.pool.post_processor;
import com.yf.common.constant.Constant;
import com.yf.core.threadpool.ThreadPool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import java.util.Map;
/**
* @author yyf
* @description: 用来注册所有的线程池(会去除掉bean容器中的little chief小线程池,开发者定义的不会去除)
*/
@Slf4j
public class TPRegisterPostProcessor implements SmartInitializingSingleton {
private final DefaultListableBeanFactory beanFactory;
// 构造器注入BeanFactory(Spring自动提供)
public TPRegisterPostProcessor(DefaultListableBeanFactory beanFactory) {
this.beanFactory = beanFactory;
}
@Override
public void afterSingletonsInstantiated() {
Map<String, ThreadPool> tpBeans = beanFactory.getBeansOfType(ThreadPool.class);
for(ThreadPool tp : tpBeans.values()){
String tpName = tp.getName();
if(tpName.equals(Constant.LITTLE_CHIEF)){
//说明是gc任务中的线程池,不能被springboot管理
beanFactory.destroySingleton(tpName);
// 3.2 删除Spring中的Bean定义(后续不会再创建)
if (beanFactory.containsBeanDefinition(tpName)) {
beanFactory.removeBeanDefinition(tpName);
}
}
}
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/springboot_integration/pool/post_processor/TPRegisterPostProcessor.java | Java | mit | 1,516 |
package com.yf.springboot_integration.pool.properties;
import lombok.Data;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* @author yyf
* @description
*/
@Data
@ConditionalOnProperty(prefix = "yf.thread-pool.little-chief",name = "enabled",havingValue = "true")
@ConfigurationProperties(prefix = "yf.thread-pool.little-chief")
public class LittleChiefProperties {
private boolean useVirtualThread;//是否使用虚拟线程
private Integer coreNums;//核心线程数
private Integer maxNums;//最大线程数
private String threadName;//线程名称
private boolean useDaemon;//是否守护线程
private Integer aliveTime;//线程空闲时间
private String rejectStrategyName;//拒绝策略名称
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/springboot_integration/pool/properties/LittleChiefProperties.java | Java | mit | 845 |
package com.yf.springboot_integration.pool.properties;
import lombok.Data;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* @author yyf
* @date 2025/8/21 17:40
* @description
*/
@ConditionalOnProperty(prefix = "yf.thread-pool.pool",name = "enabled",havingValue = "true")
@ConfigurationProperties(prefix = "yf.thread-pool.queue")
@Data
public class QueueProperties {
// 是否分区化(如果是false,只需要读取capacity和queueName)
private boolean partitioning;
// 分区数量
private Integer partitionNum;
// 队列容量(null表示无界)
private Integer capacity;
// 队列名称
private String queueName;
// 入队策略
private String offerPolicy;
// 出队策略
private String pollPolicy;
// 移除策略
private String removePolicy;
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/springboot_integration/pool/properties/QueueProperties.java | Java | mit | 936 |
package com.yf.test_or_explore_springboot_integration;
import com.yf.core.threadpool.ThreadPool;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import java.util.Map;
/**
* @author yyf
* @description
*/
@EnableScheduling
@SpringBootApplication
public class Start {
public static void main(String[] args) {
ConfigurableApplicationContext run = SpringApplication.run(Start.class, args);
//命令行启动的流程 springboot环境不建议,建议用可视化界面。
Map<String, ThreadPool> beansOfType = run.getBeansOfType(ThreadPool.class);
// new Thread(()->{
// for(ThreadPool threadPool:beansOfType.values()){
// if(threadPool.getName().equals("TP-ThreadPool1")){
// //io类型线程池,设置io任务,一次100个任务
// while(true) {
// for (int i = 0; i < 100; i++) {
// threadPool.execute(new Runnable() {
// @Override
// public void run() {
// try {
// Thread.sleep(700);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
// });
// }
// }
// }
// }
// },"io线程池").start();
// new Thread(()->{
// for(ThreadPool threadPool:beansOfType.values()){
// if(threadPool.getName().equals("TP-ThreadPool2")){
// //cpu类型线程池,设置cpu任务,一次50个任务
// while(true) {
// for (int i = 0; i < 50; i++) {
// threadPool.execute(new Runnable() {
// @Override
// public void run() {
// // 模拟CPU密集型计算(如复杂运算、数据处理)
// long result = 0;
// for (long j = 0; j < 10_000_000L; j++) { // 大量循环计算
// result += j;
// }
// // 避免JIT优化掉无意义计算(可选)
// if (result < 0) {
// System.out.print("");
// }
// }
// });
// }
// }
// }
// }
// },"cpu线程池").start();
//
// PoolCommandHandler poolCommandHandler = new PoolCommandHandler();
// poolCommandHandler.start();
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/test_or_explore_springboot_integration/Start.java | Java | mit | 3,167 |
package com.yf.test_or_explore_springboot_integration.ai_explore.config;
import jakarta.annotation.PostConstruct;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.document.Document;
import org.springframework.ai.reader.TextReader;
import org.springframework.ai.transformer.splitter.TokenTextSplitter;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Set;
/**
* @author yyf
* @date 2025/10/8 18:13
* @description
*/
@ConditionalOnProperty(prefix = "yf.thread-pool.ai", name ="enabled",havingValue = "true")
@Configuration
public class CentralConfig {
@Value("classpath:base_knowledge.txt")
private Resource knowledge;
@Value("classpath:io.txt")
private Resource io;
@Value("classpath:cpu.txt")
private Resource cpu;
@Autowired
private VectorStore vectorStore;
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Value("${spring.ai.vectorstore.redis.prefix}")
private String redisPrefix;
public static final String NOT_TRAIN_SYSTEM_INFO =
"你是个线程池调控参数的非训练模式下的助手,你需要根据用户发送给你的负载情况和知识文档决定是否进行调控,以下是负载信息的说明" +
"负载信息是key value都是String类型的Map,获得的是内存使用率和各个线程池负载," +
"除了memoryUsage,其他key冒号前面的是线程池的名字\n";
public static final String TRAIN_SYSTEM_INFO =
"你是个线程池调控参数的训练模式下的助手,你需要根据用户发送给你的负载情况和知识文档决定是否进行调控,以下是负载信息的说明" +
"负载信息是key value都是String类型的Map,获得的是内存使用率和各个线程池负载," +
"除了memoryUsage,其他key冒号前面的是线程池的名字;" +
"另外如果你进行了调控,你还需要调用writeToRag方法\n";
@Bean
public ChatClient chatClient(ChatModel chatModel) {
return ChatClient.builder(chatModel)
.build();
}
@PostConstruct
public void init(){
//0删除之前的rag文档,按照前缀删除
String pattern = redisPrefix + "*";
// 获取所有匹配前缀的键
Set<String> keys = stringRedisTemplate.keys(pattern);
if (keys != null && !keys.isEmpty()) {
// 批量删除匹配的键
Long deleted = stringRedisTemplate.delete(keys);
System.out.println("删除了" + deleted + "个前缀为" + redisPrefix + "的文档");
}
//1 读取文件
TextReader knowledgeTextReader = new TextReader(knowledge);
knowledgeTextReader.setCharset(Charset.defaultCharset());
TextReader ioTextReader = new TextReader(io);
ioTextReader.setCharset(Charset.defaultCharset());
TextReader cpuTextReader = new TextReader(cpu);
cpuTextReader.setCharset(Charset.defaultCharset());
//2 文件内容转换为向量(开启分词)
List<Document> knledgeList = new TokenTextSplitter().transform(knowledgeTextReader.read());
List<Document> ioList = new TokenTextSplitter().transform(ioTextReader.read());
List<Document> cpuList = new TokenTextSplitter().transform(cpuTextReader.read());
//3 写入向量数据库
vectorStore.add(knledgeList);
vectorStore.add(ioList);
vectorStore.add(cpuList);
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/test_or_explore_springboot_integration/ai_explore/config/CentralConfig.java | Java | mit | 4,067 |
package com.yf.test_or_explore_springboot_integration.ai_explore.schedule;
import com.yf.test_or_explore_springboot_integration.ai_explore.config.CentralConfig;
import com.yf.test_or_explore_springboot_integration.ai_explore.tools.RegulateTools;
import jakarta.annotation.Resource;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.rag.advisor.RetrievalAugmentationAdvisor;
import org.springframework.ai.rag.retrieval.search.VectorStoreDocumentRetriever;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import static com.yf.test_or_explore_springboot_integration.ai_explore.utils.Utils.getLoad;
/**
* @author yyf
* @date 2025/10/8 18:20
* @description
*/
@Component
@ConditionalOnProperty(prefix = "yf.thread-pool.ai", name = "enabled", havingValue = "true")
public class RegulateRequestToModel {
@Resource
private ChatClient chatClient;
@Resource
private VectorStore vectorStore;
@Value("${yf.thread-pool.ai.training}")
private boolean isTrainingMode;
@Scheduled(fixedDelayString = "${yf.thread-pool.ai.fixedDelay}")
public void ask(){
System.out.println("=======~~~~~~~~~~~~开始请求模型~~~~~~~~~~~~=============");
RetrievalAugmentationAdvisor advisor = RetrievalAugmentationAdvisor.builder()
.documentRetriever(VectorStoreDocumentRetriever.builder().vectorStore(vectorStore).build())
.build();
String message;
if(isTrainingMode){
message = CentralConfig.TRAIN_SYSTEM_INFO;
}else{
message = CentralConfig.NOT_TRAIN_SYSTEM_INFO;
}
String s = chatClient.prompt().system(message)
.user(getLoad().toString()).tools(new RegulateTools()).advisors(advisor).call().content();
System.out.println(s);
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/test_or_explore_springboot_integration/ai_explore/schedule/RegulateRequestToModel.java | Java | mit | 2,085 |
package com.yf.test_or_explore_springboot_integration.ai_explore.tools;
import java.util.Map;
/**
* @author yyf
* @date 2025/10/9 16:46
* @description
*/
public class RegulateInformation {
Map<String,String> load;
String toolName;
Map<String,String> params;
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/test_or_explore_springboot_integration/ai_explore/tools/RegulateInformation.java | Java | mit | 278 |
package com.yf.test_or_explore_springboot_integration.ai_explore.tools;
import com.yf.core.tp_regulator.UnifiedTPRegulator;
import com.yf.test_or_explore_springboot_integration.ai_explore.utils.Utils;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* @author yyf
* @date 2025/10/9 14:38
* @description
*/
@Component
public class RegulateTools {
@Value("${yf.thread-pool.ai.training}")
private boolean isTrainingMode;
@Tool(description = "获取线程池的类型,建议调控之前先了解类型。类型代表着线程池中任务的类型,类型主要分为两种1 cpu,2 io 如果不是这两种,那么就代表线程池没有固定哪种类型。")
public String getPoolType(String poolName){
System.out.println("~~~~~~~~~~~·使用了");
return UnifiedTPRegulator.getResource(poolName).getType();
}
@Tool(description = "调控线程数量,返回值代表成功与否")
public boolean regulateWorker(String poolName,Integer coreNums, Integer maxNums,Integer aliveTime) {
System.out.println("~~~~~~~~~~~·使用了");
return UnifiedTPRegulator.changeWorkerParams(poolName, coreNums, maxNums, null, aliveTime, null);
}
@Tool(description = "调控队列长短")
public void regulateQueue(String poolName,Integer queueCapacity) {
System.out.println("~~~~~~~~~~~·使用了");
UnifiedTPRegulator.changeQueueCapacity(poolName, queueCapacity);
}
@Tool(description = "将调控的信息写入rag数据库,第二个参数的load成员代表这次用户发送给你的的负载信息;" +
"toolName代表你使用的调控工具名称没有使用就不用写;" +
"params的key代表你设置的参数名,value代表你设置的具体的值,没有使用调控工具就不用写")
public void writeToRag(String type,RegulateInformation information){
System.out.println("~~~~~~~~~~~·使用了writeToRag");
if (type == null || !("cpu".equals(type) || "io".equals(type)) || information == null) {
return;
}
// 仅训练模式开启时写入
if (!isTrainingMode) {
return;
}
Utils.writeToRag(type,information);
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/test_or_explore_springboot_integration/ai_explore/tools/RegulateTools.java | Java | mit | 2,360 |
package com.yf.test_or_explore_springboot_integration.ai_explore.utils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yf.core.threadpool.ThreadPool;
import com.yf.core.tp_regulator.UnifiedTPRegulator;
import com.yf.test_or_explore_springboot_integration.ai_explore.tools.RegulateInformation;
import org.springframework.ai.document.Document;
import org.springframework.ai.reader.TextReader;
import org.springframework.ai.transformer.splitter.TokenTextSplitter;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author yyf
* @date 2025/10/9 16:33
* @description
*/
@Component
@ConditionalOnProperty(prefix = "yf.thread-pool.ai", name ="enabled",havingValue = "true")
public class Utils {
private static VectorStore vectorStore;
private static ResourceLoader resourceLoader;
private static final ObjectMapper objectMapper = new ObjectMapper();
private static final TokenTextSplitter textSplitter = new TokenTextSplitter();
// 注入Spring管理的Bean到静态变量
@Autowired
public void setDependencies(VectorStore vectorStore, ResourceLoader resourceLoader) {
Utils.vectorStore = vectorStore;
Utils.resourceLoader = resourceLoader;
}
public static Map<String, String> getLoad(){
Map<String, String> map = new HashMap<>();
double memoryUsage = (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) * 100.0 / Runtime.getRuntime().maxMemory();;
map.put("memoryUsage", String.valueOf(memoryUsage));
for(Map.Entry<String, ThreadPool> entry: UnifiedTPRegulator.getResources().entrySet()){
ThreadPool threadPool = entry.getValue();
String name = entry.getKey();
int taskNums = threadPool.getPartition().getEleNums();
map.put(name+":taskNums", String.valueOf(taskNums));
Integer capacity = threadPool.getPartition().getCapacity();
map.put(name+":queueCapacity", String.valueOf(capacity));
}
return map;
}
/**
* 将调控信息写入RAG系统(向量数据库和对应类型文件)
* @param type 线程池类型(cpu/io)
* @param information 调控信息对象
*/
public static void writeToRag(String type, RegulateInformation information) {
if (type == null || !("cpu".equals(type) || "io".equals(type)) || information == null) {
throw new IllegalArgumentException("无效的类型或调控信息");
}
File tempFile = null;
try {
// 1. 将调控信息转换为JSON字符串
String jsonContent = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(information);
// 2. 创建临时文件并写入JSON数据
tempFile = File.createTempFile("regulate-"+type+"-", ".json");
Files.write(tempFile.toPath(), jsonContent.getBytes(StandardCharsets.UTF_8),
StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
// 3. 将临时文件内容写入向量数据库
TextReader textReader = new TextReader(new FileSystemResource(tempFile));
textReader.setCharset(StandardCharsets.UTF_8);
List<Document> documents = textSplitter.transform(textReader.read());
vectorStore.add(documents);
// 4. 将JSON数据追加到对应的类型文件(cpu.txt或io.txt)
appendToTypeFile(type, jsonContent);
} catch (Exception e) {
throw new RuntimeException("处理调控信息时发生错误", e);
} finally {
// 清理临时文件
if (tempFile != null && tempFile.exists()) {
if (!tempFile.delete()) {
tempFile.deleteOnExit(); // 确保程序退出时删除
}
}
}
}
/**
* 将JSON内容追加到对应的类型文件
* @param type 线程池类型(cpu/io)
* @param jsonContent 要追加的JSON内容
*/
private static void appendToTypeFile(String type, String jsonContent) throws IOException {
String fileName = type + ".txt";
Resource resource = resourceLoader.getResource("classpath:" + fileName);
// 构建追加内容(添加时间戳和分隔符)
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String timestamp = "// 调控时间: " + LocalDateTime.now().format(formatter) + "\n";
String contentToAppend = timestamp + jsonContent + "\n\n";
// 处理文件写入
if (resource.exists() && resource.isFile()) {
// 直接写入现有文件
Files.write(Path.of(resource.getURI()),
contentToAppend.getBytes(StandardCharsets.UTF_8),
StandardOpenOption.APPEND);
} else {
// 资源不存在或在JAR包内,写入外部目录
File externalDir = new File("src/main/resources");
if (!externalDir.exists()) {
externalDir.mkdirs();
}
File externalFile = new File(externalDir, fileName);
Files.write(externalFile.toPath(),
contentToAppend.getBytes(StandardCharsets.UTF_8),
StandardOpenOption.CREATE, StandardOpenOption.APPEND);
}
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/test_or_explore_springboot_integration/ai_explore/utils/Utils.java | Java | mit | 6,049 |
package com.yf.test_or_explore_springboot_integration.service_registry;
import com.yf.common.constant.Logo;
import com.yf.core.threadpool.ThreadPool;
import com.yf.core.tp_regulator.UnifiedTPRegulator;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* @author yyf
* @date 2025/8/20 0:20
* @description
*/
@Component
@ConditionalOnProperty(prefix = "yf.thread-pool.service-registry", name = "enabled", havingValue = "true")
public class ServiceRegistryHandler {
// 每个节点信息包含字段:ip、port、memoryUsage(内存使用率)、taskNums(任务数量)、queueCapacity(队列大小)
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
private ResourceLoader resourceLoader;
@Autowired
private ServerProperties serverProperties;
private static String IP;
private static String PORT;
private static String KEY;
//redis中的key
private final static String REGISTRY_KEY_PREFIX = "task_flow:registry";//基础信息注册 hash 真正的key是前缀加节点的ip和进程号
private final static String SORT_BY_MEMORY = "task_flow:sort:memoryUsage";//节点按内存使用率排序
private final static String SORT_BY_QUEUE = "task_flow:sort:queueUsage";//节点按队列使用率排序
private final static List<String> zsetKeys = Arrays.asList(SORT_BY_MEMORY, SORT_BY_QUEUE);
// Lua脚本
DefaultRedisScript<Long> redisScript;
@Value("${yf.thread-pool.service-registry.expireTime}")
private static int EXPIRE;
public ServiceRegistryHandler(StringRedisTemplate srt, ResourceLoader rl, ServerProperties sp) {
this.stringRedisTemplate = srt;
this.resourceLoader = rl;
this.serverProperties = sp;
IP = serverProperties.getAddress().getHostAddress();
PORT = serverProperties.getPort().toString();
KEY = REGISTRY_KEY_PREFIX+":"+IP+ ":"+ PORT;
}
@PostConstruct
public void firstRegister(){//启动服务,向redis进行注册
register();
Runtime.getRuntime().addShutdownHook(new Thread(() -> {//进程退出时,删除redis中hash的key 以及zset的元素
stringRedisTemplate.opsForHash().delete(KEY,"ip", "port", "memoryUsage", "taskNums", "queueCapacity");
stringRedisTemplate.opsForZSet().remove(SORT_BY_MEMORY,KEY);
stringRedisTemplate.opsForZSet().remove(SORT_BY_QUEUE,KEY);
}));
// 加载并预编译Lua脚本
loadAndPrecompileLuaScript();
}
@Scheduled(fixedDelayString = "${yf.thread-pool.service-registry.heartBeat}")
public void heartBeating(){//心跳机制
register();
//清理ZSet中无效元素
stringRedisTemplate.execute(
redisScript,
zsetKeys
);
System.out.println(Logo.LOG_LOGO +"beating....");
}
public void register(){//注册服务
for(ThreadPool threadPool: UnifiedTPRegulator.getResources().values()) {
Map<String, String> map = getEnvironment(threadPool);
double memoryUsage = Double.parseDouble(map.get("memoryUsage"));
int taskNums = threadPool.getTaskNums();
Integer capacity = threadPool.getPartition().getCapacity();
stringRedisTemplate.opsForHash().putAll(KEY, map);
stringRedisTemplate.expire(KEY, EXPIRE, TimeUnit.SECONDS);
stringRedisTemplate.opsForZSet().add(SORT_BY_MEMORY, KEY, memoryUsage);
stringRedisTemplate.opsForZSet().add(SORT_BY_QUEUE, KEY, capacity == null ? 0 : (double) taskNums / capacity);
stringRedisTemplate.expire(SORT_BY_MEMORY, EXPIRE, TimeUnit.SECONDS);
stringRedisTemplate.expire(SORT_BY_QUEUE, EXPIRE, TimeUnit.SECONDS);
}
}
public static Map<String,String> getEnvironment(ThreadPool threadPool){
Map<String, String> map = new HashMap<>();
map.put("ip", IP);
map.put("port", PORT);
double memoryUsage = (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) * 100.0 / Runtime.getRuntime().maxMemory();;
map.put("memoryUsage", String.valueOf(memoryUsage));
int taskNums = threadPool.getPartition().getEleNums();
map.put("taskNums", String.valueOf(taskNums));
Integer capacity = threadPool.getPartition().getCapacity();
map.put("queueCapacity", String.valueOf(capacity));
return map;
}
//加载并预编译Lua脚本
private void loadAndPrecompileLuaScript() {
try {
// 加载resources目录下的Lua脚本文件
Resource resource = resourceLoader.getResource("classpath:lua/cleanup_zset.lua");
byte[] scriptBytes = FileCopyUtils.copyToByteArray(resource.getInputStream());
redisScript = new DefaultRedisScript<>(new String(scriptBytes, StandardCharsets.UTF_8), Long.class);
} catch (IOException e) {
throw new RuntimeException("lua脚本加载失败", e);
}
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/test_or_explore_springboot_integration/service_registry/ServiceRegistryHandler.java | Java | mit | 5,871 |
package com.yf.test_or_explore_springboot_integration.test_resource.q;
import com.yf.core.partition.Partition;
import com.yf.springboot_integration.pool.annotation.PartiResource;
/**
* @author yyf
* @description
*/
@PartiResource("myq")
public class myq extends Partition {
@Override
public boolean offer(Object t) {
return false;
}
@Override
public Runnable poll(Integer waitTime) throws InterruptedException {
return null;
}
@Override
public Boolean removeEle() {
return null;
}
@Override
public int getEleNums() {
return 0;
}
@Override
public void lockGlobally() {
}
@Override
public void unlockGlobally() {
}
@Override
public Integer getCapacity() {
return 0;
}
@Override
public void setCapacity(Integer capacity) {
}
@Override
public void markAsSwitched() {
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/test_or_explore_springboot_integration/test_resource/q/myq.java | Java | mit | 935 |
package com.yf.test_or_explore_springboot_integration.test_resource.q;
import com.yf.springboot_integration.pool.annotation.PartiResource;
import com.yf.core.partition.Partition;
/**
* @author yyf
* @description
*/
@PartiResource("myqn")
public class myqn extends Partition {
@Override
public boolean offer(Object t) {
return false;
}
@Override
public Runnable poll(Integer waitTime) throws InterruptedException {
return null;
}
@Override
public Boolean removeEle() {
return null;
}
@Override
public int getEleNums() {
return 0;
}
@Override
public void lockGlobally() {
}
@Override
public void unlockGlobally() {
}
@Override
public Integer getCapacity() {
return 0;
}
@Override
public void setCapacity(Integer capacity) {
}
@Override
public void markAsSwitched() {
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/test_or_explore_springboot_integration/test_resource/q/myqn.java | Java | mit | 935 |
package com.yf.test_or_explore_springboot_integration.test_resource.s;
import com.yf.core.rejectstrategy.RejectStrategy;
import com.yf.core.threadpool.ThreadPool;
import com.yf.springboot_integration.pool.annotation.RSResource;
/**
* @author yyf
* @description
*/
@RSResource("mys")
public class mys extends RejectStrategy {
@Override
public void reject(ThreadPool threadPool,Runnable task) {
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/test_or_explore_springboot_integration/test_resource/s/mys.java | Java | mit | 415 |
package com.yf.test_or_explore_springboot_integration.test_resource.s;
import com.yf.core.rejectstrategy.RejectStrategy;
import com.yf.core.threadpool.ThreadPool;
/**
* @author yyf
* @description
*/
public class myst extends RejectStrategy {
@Override
public void reject(ThreadPool threadPool,Runnable task) {
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/test_or_explore_springboot_integration/test_resource/s/myst.java | Java | mit | 333 |
package com.yf.test_or_explore_springboot_integration.test_resource.sp;
import com.yf.core.partitioning.schedule_policy.OfferPolicy;
import com.yf.core.partition.Partition;
import com.yf.springboot_integration.pool.annotation.SPResource;
/**
* @author yyf
* @date 2025/9/21 0:57
* @description
*/
@SPResource("mysp")
public class mysp extends OfferPolicy {
@Override
public int selectPartition(Partition[] partitions, Object object) {
return 0;
}
@Override
public boolean getRoundRobin() {
return false;
}
@Override
public void setRoundRobin(boolean roundRobin) {
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/test_or_explore_springboot_integration/test_resource/sp/mysp.java | Java | mit | 630 |
package com.yf.test_or_explore_springboot_integration.test_resource.task;
import com.yf.common.constant.Constant;
import com.yf.common.task.GCTask;
import com.yf.core.partition.Partition;
import com.yf.core.threadpool.ThreadPool;
import com.yf.springboot_integration.pool.annotation.GCTResource;
/**
* @author yyf
* @date 2025/10/6 19:07
* @description
*/
@GCTResource(bindingPartiResource = "myq",bindingSPResource = "thread_binding",spType = Constant.POLL)
public class t extends GCTask {
@Override
public void run() {
ThreadPool threadPool = getThreadPool();
Partition<?> partition = getPartition();
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/test_or_explore_springboot_integration/test_resource/task/t.java | Java | mit | 644 |
package com.yf.test_or_explore_springboot_integration.thread_pool;
import com.yf.common.constant.Constant;
import com.yf.core.partition.Impl.LinkedBlockingQ;
import com.yf.core.rejectstrategy.impl.CallerRunsStrategy;
import com.yf.core.threadpool.ThreadPool;
import com.yf.core.workerfactory.WorkerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author yyf
* @date 2025/10/6 20:34
* @description
*/
@Configuration
public class TPConfig {
@Bean
public ThreadPool threadPool1(){
return new ThreadPool(
Constant.IO,
5,
10,
"TP-ThreadPool1",
new WorkerFactory("", false, true, 10),
new LinkedBlockingQ<Runnable>(50),
new CallerRunsStrategy()
);
}
@Bean
public ThreadPool threadPool2(){
return new ThreadPool(
Constant.CPU,
5,
10,
"TP-ThreadPool2",
new WorkerFactory("", false, true, 10),
new LinkedBlockingQ<Runnable>(50),
new CallerRunsStrategy()
);
}
}
| 2401_82379797/DGA-Pool | src/main/java/com/yf/test_or_explore_springboot_integration/thread_pool/TPConfig.java | Java | mit | 1,219 |