CacheController.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. <?php
  2. namespace App\Module\Admin\AdminControllers;
  3. use App\Module\Admin\Enums\ADMIN_ACTION_TYPE;
  4. use App\Module\Admin\Enums\CACHE_TYPE;
  5. use App\Module\Admin\Services\AdminService;
  6. use App\Module\Admin\Services\CacheService;
  7. use Dcat\Admin\Grid;
  8. use Dcat\Admin\Layout\Content;
  9. use Dcat\Admin\Widgets\Card;
  10. use Dcat\Admin\Widgets\Tab;
  11. use Illuminate\Http\Request;
  12. use Spatie\RouteAttributes\Attributes\Get;
  13. use Spatie\RouteAttributes\Attributes\Post;
  14. use Spatie\RouteAttributes\Attributes\Resource;
  15. use UCore\DcatAdmin\AdminController;
  16. /**
  17. * 缓存管理控制器
  18. */
  19. #[Resource('admin-cache', names: 'admin.cache')]
  20. class CacheController extends AdminController
  21. {
  22. protected $title = '缓存管理';
  23. /**
  24. * @var CacheService
  25. */
  26. protected CacheService $cacheService;
  27. /**
  28. * @var AdminService
  29. */
  30. protected AdminService $adminService;
  31. public function __construct()
  32. {
  33. $this->cacheService = app('admin.cache');
  34. $this->adminService = app('admin.service');
  35. }
  36. /**
  37. * 缓存管理首页
  38. *
  39. * @param Content $content
  40. * @return Content
  41. */
  42. public function index(Content $content): Content
  43. {
  44. return $content
  45. ->title($this->title)
  46. ->description('缓存状态管理')
  47. ->body($this->buildCacheManagement());
  48. }
  49. /**
  50. * 构建缓存管理界面
  51. *
  52. * @return Tab
  53. */
  54. protected function buildCacheManagement(): Tab
  55. {
  56. $tab = new Tab();
  57. // 缓存状态标签页
  58. $tab->add('缓存状态', $this->buildCacheStatusCard());
  59. // 缓存操作标签页
  60. $tab->add('缓存操作', $this->buildCacheActionsCard());
  61. // 缓存统计标签页
  62. $tab->add('缓存统计', $this->buildCacheStatisticsCard());
  63. return $tab;
  64. }
  65. /**
  66. * 构建缓存状态卡片
  67. *
  68. * @return Card
  69. */
  70. protected function buildCacheStatusCard(): Card
  71. {
  72. $status = $this->cacheService->getStatus();
  73. $html = '<div class="row">';
  74. foreach ($status as $typeStatus) {
  75. $statusClass = $typeStatus['status'] === 'healthy' ? 'success' : 'danger';
  76. $statusText = $typeStatus['status'] === 'healthy' ? '正常' : '异常';
  77. $html .= '<div class="col-md-4 mb-3">';
  78. $html .= '<div class="card">';
  79. $html .= '<div class="card-body">';
  80. $html .= "<h5 class=\"card-title\">{$typeStatus['label']}</h5>";
  81. $html .= "<span class=\"badge badge-{$statusClass}\">{$statusText}</span>";
  82. $html .= "<p class=\"card-text mt-2\">{$typeStatus['description']}</p>";
  83. if (isset($typeStatus['ttl'])) {
  84. $html .= "<small class=\"text-muted\">TTL: {$typeStatus['ttl']}秒</small><br>";
  85. }
  86. if (isset($typeStatus['tags'])) {
  87. $tags = implode(', ', $typeStatus['tags']);
  88. $html .= "<small class=\"text-muted\">标签: {$tags}</small>";
  89. }
  90. if (isset($typeStatus['error'])) {
  91. $html .= "<div class=\"text-danger mt-2\">{$typeStatus['error']}</div>";
  92. }
  93. $html .= '</div>';
  94. $html .= '</div>';
  95. $html .= '</div>';
  96. }
  97. $html .= '</div>';
  98. return new Card('缓存状态', $html);
  99. }
  100. /**
  101. * 构建缓存操作卡片
  102. *
  103. * @return Card
  104. */
  105. protected function buildCacheActionsCard(): Card
  106. {
  107. $html = '<div class="row">';
  108. // 全部清理按钮
  109. $html .= '<div class="col-md-12 mb-3">';
  110. $html .= '<button type="button" class="btn btn-danger" onclick="clearAllCache()">';
  111. $html .= '<i class="fa fa-trash"></i> 清理所有缓存';
  112. $html .= '</button>';
  113. $html .= '</div>';
  114. // 按类型清理
  115. $html .= '<div class="col-md-12">';
  116. $html .= '<h5>按类型清理</h5>';
  117. $html .= '<div class="row">';
  118. foreach (CACHE_TYPE::cases() as $type) {
  119. $buttonClass = $type->isSafeToClear() ? 'btn-warning' : 'btn-danger';
  120. $safeText = $type->isSafeToClear() ? '(安全)' : '(谨慎)';
  121. $html .= '<div class="col-md-3 mb-2">';
  122. $html .= "<button type=\"button\" class=\"btn {$buttonClass} btn-sm\" onclick=\"clearCacheByType('{$type->value}')\">";
  123. $html .= "<i class=\"fa fa-broom\"></i> {$type->getLabel()} {$safeText}";
  124. $html .= '</button>';
  125. $html .= '</div>';
  126. }
  127. $html .= '</div>';
  128. $html .= '</div>';
  129. // 预热缓存
  130. $html .= '<div class="col-md-12 mt-3">';
  131. $html .= '<h5>缓存预热</h5>';
  132. $html .= '<button type="button" class="btn btn-primary" onclick="warmupCache()">';
  133. $html .= '<i class="fa fa-fire"></i> 预热缓存';
  134. $html .= '</button>';
  135. $html .= '</div>';
  136. $html .= '</div>';
  137. // 添加JavaScript
  138. $html .= $this->getCacheManagementScript();
  139. return new Card('缓存操作', $html);
  140. }
  141. /**
  142. * 构建缓存统计卡片
  143. *
  144. * @return Card
  145. */
  146. protected function buildCacheStatisticsCard(): Card
  147. {
  148. $statistics = $this->cacheService->getStatistics();
  149. $html = '<div class="row">';
  150. $html .= '<div class="col-md-6">';
  151. $html .= '<table class="table table-bordered">';
  152. $html .= '<tr><th>缓存驱动</th><td>' . ($statistics['driver'] ?? 'Unknown') . '</td></tr>';
  153. $html .= '<tr><th>缓存类型总数</th><td>' . ($statistics['total_types'] ?? 0) . '</td></tr>';
  154. $html .= '<tr><th>关键缓存类型</th><td>' . ($statistics['critical_types'] ?? 0) . '</td></tr>';
  155. $html .= '<tr><th>安全清理类型</th><td>' . ($statistics['safe_to_clear'] ?? 0) . '</td></tr>';
  156. $html .= '</table>';
  157. $html .= '</div>';
  158. $html .= '</div>';
  159. return new Card('缓存统计', $html);
  160. }
  161. /**
  162. * 获取缓存管理JavaScript
  163. *
  164. * @return string
  165. */
  166. protected function getCacheManagementScript(): string
  167. {
  168. return '
  169. <script>
  170. function clearAllCache() {
  171. if (confirm("确定要清理所有缓存吗?这可能会影响系统性能。")) {
  172. $.post("/admin/admin-cache/clear-all", {
  173. _token: $("meta[name=csrf-token]").attr("content")
  174. }).done(function(data) {
  175. if (data.status === "success") {
  176. Dcat.success(data.message);
  177. location.reload();
  178. } else {
  179. Dcat.error(data.message);
  180. }
  181. }).fail(function() {
  182. Dcat.error("操作失败");
  183. });
  184. }
  185. }
  186. function clearCacheByType(type) {
  187. if (confirm("确定要清理 " + type + " 缓存吗?")) {
  188. $.post("/admin/admin-cache/clear-type", {
  189. type: type,
  190. _token: $("meta[name=csrf-token]").attr("content")
  191. }).done(function(data) {
  192. if (data.status === "success") {
  193. Dcat.success(data.message);
  194. location.reload();
  195. } else {
  196. Dcat.error(data.message);
  197. }
  198. }).fail(function() {
  199. Dcat.error("操作失败");
  200. });
  201. }
  202. }
  203. function warmupCache() {
  204. if (confirm("确定要预热缓存吗?")) {
  205. $.post("/admin/admin-cache/warmup", {
  206. _token: $("meta[name=csrf-token]").attr("content")
  207. }).done(function(data) {
  208. if (data.status === "success") {
  209. Dcat.success(data.message);
  210. location.reload();
  211. } else {
  212. Dcat.error(data.message);
  213. }
  214. }).fail(function() {
  215. Dcat.error("操作失败");
  216. });
  217. }
  218. }
  219. </script>';
  220. }
  221. /**
  222. * 清理所有缓存
  223. *
  224. * @return \Illuminate\Http\JsonResponse
  225. */
  226. #[Post('admin-cache/clear-all')]
  227. public function clearAll()
  228. {
  229. try {
  230. $results = $this->cacheService->clearAll();
  231. // 记录操作日志
  232. $this->adminService->logAdminAction(
  233. ADMIN_ACTION_TYPE::CACHE_CLEAR,
  234. '清理所有缓存',
  235. ['results' => $results]
  236. );
  237. return response()->json([
  238. 'status' => 'success',
  239. 'message' => '所有缓存清理完成',
  240. 'data' => $results,
  241. ]);
  242. } catch (\Exception $e) {
  243. return response()->json([
  244. 'status' => 'error',
  245. 'message' => $e->getMessage(),
  246. ], 500);
  247. }
  248. }
  249. /**
  250. * 按类型清理缓存
  251. *
  252. * @param Request $request
  253. * @return \Illuminate\Http\JsonResponse
  254. */
  255. #[Post('admin-cache/clear-type')]
  256. public function clearByType(Request $request)
  257. {
  258. try {
  259. $type = CACHE_TYPE::from($request->input('type'));
  260. $result = $this->cacheService->clearByType($type);
  261. // 记录操作日志
  262. $this->adminService->logAdminAction(
  263. ADMIN_ACTION_TYPE::CACHE_CLEAR,
  264. "清理{$type->getLabel()}缓存",
  265. ['type' => $type->value, 'result' => $result]
  266. );
  267. return response()->json([
  268. 'status' => 'success',
  269. 'message' => $result['message'],
  270. 'data' => $result,
  271. ]);
  272. } catch (\Exception $e) {
  273. return response()->json([
  274. 'status' => 'error',
  275. 'message' => $e->getMessage(),
  276. ], 500);
  277. }
  278. }
  279. /**
  280. * 预热缓存
  281. *
  282. * @return \Illuminate\Http\JsonResponse
  283. */
  284. #[Post('admin-cache/warmup')]
  285. public function warmup()
  286. {
  287. try {
  288. $results = $this->cacheService->warmup();
  289. // 记录操作日志
  290. $this->adminService->logAdminAction(
  291. ADMIN_ACTION_TYPE::CACHE_CLEAR,
  292. '预热缓存',
  293. ['results' => $results]
  294. );
  295. return response()->json([
  296. 'status' => 'success',
  297. 'message' => '缓存预热完成',
  298. 'data' => $results,
  299. ]);
  300. } catch (\Exception $e) {
  301. return response()->json([
  302. 'status' => 'error',
  303. 'message' => $e->getMessage(),
  304. ], 500);
  305. }
  306. }
  307. }