功能:完善 YumiNail 全栈修复与打包

This commit is contained in:
xiaowang
2026-05-15 21:10:41 +08:00
parent 3d0a859980
commit 1f05e0ab44
42 changed files with 768 additions and 316 deletions
@@ -26,6 +26,8 @@ public class AppCacheProperties {
private CacheSpec objectStorageFile = new CacheSpec(300, 1800);
private CacheSpec dashboard = new CacheSpec(30, 90);
@Data
public static class CacheSpec {
private long localTtlSeconds;
@@ -1,8 +1,10 @@
package com.xiaowang.yuminailcore.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.xiaowang.yuminailcore.annotation.RequirePermission;
import com.xiaowang.yuminailcore.common.Result;
import com.xiaowang.yuminailcore.config.AppCacheProperties;
import com.xiaowang.yuminailcore.entity.CommentDO;
import com.xiaowang.yuminailcore.entity.OrderDO;
import com.xiaowang.yuminailcore.entity.OrderItemDO;
@@ -16,6 +18,7 @@ import com.xiaowang.yuminailcore.mapper.ShopMapper;
import com.xiaowang.yuminailcore.mapper.UserMapper;
import com.xiaowang.yuminailcore.support.AdminScopeHelper;
import com.xiaowang.yuminailcore.support.UserShopBindingSupport;
import com.xiaowang.yuminailcore.support.cache.MultiLevelCacheService;
import com.xiaowang.yuminailcore.vo.DashboardStatsVO;
import com.xiaowang.yuminailcore.vo.HotProductVO;
import com.xiaowang.yuminailcore.vo.RecentActivityVO;
@@ -24,6 +27,7 @@ import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
@@ -44,15 +48,30 @@ public class DashboardController {
private final OrderItemMapper orderItemMapper;
private final AdminScopeHelper adminScopeHelper;
private final UserShopBindingSupport userShopBindingSupport;
private final MultiLevelCacheService multiLevelCacheService;
private final AppCacheProperties appCacheProperties;
@GetMapping("/stats")
@RequirePermission("dashboard:view")
public Result<DashboardStatsVO> getDashboardStats(HttpServletRequest request) {
DashboardStatsVO stats = new DashboardStatsVO();
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
Long shopIdScope = null;
Long shopIdScope = resolveShopScope(currentUser);
String cacheScope = currentUser == null ? "anonymous" : (shopIdScope == null ? "admin" : "shop:" + shopIdScope);
AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getDashboard();
DashboardStatsVO stats = multiLevelCacheService.getOrLoad(
"cache:dashboard:stats:" + cacheScope,
Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()),
Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()),
new TypeReference<DashboardStatsVO>() {
},
() -> buildDashboardStats(currentUser, shopIdScope)
);
return Result.success(stats);
}
private DashboardStatsVO buildDashboardStats(UserDO currentUser, Long shopIdScope) {
DashboardStatsVO stats = new DashboardStatsVO();
if (currentUser != null) {
// 根据用户类型显示不同的数据
if (currentUser.getType() == 4) { // 管理员
@@ -88,27 +107,29 @@ public class DashboardController {
stats.setHotProducts(getHotProducts(shopIdScope));
stats.setRecentActivities(getRecentActivities(shopIdScope));
return Result.success(stats);
return stats;
}
private Long resolveShopScope(UserDO currentUser) {
if (currentUser == null || currentUser.getType() == 4) {
return null;
}
return currentUser.getShopId();
}
private Long getTodayOrders(Long shopId) {
// 获取今天的开始时间
LocalDateTime todayStart = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0).withNano(0);
String todayStartStr = todayStart.format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
System.out.println("Today start time: " + todayStartStr);
if (shopId != null) {
// 非管理员只查询自己店铺的订单,通过订单商品关联到商品,再关联到店铺
java.util.Map<String, Object> result = orderItemMapper.countTodayOrdersByShopId(shopId, todayStartStr);
Long count = result != null && result.get("count") != null ? Long.valueOf(result.get("count").toString()) : 0L;
System.out.println("Shop ID: " + shopId + ", Order count: " + count);
return count;
return result != null && result.get("count") != null ? Long.valueOf(result.get("count").toString()) : 0L;
} else {
// 管理员查询所有订单
java.util.Map<String, Object> result = orderItemMapper.countTodayOrders(todayStartStr);
Long count = result != null && result.get("count") != null ? Long.valueOf(result.get("count").toString()) : 0L;
System.out.println("Admin order count: " + count);
return count;
return result != null && result.get("count") != null ? Long.valueOf(result.get("count").toString()) : 0L;
}
}
@@ -1,10 +1,22 @@
package com.xiaowang.yuminailcore.controller;
import com.xiaowang.yuminailcore.common.Result;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.sql.DataSource;
import java.sql.Connection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* 健康检查控制器
*
@@ -13,8 +25,14 @@ import org.springframework.web.bind.annotation.RestController;
*/
@RestController
@RequestMapping("/health")
@RequiredArgsConstructor
public class HealthController {
private final DataSource dataSource;
private final StringRedisTemplate stringRedisTemplate;
private final DiscoveryClient discoveryClient;
private final Environment environment;
/**
* 服务状态检查
*/
@@ -22,4 +40,55 @@ public class HealthController {
public Result<String> check() {
return Result.success("YumiNail-Core is running");
}
@GetMapping("/diagnostics")
public Result<Map<String, Object>> diagnostics() {
Map<String, Object> diagnostics = new LinkedHashMap<>();
diagnostics.put("service", environment.getProperty("spring.application.name", "yumi-nail-core"));
diagnostics.put("port", environment.getProperty("server.port", ""));
diagnostics.put("database", checkDatabase());
diagnostics.put("redis", checkRedis());
diagnostics.put("discovery", checkDiscovery());
return Result.success(diagnostics);
}
private Map<String, Object> checkDatabase() {
Map<String, Object> result = new LinkedHashMap<>();
try (Connection connection = dataSource.getConnection()) {
result.put("ok", connection.isValid(2));
result.put("catalog", connection.getCatalog());
result.put("product", connection.getMetaData().getDatabaseProductName());
} catch (Exception exception) {
result.put("ok", false);
result.put("error", exception.getClass().getSimpleName());
}
return result;
}
private Map<String, Object> checkRedis() {
Map<String, Object> result = new LinkedHashMap<>();
try (RedisConnection connection = stringRedisTemplate.getConnectionFactory().getConnection()) {
String pong = connection.ping();
result.put("ok", "PONG".equalsIgnoreCase(pong));
} catch (Exception exception) {
result.put("ok", false);
result.put("error", exception.getClass().getSimpleName());
}
return result;
}
private Map<String, Object> checkDiscovery() {
Map<String, Object> result = new LinkedHashMap<>();
try {
String serviceName = environment.getProperty("spring.application.name", "yumi-nail-core");
List<ServiceInstance> instances = discoveryClient.getInstances(serviceName);
result.put("ok", !instances.isEmpty());
result.put("service", serviceName);
result.put("instanceCount", instances.size());
} catch (Exception exception) {
result.put("ok", false);
result.put("error", exception.getClass().getSimpleName());
}
return result;
}
}
@@ -179,13 +179,23 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
@Override
public List<ProductVO> listProductsByShopId(Long shopId) {
List<ProductDO> productDOs = productMapper.selectList(
Wrappers.lambdaQuery(ProductDO.class)
.eq(ProductDO::getIsDelete, 0)
.eq(ProductDO::getShopId, shopId)
.orderByDesc(ProductDO::getCreateTime)
AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getProductList();
return multiLevelCacheService.getOrLoad(
PRODUCT_LIST_CACHE_PREFIX + "shop:" + shopId,
Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()),
Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()),
new TypeReference<List<ProductVO>>() {
},
() -> {
List<ProductDO> productDOs = productMapper.selectList(
Wrappers.lambdaQuery(ProductDO.class)
.eq(ProductDO::getIsDelete, 0)
.eq(ProductDO::getShopId, shopId)
.orderByDesc(ProductDO::getCreateTime)
);
return toProductVOList(productDOs);
}
);
return toProductVOList(productDOs);
}
@Override
@@ -211,15 +211,26 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopDO> implements
@Override
public List<ShopVO> listShopsByShopName(String shopName) {
List<ShopDO> shopDOs = shopMapper.selectList(
Wrappers.lambdaQuery(ShopDO.class)
.eq(ShopDO::getIsDelete, 0)
.eq(ShopDO::getStatus, 1)
.like(ShopDO::getShopName, shopName)
AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getShop();
String normalizedShopName = StringUtils.hasText(shopName) ? shopName.trim() : "";
return multiLevelCacheService.getOrLoad(
SHOP_LIST_CACHE_PREFIX + "name:" + normalizedShopName,
Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()),
Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()),
new TypeReference<List<ShopVO>>() {
},
() -> {
List<ShopDO> shopDOs = shopMapper.selectList(
Wrappers.lambdaQuery(ShopDO.class)
.eq(ShopDO::getIsDelete, 0)
.eq(ShopDO::getStatus, 1)
.like(ShopDO::getShopName, normalizedShopName)
);
return shopDOs.stream()
.map(this::convertToVO)
.collect(Collectors.toList());
}
);
return shopDOs.stream()
.map(this::convertToVO)
.collect(Collectors.toList());
}
@Override
@@ -13,14 +13,14 @@ public final class PermissionPolicy {
"home:view",
"dashboard:view",
"user:view", "user:create", "user:edit", "user:disable", "user:unbind", "user:reset_password", "user:delete",
"user:balance:view",
"product:view",
"user:balance:view", "user:balance:manage", "user:vip:manage",
"product:view", "product:create", "product:edit", "product:delete", "product:category:manage",
"shop:view", "shop:create", "shop:edit", "shop:delete", "shop:staff:manage",
"permission:view", "permission:create", "permission:edit", "permission:delete", "permission:assign",
"tag:view",
"coupon:view",
"order:view",
"nail_artist:view"
"tag:view", "tag:create", "tag:edit", "tag:delete", "tag:assign",
"coupon:view", "coupon:create", "coupon:edit", "coupon:delete", "coupon:assign",
"order:view", "order:process", "order:edit", "order:delete",
"nail_artist:view", "nail_artist:edit"
);
private static final List<String> SHOP_MANAGER_DEFAULT_PERMISSION_CODES = List.of(
@@ -8,12 +8,18 @@ import com.github.benmanes.caffeine.cache.Caffeine;
import com.xiaowang.yuminailcore.config.AppCacheProperties;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import java.time.Duration;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashSet;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeUnit;
@@ -24,6 +30,7 @@ import java.util.function.Supplier;
*/
@Component
@RequiredArgsConstructor
@Slf4j
public class MultiLevelCacheService {
private static final String NULL_SENTINEL = "__CACHE_NULL__";
@@ -71,7 +78,7 @@ public class MultiLevelCacheService {
getLocalCache().invalidate(key);
}
String json = stringRedisTemplate.opsForValue().get(key);
String json = readRedisValue(key);
if (!StringUtils.hasText(json)) {
return CacheLookup.miss();
}
@@ -86,7 +93,7 @@ public class MultiLevelCacheService {
}
String json = writeValue(value);
putLocal(key, json, localTtl);
stringRedisTemplate.opsForValue().set(key, json, redisTtl.getSeconds(), TimeUnit.SECONDS);
writeRedisValue(key, json, redisTtl);
}
public void evict(String... keys) {
@@ -96,7 +103,7 @@ public class MultiLevelCacheService {
for (String key : keys) {
getLocalCache().invalidate(key);
}
stringRedisTemplate.delete(Set.of(keys));
deleteRedisKeys(Set.of(keys));
}
public void evictByPrefix(String prefix) {
@@ -104,9 +111,58 @@ public class MultiLevelCacheService {
return;
}
getLocalCache().asMap().keySet().removeIf(key -> key.startsWith(prefix));
Set<String> redisKeys = stringRedisTemplate.keys(prefix + "*");
Set<String> redisKeys = scanRedisKeys(prefix + "*");
if (!CollectionUtils.isEmpty(redisKeys)) {
stringRedisTemplate.delete(redisKeys);
deleteRedisKeys(redisKeys);
}
}
private String readRedisValue(String key) {
try {
return stringRedisTemplate.opsForValue().get(key);
} catch (Exception exception) {
log.warn("Redis cache read failed, key={}", key, exception);
return null;
}
}
private void writeRedisValue(String key, String json, Duration redisTtl) {
try {
stringRedisTemplate.opsForValue().set(key, json, redisTtl.getSeconds(), TimeUnit.SECONDS);
} catch (Exception exception) {
log.warn("Redis cache write failed, key={}", key, exception);
}
}
private void deleteRedisKeys(Set<String> keys) {
if (CollectionUtils.isEmpty(keys)) {
return;
}
try {
stringRedisTemplate.delete(keys);
} catch (Exception exception) {
log.warn("Redis cache delete failed, size={}", keys.size(), exception);
}
}
private Set<String> scanRedisKeys(String pattern) {
Set<String> keys = new LinkedHashSet<>();
try {
return stringRedisTemplate.execute((RedisConnection connection) -> {
Set<String> matchedKeys = new LinkedHashSet<>();
try (Cursor<byte[]> cursor = connection.scan(ScanOptions.scanOptions()
.match(pattern)
.count(500)
.build())) {
while (cursor.hasNext()) {
matchedKeys.add(new String(cursor.next(), StandardCharsets.UTF_8));
}
}
return matchedKeys;
});
} catch (Exception exception) {
log.warn("Redis cache scan failed, pattern={}", pattern, exception);
return keys;
}
}
@@ -1,6 +1,6 @@
spring:
datasource:
url: jdbc:mysql://localhost:3306/yumi_nail?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
url: jdbc:mysql://localhost:3306/nailart?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
servlet:
multipart:
max-file-size: 5MB
@@ -72,6 +72,9 @@ yuminail:
object-storage-file:
local-ttl-seconds: 300
redis-ttl-seconds: 1800
dashboard:
local-ttl-seconds: 30
redis-ttl-seconds: 90
slow-request:
enabled: true
threshold-ms: 300
@@ -3,7 +3,8 @@
-- 1. 首次部署空库时,只需要执行本文件即可完成基础建表、结构补丁、权限种子、VIP 规则、admin01 初始化与默认权限分配。
-- 2. 2026-03-20_user_asset_vip_coupon_permission_patch.sql、2026-03-25_user_shop_binding_and_shop_status_patch.sql、
-- 2026-03-20_init_admin_permission_template.sql 仍保留用于已有数据库的增量升级,不再作为空库首选入口。
-- 3. 如果你的数据库名不是 nailart,请先将本文件中的 `use nailart;` 改成实际库名后再执行。
-- 3. 当前 Nacos datasource.yaml 指向 nailart,本文件默认按该库名初始化;如果你的实际数据库名不同,请先统一 datasource 与下方库名。
CREATE DATABASE IF NOT EXISTS nailart DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
use nailart;
-- auto-generated definition
@@ -1192,7 +1193,13 @@ INNER JOIN t_permission p
'user:reset_password',
'user:delete',
'user:balance:view',
'user:balance:manage',
'user:vip:manage',
'product:view',
'product:create',
'product:edit',
'product:delete',
'product:category:manage',
'shop:view',
'shop:create',
'shop:edit',
@@ -1204,9 +1211,21 @@ INNER JOIN t_permission p
'permission:delete',
'permission:assign',
'tag:view',
'tag:create',
'tag:edit',
'tag:delete',
'tag:assign',
'coupon:view',
'coupon:create',
'coupon:edit',
'coupon:delete',
'coupon:assign',
'order:view',
'nail_artist:view'
'order:process',
'order:edit',
'order:delete',
'nail_artist:view',
'nail_artist:edit'
)
WHERE u.is_delete = 0
AND u.type = 4