init: first commit

This commit is contained in:
2025-12-19 00:13:28 +08:00
commit cafd2708b4
25 changed files with 3364 additions and 0 deletions

View File

@@ -0,0 +1,13 @@
package icu.sunway.ai_spring_example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class AiSpringExampleApplication {
public static void main(String[] args) {
SpringApplication.run(AiSpringExampleApplication.class, args);
}
}

View File

@@ -0,0 +1,47 @@
package icu.sunway.ai_spring_example.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import java.util.Arrays;
/**
* 跨域配置类
* 用于配置允许的跨域请求来源、方法、头信息等
*/
@Configuration
public class CorsConfig {
@Bean
public CorsFilter corsFilter() {
// 创建CorsConfiguration对象
CorsConfiguration config = new CorsConfiguration();
// 允许所有域名进行跨域请求
config.addAllowedOriginPattern("*");
// 允许的请求头
config.addAllowedHeader("*");
// 允许的请求方法
config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
// 允许发送Cookie
config.setAllowCredentials(true);
// 预检请求的有效期,单位为秒
config.setMaxAge(3600L);
// 创建UrlBasedCorsConfigurationSource对象
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
// 对所有URL应用跨域配置
source.registerCorsConfiguration("/**", config);
// 返回CorsFilter实例
return new CorsFilter(source);
}
}

View File

@@ -0,0 +1,30 @@
package icu.sunway.ai_spring_example.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
// 设置键的序列化器为 StringRedisSerializer
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
// 设置值的序列化器为 GenericJackson2JsonRedisSerializer
GenericJackson2JsonRedisSerializer serializer = new GenericJackson2JsonRedisSerializer();
redisTemplate.setValueSerializer(serializer);
redisTemplate.setHashValueSerializer(serializer);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}

View File

@@ -0,0 +1,33 @@
package icu.sunway.ai_spring_example.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
// 启用跨域配置
.cors(cors -> cors.configurationSource(
request -> new org.springframework.web.cors.CorsConfiguration().applyPermitDefaultValues()))
// 禁用默认的登录表单和HTTP基本认证
.formLogin(form -> form.disable())
.httpBasic(basic -> basic.disable())
// 允许所有请求通过,取消默认登录验证
.authorizeHttpRequests((authz) -> authz
.anyRequest().permitAll())
// 禁用CSRF保护
.csrf(csrf -> csrf.disable())
// 设置会话创建策略为无状态
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
return http.build();
}
}

View File

@@ -0,0 +1,17 @@
package icu.sunway.ai_spring_example.Controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.RequestMapping;
import icu.sunway.ai_spring_example.Service.IExampleEntityService;
@Controller
@RestController
@RequestMapping("/example")
public class EaxmpleEntityController {
@Resource
private IExampleEntityService exampleEntityService;
}

View File

@@ -0,0 +1,19 @@
package icu.sunway.ai_spring_example.Entity;
import java.time.LocalDateTime;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("example_entity")
public class ExampleEntity {
private Long id;
private String name;
private LocalDateTime createTime;
}

View File

@@ -0,0 +1,10 @@
package icu.sunway.ai_spring_example.Mapper;
import org.apache.ibatis.annotations.Mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import icu.sunway.ai_spring_example.Entity.ExampleEntity;
@Mapper
public interface ExampleEntityMapper extends BaseMapper<ExampleEntity> {
}

View File

@@ -0,0 +1,7 @@
package icu.sunway.ai_spring_example.Service;
import com.baomidou.mybatisplus.extension.service.IService;
import icu.sunway.ai_spring_example.Entity.ExampleEntity;
public interface IExampleEntityService extends IService<ExampleEntity> {
}

View File

@@ -0,0 +1,18 @@
package icu.sunway.ai_spring_example.Service.Implements;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import icu.sunway.ai_spring_example.Entity.ExampleEntity;
import icu.sunway.ai_spring_example.Mapper.ExampleEntityMapper;
import icu.sunway.ai_spring_example.Service.IExampleEntityService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
@Service
public class ExampleEntityServiceImpl extends ServiceImpl<ExampleEntityMapper, ExampleEntity>
implements IExampleEntityService {
@Resource
private ExampleEntityMapper exampleEntityMapper;
}

View File

@@ -0,0 +1,287 @@
package icu.sunway.ai_spring_example.Utils;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Date;
/**
* 日期时间工具类
*/
public class DateUtils {
/**
* 常用日期时间格式
*/
public static final String FORMAT_DATE = "yyyy-MM-dd";
public static final String FORMAT_TIME = "HH:mm:ss";
public static final String FORMAT_DATETIME = "yyyy-MM-dd HH:mm:ss";
public static final String FORMAT_DATETIME_SSS = "yyyy-MM-dd HH:mm:ss.SSS";
public static final String FORMAT_DATE_CHINESE = "yyyy年MM月dd日";
public static final String FORMAT_DATETIME_CHINESE = "yyyy年MM月dd日 HH时mm分ss秒";
/**
* 获取当前日期时间
*
* @return LocalDateTime
*/
public static LocalDateTime now() {
return LocalDateTime.now();
}
/**
* 获取当前日期
*
* @return LocalDate
*/
public static LocalDate today() {
return LocalDate.now();
}
/**
* 获取当前时间
*
* @return LocalTime
*/
public static LocalTime currentTime() {
return LocalTime.now();
}
/**
* 格式化日期时间
*
* @param dateTime 日期时间
* @param pattern 格式
* @return 格式化后的字符串
*/
public static String format(LocalDateTime dateTime, String pattern) {
if (dateTime == null) {
return null;
}
return dateTime.format(DateTimeFormatter.ofPattern(pattern));
}
/**
* 格式化日期
*
* @param date 日期
* @param pattern 格式
* @return 格式化后的字符串
*/
public static String format(LocalDate date, String pattern) {
if (date == null) {
return null;
}
return date.format(DateTimeFormatter.ofPattern(pattern));
}
/**
* 格式化时间
*
* @param time 时间
* @param pattern 格式
* @return 格式化后的字符串
*/
public static String format(LocalTime time, String pattern) {
if (time == null) {
return null;
}
return time.format(DateTimeFormatter.ofPattern(pattern));
}
/**
* 解析日期时间字符串
*
* @param dateTimeStr 日期时间字符串
* @param pattern 格式
* @return LocalDateTime
*/
public static LocalDateTime parseDateTime(String dateTimeStr, String pattern) {
if (dateTimeStr == null || dateTimeStr.isEmpty()) {
return null;
}
return LocalDateTime.parse(dateTimeStr, DateTimeFormatter.ofPattern(pattern));
}
/**
* 解析日期字符串
*
* @param dateStr 日期字符串
* @param pattern 格式
* @return LocalDate
*/
public static LocalDate parseDate(String dateStr, String pattern) {
if (dateStr == null || dateStr.isEmpty()) {
return null;
}
return LocalDate.parse(dateStr, DateTimeFormatter.ofPattern(pattern));
}
/**
* 解析时间字符串
*
* @param timeStr 时间字符串
* @param pattern 格式
* @return LocalTime
*/
public static LocalTime parseTime(String timeStr, String pattern) {
if (timeStr == null || timeStr.isEmpty()) {
return null;
}
return LocalTime.parse(timeStr, DateTimeFormatter.ofPattern(pattern));
}
/**
* Date转LocalDateTime
*
* @param date Date
* @return LocalDateTime
*/
public static LocalDateTime dateToLocalDateTime(Date date) {
if (date == null) {
return null;
}
return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
}
/**
* LocalDateTime转Date
*
* @param dateTime LocalDateTime
* @return Date
*/
public static Date localDateTimeToDate(LocalDateTime dateTime) {
if (dateTime == null) {
return null;
}
return Date.from(dateTime.atZone(ZoneId.systemDefault()).toInstant());
}
/**
* 计算两个日期时间之间的差值
*
* @param start 开始时间
* @param end 结束时间
* @param unit 时间单位
* @return 差值
*/
public static long between(LocalDateTime start, LocalDateTime end, ChronoUnit unit) {
if (start == null || end == null || unit == null) {
return 0;
}
return unit.between(start, end);
}
/**
* 日期时间加减
*
* @param dateTime 日期时间
* @param amount 数量
* @param unit 时间单位
* @return 计算后的日期时间
*/
public static LocalDateTime plus(LocalDateTime dateTime, long amount, ChronoUnit unit) {
if (dateTime == null || unit == null) {
return null;
}
return dateTime.plus(amount, unit);
}
/**
* 日期时间加减
*
* @param dateTime 日期时间
* @param amount 数量
* @param unit 时间单位
* @return 计算后的日期时间
*/
public static LocalDateTime minus(LocalDateTime dateTime, long amount, ChronoUnit unit) {
if (dateTime == null || unit == null) {
return null;
}
return dateTime.minus(amount, unit);
}
/**
* 获取本周的第一天(周一)
*
* @return LocalDate
*/
public static LocalDate firstDayOfWeek() {
return today().with(DayOfWeek.MONDAY);
}
/**
* 获取本周的最后一天(周日)
*
* @return LocalDate
*/
public static LocalDate lastDayOfWeek() {
return today().with(DayOfWeek.SUNDAY);
}
/**
* 获取本月的第一天
*
* @return LocalDate
*/
public static LocalDate firstDayOfMonth() {
return today().withDayOfMonth(1);
}
/**
* 获取本月的最后一天
*
* @return LocalDate
*/
public static LocalDate lastDayOfMonth() {
return today().withDayOfMonth(today().lengthOfMonth());
}
/**
* 获取本年的第一天
*
* @return LocalDate
*/
public static LocalDate firstDayOfYear() {
return today().withDayOfYear(1);
}
/**
* 获取本年的最后一天
*
* @return LocalDate
*/
public static LocalDate lastDayOfYear() {
return today().withDayOfYear(today().lengthOfYear());
}
/**
* 判断两个日期是否是同一天
*
* @param date1 日期1
* @param date2 日期2
* @return 是否是同一天
*/
public static boolean isSameDay(LocalDateTime date1, LocalDateTime date2) {
if (date1 == null || date2 == null) {
return false;
}
return date1.toLocalDate().isEqual(date2.toLocalDate());
}
/**
* 判断日期是否在指定范围内
*
* @param dateTime 日期时间
* @param startTime 开始时间
* @param endTime 结束时间
* @return 是否在范围内
*/
public static boolean isBetween(LocalDateTime dateTime, LocalDateTime startTime, LocalDateTime endTime) {
if (dateTime == null || startTime == null || endTime == null) {
return false;
}
return dateTime.isAfter(startTime) && dateTime.isBefore(endTime);
}
}

View File

@@ -0,0 +1,256 @@
package icu.sunway.ai_spring_example.Utils;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
/**
* 加密工具类
*/
public class EncryptUtils {
/**
* MD5加密
*
* @param str 待加密字符串
* @return 加密后字符串
*/
public static String md5(String str) {
if (str == null || str.isEmpty()) {
return null;
}
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] bytes = md.digest(str.getBytes(StandardCharsets.UTF_8));
return byteArrayToHexString(bytes);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
/**
* SHA-1加密
*
* @param str 待加密字符串
* @return 加密后字符串
*/
public static String sha1(String str) {
if (str == null || str.isEmpty()) {
return null;
}
try {
MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] bytes = md.digest(str.getBytes(StandardCharsets.UTF_8));
return byteArrayToHexString(bytes);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
/**
* SHA-256加密
*
* @param str 待加密字符串
* @return 加密后字符串
*/
public static String sha256(String str) {
if (str == null || str.isEmpty()) {
return null;
}
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] bytes = md.digest(str.getBytes(StandardCharsets.UTF_8));
return byteArrayToHexString(bytes);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
/**
* SHA-512加密
*
* @param str 待加密字符串
* @return 加密后字符串
*/
public static String sha512(String str) {
if (str == null || str.isEmpty()) {
return null;
}
try {
MessageDigest md = MessageDigest.getInstance("SHA-512");
byte[] bytes = md.digest(str.getBytes(StandardCharsets.UTF_8));
return byteArrayToHexString(bytes);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
/**
* BASE64加密
*
* @param str 待加密字符串
* @return 加密后字符串
*/
public static String base64Encode(String str) {
if (str == null || str.isEmpty()) {
return null;
}
return Base64.getEncoder().encodeToString(str.getBytes(StandardCharsets.UTF_8));
}
/**
* BASE64解密
*
* @param str 待解密字符串
* @return 解密后字符串
*/
public static String base64Decode(String str) {
if (str == null || str.isEmpty()) {
return null;
}
return new String(Base64.getDecoder().decode(str), StandardCharsets.UTF_8);
}
/**
* HMAC-MD5加密
*
* @param str 待加密字符串
* @param key 密钥
* @return 加密后字符串
*/
public static String hmacMd5(String str, String key) {
return hmac(str, key, "HmacMD5");
}
/**
* HMAC-SHA1加密
*
* @param str 待加密字符串
* @param key 密钥
* @return 加密后字符串
*/
public static String hmacSha1(String str, String key) {
return hmac(str, key, "HmacSHA1");
}
/**
* HMAC-SHA256加密
*
* @param str 待加密字符串
* @param key 密钥
* @return 加密后字符串
*/
public static String hmacSha256(String str, String key) {
return hmac(str, key, "HmacSHA256");
}
/**
* HMAC-SHA512加密
*
* @param str 待加密字符串
* @param key 密钥
* @return 加密后字符串
*/
public static String hmacSha512(String str, String key) {
return hmac(str, key, "HmacSHA512");
}
/**
* HMAC通用加密方法
*
* @param str 待加密字符串
* @param key 密钥
* @param algorithm 算法
* @return 加密后字符串
*/
private static String hmac(String str, String key, String algorithm) {
if (str == null || str.isEmpty() || key == null || key.isEmpty()) {
return null;
}
try {
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), algorithm);
Mac mac = Mac.getInstance(algorithm);
mac.init(secretKeySpec);
byte[] bytes = mac.doFinal(str.getBytes(StandardCharsets.UTF_8));
return byteArrayToHexString(bytes);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 将字节数组转换为十六进制字符串
*
* @param bytes 字节数组
* @return 十六进制字符串
*/
private static String byteArrayToHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (byte aByte : bytes) {
String hex = Integer.toHexString(0xFF & aByte);
if (hex.length() == 1) {
sb.append('0');
}
sb.append(hex);
}
return sb.toString();
}
/**
* 生成随机字符串
*
* @param length 长度
* @return 随机字符串
*/
public static String generateRandomString(int length) {
if (length <= 0) {
return "";
}
String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
StringBuilder sb = new StringBuilder(length);
for (int i = 0; i < length; i++) {
int index = (int) (Math.random() * characters.length());
sb.append(characters.charAt(index));
}
return sb.toString();
}
/**
* 生成盐值
*
* @return 盐值
*/
public static String generateSalt() {
return generateRandomString(16);
}
/**
* 带盐值的MD5加密
*
* @param str 待加密字符串
* @param salt 盐值
* @return 加密后字符串
*/
public static String md5WithSalt(String str, String salt) {
return md5(str + salt);
}
/**
* 带盐值的SHA-256加密
*
* @param str 待加密字符串
* @param salt 盐值
* @return 加密后字符串
*/
public static String sha256WithSalt(String str, String salt) {
return sha256(str + salt);
}
}

View File

@@ -0,0 +1,352 @@
package icu.sunway.ai_spring_example.Utils;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;
/**
* 文件工具类
*/
public class FileUtils {
/**
* 获取文件扩展名
*
* @param fileName 文件名
* @return 扩展名
*/
public static String getFileExtension(String fileName) {
if (fileName == null || fileName.isEmpty()) {
return null;
}
int lastDotIndex = fileName.lastIndexOf('.');
if (lastDotIndex == -1 || lastDotIndex == fileName.length() - 1) {
return null;
}
return fileName.substring(lastDotIndex + 1).toLowerCase();
}
/**
* 获取文件名(不含扩展名)
*
* @param fileName 文件名
* @return 文件名(不含扩展名)
*/
public static String getFileNameWithoutExtension(String fileName) {
if (fileName == null || fileName.isEmpty()) {
return null;
}
int lastDotIndex = fileName.lastIndexOf('.');
if (lastDotIndex == -1) {
return fileName;
}
return fileName.substring(0, lastDotIndex);
}
/**
* 创建目录
*
* @param directoryPath 目录路径
* @return 是否创建成功
*/
public static boolean createDirectory(String directoryPath) {
if (directoryPath == null || directoryPath.isEmpty()) {
return false;
}
Path path = Paths.get(directoryPath);
if (Files.exists(path)) {
return Files.isDirectory(path);
}
try {
Files.createDirectories(path);
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* 复制文件
*
* @param sourcePath 源文件路径
* @param targetPath 目标文件路径
* @return 是否复制成功
*/
public static boolean copyFile(String sourcePath, String targetPath) {
if (sourcePath == null || targetPath == null) {
return false;
}
Path source = Paths.get(sourcePath);
Path target = Paths.get(targetPath);
try {
// 创建目标文件的父目录
Files.createDirectories(target.getParent());
Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* 移动文件
*
* @param sourcePath 源文件路径
* @param targetPath 目标文件路径
* @return 是否移动成功
*/
public static boolean moveFile(String sourcePath, String targetPath) {
if (sourcePath == null || targetPath == null) {
return false;
}
Path source = Paths.get(sourcePath);
Path target = Paths.get(targetPath);
try {
// 创建目标文件的父目录
Files.createDirectories(target.getParent());
Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* 删除文件
*
* @param filePath 文件路径
* @return 是否删除成功
*/
public static boolean deleteFile(String filePath) {
if (filePath == null) {
return false;
}
Path path = Paths.get(filePath);
try {
return Files.deleteIfExists(path);
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* 删除目录(递归删除)
*
* @param directoryPath 目录路径
* @return 是否删除成功
*/
public static boolean deleteDirectory(String directoryPath) {
if (directoryPath == null) {
return false;
}
Path path = Paths.get(directoryPath);
if (!Files.exists(path) || !Files.isDirectory(path)) {
return false;
}
try {
Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* 获取文件大小
*
* @param filePath 文件路径
* @return 文件大小(字节)
*/
public static long getFileSize(String filePath) {
if (filePath == null) {
return 0;
}
Path path = Paths.get(filePath);
try {
return Files.size(path);
} catch (IOException e) {
e.printStackTrace();
return 0;
}
}
/**
* 判断文件是否存在
*
* @param filePath 文件路径
* @return 是否存在
*/
public static boolean exists(String filePath) {
if (filePath == null) {
return false;
}
return Files.exists(Paths.get(filePath));
}
/**
* 判断是否是目录
*
* @param path 路径
* @return 是否是目录
*/
public static boolean isDirectory(String path) {
if (path == null) {
return false;
}
return Files.isDirectory(Paths.get(path));
}
/**
* 读取文件内容
*
* @param filePath 文件路径
* @return 文件内容
*/
public static String readFile(String filePath) {
if (filePath == null) {
return null;
}
Path path = Paths.get(filePath);
try {
return Files.readString(path, StandardCharsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* 读取文件内容(按行读取)
*
* @param filePath 文件路径
* @return 文件内容列表
*/
public static List<String> readFileLines(String filePath) {
if (filePath == null) {
return null;
}
Path path = Paths.get(filePath);
try {
return Files.readAllLines(path, StandardCharsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* 写入文件内容
*
* @param filePath 文件路径
* @param content 内容
* @return 是否写入成功
*/
public static boolean writeFile(String filePath, String content) {
if (filePath == null || content == null) {
return false;
}
Path path = Paths.get(filePath);
try {
// 创建父目录
Files.createDirectories(path.getParent());
Files.writeString(path, content, StandardCharsets.UTF_8);
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* 追加写入文件内容
*
* @param filePath 文件路径
* @param content 内容
* @return 是否写入成功
*/
public static boolean appendFile(String filePath, String content) {
if (filePath == null || content == null) {
return false;
}
Path path = Paths.get(filePath);
try {
// 创建父目录
Files.createDirectories(path.getParent());
Files.writeString(path, content, StandardCharsets.UTF_8, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* 列出目录下的文件
*
* @param directoryPath 目录路径
* @return 文件列表
*/
public static List<File> listFiles(String directoryPath) {
if (directoryPath == null) {
return null;
}
File directory = new File(directoryPath);
if (!directory.exists() || !directory.isDirectory()) {
return null;
}
File[] files = directory.listFiles();
if (files == null) {
return new ArrayList<>();
}
List<File> fileList = new ArrayList<>();
for (File file : files) {
fileList.add(file);
}
return fileList;
}
/**
* 格式化文件大小
*
* @param size 文件大小(字节)
* @return 格式化后的文件大小
*/
public static String formatFileSize(long size) {
if (size < 0) {
return "-" + formatFileSize(-size);
}
if (size < 1024) {
return size + " B";
}
if (size < 1024 * 1024) {
return String.format("%.2f KB", size / 1024.0);
}
if (size < 1024 * 1024 * 1024) {
return String.format("%.2f MB", size / (1024.0 * 1024.0));
}
if (size < 1024L * 1024L * 1024L * 1024L) {
return String.format("%.2f GB", size / (1024.0 * 1024.0 * 1024.0));
}
return String.format("%.2f TB", size / (1024.0 * 1024.0 * 1024.0 * 1024.0));
}
}

View File

@@ -0,0 +1,310 @@
package icu.sunway.ai_spring_example.Utils;
import org.springframework.http.*;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* HTTP工具类用于发送HTTP请求
*/
public class HttpUtil {
private static final RestTemplate restTemplate;
static {
// 配置RestTemplate
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout((int) TimeUnit.SECONDS.toMillis(10)); // 连接超时10秒
factory.setReadTimeout((int) TimeUnit.SECONDS.toMillis(30)); // 读取超时30秒
restTemplate = new RestTemplate(factory);
}
/**
* 发送GET请求
*
* @param url 请求URL
* @return 响应结果
*/
public static String get(String url) {
return get(url, null, null);
}
/**
* 发送GET请求
*
* @param url 请求URL
* @param headers 请求头
* @return 响应结果
*/
public static String get(String url, Map<String, String> headers) {
return get(url, headers, null);
}
/**
* 发送GET请求
*
* @param url 请求URL
* @param headers 请求头
* @param params 请求参数
* @return 响应结果
*/
public static String get(String url, Map<String, String> headers, Map<String, Object> params) {
HttpHeaders httpHeaders = createHeaders(headers);
HttpEntity<?> requestEntity = new HttpEntity<>(httpHeaders);
// 构建完整URL添加查询参数
String fullUrl = buildUrlWithParams(url, params);
ResponseEntity<String> response = restTemplate.exchange(
fullUrl,
HttpMethod.GET,
requestEntity,
String.class);
return response.getBody();
}
/**
* 发送POST请求JSON格式
*
* @param url 请求URL
* @param body 请求体
* @return 响应结果
*/
public static String post(String url, Object body) {
return post(url, body, null);
}
/**
* 发送POST请求JSON格式
*
* @param url 请求URL
* @param body 请求体
* @param headers 请求头
* @return 响应结果
*/
public static String post(String url, Object body, Map<String, String> headers) {
HttpHeaders httpHeaders = createHeaders(headers);
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<?> requestEntity = new HttpEntity<>(body, httpHeaders);
ResponseEntity<String> response = restTemplate.exchange(
url,
HttpMethod.POST,
requestEntity,
String.class);
return response.getBody();
}
/**
* 发送POST请求表单格式
*
* @param url 请求URL
* @param params 表单参数
* @return 响应结果
*/
public static String postForm(String url, Map<String, Object> params) {
return postForm(url, params, null);
}
/**
* 发送POST请求表单格式
*
* @param url 请求URL
* @param params 表单参数
* @param headers 请求头
* @return 响应结果
*/
public static String postForm(String url, Map<String, Object> params, Map<String, String> headers) {
HttpHeaders httpHeaders = createHeaders(headers);
httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<?> requestEntity = new HttpEntity<>(params, httpHeaders);
ResponseEntity<String> response = restTemplate.exchange(
url,
HttpMethod.POST,
requestEntity,
String.class);
return response.getBody();
}
/**
* 发送PUT请求JSON格式
*
* @param url 请求URL
* @param body 请求体
* @return 响应结果
*/
public static String put(String url, Object body) {
return put(url, body, null);
}
/**
* 发送PUT请求JSON格式
*
* @param url 请求URL
* @param body 请求体
* @param headers 请求头
* @return 响应结果
*/
public static String put(String url, Object body, Map<String, String> headers) {
HttpHeaders httpHeaders = createHeaders(headers);
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<?> requestEntity = new HttpEntity<>(body, httpHeaders);
ResponseEntity<String> response = restTemplate.exchange(
url,
HttpMethod.PUT,
requestEntity,
String.class);
return response.getBody();
}
/**
* 发送DELETE请求
*
* @param url 请求URL
* @return 响应结果
*/
public static String delete(String url) {
return delete(url, null);
}
/**
* 发送DELETE请求
*
* @param url 请求URL
* @param headers 请求头
* @return 响应结果
*/
public static String delete(String url, Map<String, String> headers) {
HttpHeaders httpHeaders = createHeaders(headers);
HttpEntity<?> requestEntity = new HttpEntity<>(httpHeaders);
ResponseEntity<String> response = restTemplate.exchange(
url,
HttpMethod.DELETE,
requestEntity,
String.class);
return response.getBody();
}
/**
* 构建完整URL添加查询参数
*
* @param url 请求URL
* @param params 查询参数
* @return 完整URL
*/
private static String buildUrlWithParams(String url, Map<String, Object> params) {
if (params == null || params.isEmpty()) {
return url;
}
StringBuilder fullUrl = new StringBuilder(url);
if (!url.contains("?")) {
fullUrl.append("?");
} else if (!url.endsWith("?")) {
fullUrl.append("&");
}
for (Map.Entry<String, Object> entry : params.entrySet()) {
if (entry.getValue() != null) {
fullUrl.append(entry.getKey())
.append("=")
.append(entry.getValue())
.append("&");
}
}
// 移除最后一个"&"
fullUrl.deleteCharAt(fullUrl.length() - 1);
return fullUrl.toString();
}
/**
* 创建请求头
*
* @param headers 请求头Map
* @return HttpHeaders对象
*/
private static HttpHeaders createHeaders(Map<String, String> headers) {
HttpHeaders httpHeaders = new HttpHeaders();
if (headers != null && !headers.isEmpty()) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpHeaders.set(entry.getKey(), entry.getValue());
}
}
return httpHeaders;
}
/**
* 获取RestTemplate实例
*
* @return RestTemplate实例
*/
public static RestTemplate getRestTemplate() {
return restTemplate;
}
/**
* 发送GET请求返回指定类型的对象
*
* @param url 请求URL
* @param headers 请求头
* @param params 请求参数
* @param clazz 返回类型
* @param <T> 泛型
* @return 响应结果对象
*/
public static <T> T getForObject(String url, Map<String, String> headers, Map<String, Object> params,
Class<T> clazz) {
HttpHeaders httpHeaders = createHeaders(headers);
HttpEntity<?> requestEntity = new HttpEntity<>(httpHeaders);
String fullUrl = buildUrlWithParams(url, params);
ResponseEntity<T> response = restTemplate.exchange(
fullUrl,
HttpMethod.GET,
requestEntity,
clazz);
return response.getBody();
}
/**
* 发送POST请求返回指定类型的对象
*
* @param url 请求URL
* @param body 请求体
* @param headers 请求头
* @param clazz 返回类型
* @param <T> 泛型
* @return 响应结果对象
*/
public static <T> T postForObject(String url, Object body, Map<String, String> headers, Class<T> clazz) {
HttpHeaders httpHeaders = createHeaders(headers);
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<?> requestEntity = new HttpEntity<>(body, httpHeaders);
ResponseEntity<T> response = restTemplate.exchange(
url,
HttpMethod.POST,
requestEntity,
clazz);
return response.getBody();
}
}

View File

@@ -0,0 +1,185 @@
package icu.sunway.ai_spring_example.Utils;
import jakarta.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
/**
* IP工具类
*/
public class IpUtils {
/**
* 本地IP地址
*/
private static final String LOCAL_IP = "127.0.0.1";
/**
* 未知IP地址
*/
private static final String UNKNOWN_IP = "unknown";
/**
* 获取客户端IP地址
*
* @param request HTTP请求
* @return IP地址
*/
public static String getClientIp(HttpServletRequest request) {
if (request == null) {
return UNKNOWN_IP;
}
String ip = request.getHeader("X-Forwarded-For");
if (ip == null || ip.isEmpty() || UNKNOWN_IP.equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.isEmpty() || UNKNOWN_IP.equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.isEmpty() || UNKNOWN_IP.equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.isEmpty() || UNKNOWN_IP.equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.isEmpty() || UNKNOWN_IP.equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
// 如果是IPv4直接返回
if (ip != null && ip.contains("0:0:0:0:0:0:0:1")) {
ip = LOCAL_IP;
}
// 如果通过了多级反向代理X-Forwarded-For的值可能有多个取第一个非unknown的IP
if (ip != null && ip.contains(",")) {
String[] ips = ip.split(",");
for (String s : ips) {
if (!UNKNOWN_IP.equalsIgnoreCase(s.trim())) {
ip = s.trim();
break;
}
}
}
return ip;
}
/**
* 获取本地IP地址
*
* @return 本地IP地址
*/
public static String getLocalIp() {
try {
// 优先获取非本地回环地址
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = networkInterfaces.nextElement();
Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
while (inetAddresses.hasMoreElements()) {
InetAddress inetAddress = inetAddresses.nextElement();
if (!inetAddress.isLoopbackAddress() && inetAddress.isSiteLocalAddress()) {
return inetAddress.getHostAddress();
}
}
}
// 如果没有找到,返回本地回环地址
return InetAddress.getLocalHost().getHostAddress();
} catch (SocketException | UnknownHostException e) {
e.printStackTrace();
return LOCAL_IP;
}
}
/**
* 将IPv4地址转换为long类型
*
* @param ip IPv4地址
* @return long类型IP
*/
public static long ipToLong(String ip) {
if (ip == null || ip.isEmpty()) {
return 0;
}
String[] ipSegments = ip.split("\\.");
if (ipSegments.length != 4) {
return 0;
}
try {
long result = 0;
for (int i = 0; i < 4; i++) {
result = (result << 8) | Integer.parseInt(ipSegments[i]);
}
return result;
} catch (NumberFormatException e) {
return 0;
}
}
/**
* 将long类型IP转换为IPv4地址
*
* @param ip long类型IP
* @return IPv4地址
*/
public static String longToIp(long ip) {
return ((ip >> 24) & 0xFF) + "." +
((ip >> 16) & 0xFF) + "." +
((ip >> 8) & 0xFF) + "." +
(ip & 0xFF);
}
/**
* 判断IP是否为内网IP
*
* @param ip IP地址
* @return 是否为内网IP
*/
public static boolean isInnerIp(String ip) {
if (ip == null || ip.isEmpty()) {
return false;
}
// 本地回环地址
if (LOCAL_IP.equals(ip) || "0:0:0:0:0:0:0:1".equals(ip)) {
return true;
}
long ipLong = ipToLong(ip);
if (ipLong == 0) {
return false;
}
// A类内网10.0.0.0-10.255.255.255
long aBegin = ipToLong("10.0.0.0");
long aEnd = ipToLong("10.255.255.255");
// B类内网172.16.0.0-172.31.255.255
long bBegin = ipToLong("172.16.0.0");
long bEnd = ipToLong("172.31.255.255");
// C类内网192.168.0.0-192.168.255.255
long cBegin = ipToLong("192.168.0.0");
long cEnd = ipToLong("192.168.255.255");
return (ipLong >= aBegin && ipLong <= aEnd) ||
(ipLong >= bBegin && ipLong <= bEnd) ||
(ipLong >= cBegin && ipLong <= cEnd);
}
/**
* 判断IP是否为公网IP
*
* @param ip IP地址
* @return 是否为公网IP
*/
public static boolean isPublicIp(String ip) {
return !isInnerIp(ip) && ValidationUtils.isIpv4(ip);
}
}

View File

@@ -0,0 +1,178 @@
package icu.sunway.ai_spring_example.Utils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
/**
* JSON工具类基于Jackson实现
*/
public class JsonUtils {
private static final ObjectMapper objectMapper = new ObjectMapper();
static {
// 注册Java 8时间模块
JavaTimeModule javaTimeModule = new JavaTimeModule();
// 自定义日期时间序列化格式
javaTimeModule.addSerializer(LocalDateTime.class,
new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DateUtils.FORMAT_DATETIME)));
objectMapper.registerModule(javaTimeModule);
// 配置序列化特性
objectMapper.configure(SerializationFeature.INDENT_OUTPUT, false); // 默认不格式化输出
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); // 日期不使用时间戳格式
// 配置反序列化特性
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // 忽略未知属性
objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); // 允许单个值作为数组
}
/**
* 将对象转换为JSON字符串
*
* @param obj 对象
* @return JSON字符串
*/
public static String toJson(Object obj) {
if (obj == null) {
return null;
}
try {
return objectMapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
e.printStackTrace();
return null;
}
}
/**
* 将对象转换为格式化的JSON字符串
*
* @param obj 对象
* @return 格式化的JSON字符串
*/
public static String toJsonPretty(Object obj) {
if (obj == null) {
return null;
}
try {
ObjectMapper prettyMapper = new ObjectMapper();
prettyMapper.registerModule(new JavaTimeModule());
prettyMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
prettyMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
return prettyMapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
e.printStackTrace();
return null;
}
}
/**
* 将JSON字符串转换为对象
*
* @param json JSON字符串
* @param clazz 对象类型
* @param <T> 泛型
* @return 对象
*/
public static <T> T toObject(String json, Class<T> clazz) {
if (json == null || json.isEmpty()) {
return null;
}
try {
return objectMapper.readValue(json, clazz);
} catch (JsonProcessingException e) {
e.printStackTrace();
return null;
}
}
/**
* 将JSON字符串转换为指定类型的对象支持泛型
*
* @param json JSON字符串
* @param collectionClazz 集合类型
* @param elementClazz 元素类型
* @param <T> 泛型
* @return 指定类型的对象
*/
public static <T> T toObject(String json, Class<?> collectionClazz, Class<?>... elementClazz) {
if (json == null || json.isEmpty()) {
return null;
}
try {
JavaType javaType = objectMapper.getTypeFactory().constructParametricType(collectionClazz, elementClazz);
return objectMapper.readValue(json, javaType);
} catch (JsonProcessingException e) {
e.printStackTrace();
return null;
}
}
/**
* 将JSON字符串转换为List
*
* @param json JSON字符串
* @param clazz 元素类型
* @param <T> 泛型
* @return List
*/
public static <T> List<T> toList(String json, Class<T> clazz) {
return toObject(json, List.class, clazz);
}
/**
* 将JSON字符串转换为Map
*
* @param json JSON字符串
* @param keyClazz 键类型
* @param valueClazz 值类型
* @param <K> 键泛型
* @param <V> 值泛型
* @return Map
*/
public static <K, V> Map<K, V> toMap(String json, Class<K> keyClazz, Class<V> valueClazz) {
return toObject(json, Map.class, keyClazz, valueClazz);
}
/**
* 将对象转换为Map
*
* @param obj 对象
* @return Map
*/
public static Map<String, Object> toMap(Object obj) {
if (obj == null) {
return null;
}
return objectMapper.convertValue(obj, Map.class);
}
/**
* 验证JSON字符串是否有效
*
* @param json JSON字符串
* @return 是否有效
*/
public static boolean isValidJson(String json) {
if (json == null || json.isEmpty()) {
return false;
}
try {
objectMapper.readTree(json);
return true;
} catch (JsonProcessingException e) {
return false;
}
}
}

View File

@@ -0,0 +1,453 @@
package icu.sunway.ai_spring_example.Utils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import jakarta.annotation.Resource;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
@Component
public class RedisUtils {
@Resource
private RedisTemplate<String, Object> redisTemplate;
// ========================== String 类型 ==========================
/**
* 设置缓存
*
* @param key 键
* @param value 值
*/
public void set(String key, Object value) {
redisTemplate.opsForValue().set(key, value);
}
/**
* 设置缓存并设置过期时间
*
* @param key 键
* @param value 值
* @param timeout 过期时间
* @param timeUnit 时间单位
*/
public void set(String key, Object value, long timeout, TimeUnit timeUnit) {
redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
}
/**
* 获取缓存
*
* @param key 键
* @return 值
*/
public Object get(String key) {
return redisTemplate.opsForValue().get(key);
}
/**
* 删除缓存
*
* @param key 键
* @return 是否成功
*/
public Boolean delete(String key) {
return redisTemplate.delete(key);
}
/**
* 批量删除缓存
*
* @param keys 键集合
* @return 删除的数量
*/
public Long delete(Collection<String> keys) {
return redisTemplate.delete(keys);
}
/**
* 判断键是否存在
*
* @param key 键
* @return 是否存在
*/
public Boolean hasKey(String key) {
return redisTemplate.hasKey(key);
}
/**
* 设置过期时间
*
* @param key 键
* @param timeout 过期时间
* @param timeUnit 时间单位
* @return 是否成功
*/
public Boolean expire(String key, long timeout, TimeUnit timeUnit) {
return redisTemplate.expire(key, timeout, timeUnit);
}
/**
* 获取过期时间
*
* @param key 键
* @return 过期时间(秒)
*/
public Long getExpire(String key) {
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
}
/**
* 自增
*
* @param key 键
* @return 自增后的值
*/
public Long increment(String key) {
return redisTemplate.opsForValue().increment(key);
}
/**
* 自增指定步长
*
* @param key 键
* @param delta 步长
* @return 自增后的值
*/
public Long increment(String key, long delta) {
return redisTemplate.opsForValue().increment(key, delta);
}
/**
* 自减
*
* @param key 键
* @return 自减后的值
*/
public Long decrement(String key) {
return redisTemplate.opsForValue().decrement(key);
}
/**
* 自减指定步长
*
* @param key 键
* @param delta 步长
* @return 自减后的值
*/
public Long decrement(String key, long delta) {
return redisTemplate.opsForValue().decrement(key, delta);
}
// ========================== Hash 类型 ==========================
/**
* 设置哈希值
*
* @param key 键
* @param field 字段
* @param value 值
*/
public void hSet(String key, String field, Object value) {
redisTemplate.opsForHash().put(key, field, value);
}
/**
* 设置哈希值并设置过期时间
*
* @param key 键
* @param field 字段
* @param value 值
* @param timeout 过期时间
* @param timeUnit 时间单位
*/
public void hSet(String key, String field, Object value, long timeout, TimeUnit timeUnit) {
redisTemplate.opsForHash().put(key, field, value);
redisTemplate.expire(key, timeout, timeUnit);
}
/**
* 获取哈希值
*
* @param key 键
* @param field 字段
* @return 值
*/
public Object hGet(String key, String field) {
return redisTemplate.opsForHash().get(key, field);
}
/**
* 获取所有哈希值
*
* @param key 键
* @return 哈希值映射
*/
public Map<Object, Object> hGetAll(String key) {
return redisTemplate.opsForHash().entries(key);
}
/**
* 批量设置哈希值
*
* @param key 键
* @param map 哈希值映射
*/
public void hPutAll(String key, Map<String, Object> map) {
redisTemplate.opsForHash().putAll(key, map);
}
/**
* 批量设置哈希值并设置过期时间
*
* @param key 键
* @param map 哈希值映射
* @param timeout 过期时间
* @param timeUnit 时间单位
*/
public void hPutAll(String key, Map<String, Object> map, long timeout, TimeUnit timeUnit) {
redisTemplate.opsForHash().putAll(key, map);
redisTemplate.expire(key, timeout, timeUnit);
}
/**
* 删除哈希字段
*
* @param key 键
* @param fields 字段数组
* @return 删除的数量
*/
public Long hDelete(String key, Object... fields) {
return redisTemplate.opsForHash().delete(key, fields);
}
/**
* 判断哈希字段是否存在
*
* @param key 键
* @param field 字段
* @return 是否存在
*/
public Boolean hHasKey(String key, String field) {
return redisTemplate.opsForHash().hasKey(key, field);
}
// ========================== List 类型 ==========================
/**
* 左侧添加元素
*
* @param key 键
* @param value 值
* @return 列表长度
*/
public Long lLeftPush(String key, Object value) {
return redisTemplate.opsForList().leftPush(key, value);
}
/**
* 左侧批量添加元素
*
* @param key 键
* @param values 值集合
* @return 列表长度
*/
public Long lLeftPushAll(String key, Collection<Object> values) {
return redisTemplate.opsForList().leftPushAll(key, values);
}
/**
* 右侧添加元素
*
* @param key 键
* @param value 值
* @return 列表长度
*/
public Long lRightPush(String key, Object value) {
return redisTemplate.opsForList().rightPush(key, value);
}
/**
* 右侧批量添加元素
*
* @param key 键
* @param values 值集合
* @return 列表长度
*/
public Long lRightPushAll(String key, Collection<Object> values) {
return redisTemplate.opsForList().rightPushAll(key, values);
}
/**
* 左侧弹出元素
*
* @param key 键
* @return 值
*/
public Object lLeftPop(String key) {
return redisTemplate.opsForList().leftPop(key);
}
/**
* 右侧弹出元素
*
* @param key 键
* @return 值
*/
public Object lRightPop(String key) {
return redisTemplate.opsForList().rightPop(key);
}
/**
* 获取列表长度
*
* @param key 键
* @return 列表长度
*/
public Long lSize(String key) {
return redisTemplate.opsForList().size(key);
}
/**
* 获取列表元素
*
* @param key 键
* @param start 开始索引
* @param end 结束索引
* @return 元素列表
*/
public List<Object> lRange(String key, long start, long end) {
return redisTemplate.opsForList().range(key, start, end);
}
// ========================== Set 类型 ==========================
/**
* 添加元素到集合
*
* @param key 键
* @param values 值集合
* @return 添加的数量
*/
public Long sAdd(String key, Object... values) {
return redisTemplate.opsForSet().add(key, values);
}
/**
* 从集合中移除元素
*
* @param key 键
* @param values 值集合
* @return 移除的数量
*/
public Long sRemove(String key, Object... values) {
return redisTemplate.opsForSet().remove(key, values);
}
/**
* 获取集合所有元素
*
* @param key 键
* @return 元素集合
*/
public Set<Object> sMembers(String key) {
return redisTemplate.opsForSet().members(key);
}
/**
* 判断元素是否在集合中
*
* @param key 键
* @param value 值
* @return 是否存在
*/
public Boolean sIsMember(String key, Object value) {
return redisTemplate.opsForSet().isMember(key, value);
}
/**
* 获取集合大小
*
* @param key 键
* @return 集合大小
*/
public Long sSize(String key) {
return redisTemplate.opsForSet().size(key);
}
// ========================== ZSet 类型 ==========================
/**
* 添加元素到有序集合
*
* @param key 键
* @param value 值
* @param score 分数
* @return 是否成功
*/
public Boolean zAdd(String key, Object value, double score) {
return redisTemplate.opsForZSet().add(key, value, score);
}
/**
* 从有序集合中移除元素
*
* @param key 键
* @param values 值集合
* @return 移除的数量
*/
public Long zRemove(String key, Object... values) {
return redisTemplate.opsForZSet().remove(key, values);
}
/**
* 获取有序集合元素(按分数升序)
*
* @param key 键
* @param start 开始索引
* @param end 结束索引
* @return 元素集合
*/
public Set<Object> zRange(String key, long start, long end) {
return redisTemplate.opsForZSet().range(key, start, end);
}
/**
* 获取有序集合元素(按分数降序)
*
* @param key 键
* @param start 开始索引
* @param end 结束索引
* @return 元素集合
*/
public Set<Object> zReverseRange(String key, long start, long end) {
return redisTemplate.opsForZSet().reverseRange(key, start, end);
}
/**
* 获取元素分数
*
* @param key 键
* @param value 值
* @return 分数
*/
public Double zScore(String key, Object value) {
return redisTemplate.opsForZSet().score(key, value);
}
/**
* 获取有序集合大小
*
* @param key 键
* @return 集合大小
*/
public Long zSize(String key) {
return redisTemplate.opsForZSet().size(key);
}
}

View File

@@ -0,0 +1,192 @@
package icu.sunway.ai_spring_example.Utils;
import lombok.Data;
/**
* 响应结果工具类
*/
public class ResponseUtils {
/**
* 响应状态码常量
*/
public static final int SUCCESS = 200; // 成功
public static final int FAIL = 500; // 失败
public static final int BAD_REQUEST = 400; // 请求参数错误
public static final int UNAUTHORIZED = 401; // 未授权
public static final int FORBIDDEN = 403; // 禁止访问
public static final int NOT_FOUND = 404; // 资源不存在
public static final int METHOD_NOT_ALLOWED = 405; // 方法不允许
public static final int INTERNAL_SERVER_ERROR = 500;// 服务器内部错误
/**
* 统一响应结果对象
*/
@Data
public static class Response<T> {
private int code; // 状态码
private String message; // 消息
private T data; // 数据
private long timestamp; // 时间戳
public Response() {
this.timestamp = System.currentTimeMillis();
}
public Response(int code, String message) {
this();
this.code = code;
this.message = message;
}
public Response(int code, String message, T data) {
this(code, message);
this.data = data;
}
}
/**
* 成功响应
*
* @return 响应结果
*/
public static <T> Response<T> success() {
return new Response<>(SUCCESS, "操作成功");
}
/**
* 成功响应
*
* @param data 数据
* @return 响应结果
*/
public static <T> Response<T> success(T data) {
return new Response<>(SUCCESS, "操作成功", data);
}
/**
* 成功响应
*
* @param message 消息
* @param data 数据
* @return 响应结果
*/
public static <T> Response<T> success(String message, T data) {
return new Response<>(SUCCESS, message, data);
}
/**
* 失败响应
*
* @return 响应结果
*/
public static <T> Response<T> fail() {
return new Response<>(FAIL, "操作失败");
}
/**
* 失败响应
*
* @param message 消息
* @return 响应结果
*/
public static <T> Response<T> fail(String message) {
return new Response<>(FAIL, message);
}
/**
* 失败响应
*
* @param code 状态码
* @param message 消息
* @return 响应结果
*/
public static <T> Response<T> fail(int code, String message) {
return new Response<>(code, message);
}
/**
* 参数错误响应
*
* @return 响应结果
*/
public static <T> Response<T> badRequest() {
return new Response<>(BAD_REQUEST, "参数错误");
}
/**
* 参数错误响应
*
* @param message 消息
* @return 响应结果
*/
public static <T> Response<T> badRequest(String message) {
return new Response<>(BAD_REQUEST, message);
}
/**
* 未授权响应
*
* @return 响应结果
*/
public static <T> Response<T> unauthorized() {
return new Response<>(UNAUTHORIZED, "未授权");
}
/**
* 未授权响应
*
* @param message 消息
* @return 响应结果
*/
public static <T> Response<T> unauthorized(String message) {
return new Response<>(UNAUTHORIZED, message);
}
/**
* 禁止访问响应
*
* @return 响应结果
*/
public static <T> Response<T> forbidden() {
return new Response<>(FORBIDDEN, "禁止访问");
}
/**
* 资源不存在响应
*
* @return 响应结果
*/
public static <T> Response<T> notFound() {
return new Response<>(NOT_FOUND, "资源不存在");
}
/**
* 资源不存在响应
*
* @param message 消息
* @return 响应结果
*/
public static <T> Response<T> notFound(String message) {
return new Response<>(NOT_FOUND, message);
}
/**
* 服务器内部错误响应
*
* @return 响应结果
*/
public static <T> Response<T> internalServerError() {
return new Response<>(INTERNAL_SERVER_ERROR, "服务器内部错误");
}
/**
* 服务器内部错误响应
*
* @param message 消息
* @return 响应结果
*/
public static <T> Response<T> internalServerError(String message) {
return new Response<>(INTERNAL_SERVER_ERROR, message);
}
}

View File

@@ -0,0 +1,272 @@
package icu.sunway.ai_spring_example.Utils;
import java.util.regex.Pattern;
/**
* 验证工具类
*/
public class ValidationUtils {
/**
* 正则表达式:邮箱
*/
private static final String REGEX_EMAIL = "^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$";
/**
* 正则表达式:手机号(中国大陆)
*/
private static final String REGEX_PHONE = "^1[3-9]\\d{9}$";
/**
* 正则表达式身份证号18位
*/
private static final String REGEX_ID_CARD = "^[1-9]\\d{5}(18|19|20)\\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\\d|3[01])\\d{3}[\\dXx]$";
/**
* 正则表达式URL
*/
private static final String REGEX_URL = "^(https?|ftp):\\/\\/[^\\s/$.?#].[^\\s]*$";
/**
* 正则表达式IPv4
*/
private static final String REGEX_IPV4 = "^((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$";
/**
* 正则表达式密码至少8位包含字母和数字
*/
private static final String REGEX_PASSWORD = "^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{8,}$";
/**
* 正则表达式强密码至少8位包含大写字母、小写字母和数字
*/
private static final String REGEX_STRONG_PASSWORD = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)[a-zA-Z\\d]{8,}$";
/**
* 正则表达式用户名4-20位字母、数字、下划线
*/
private static final String REGEX_USERNAME = "^[a-zA-Z0-9_]{4,20}$";
/**
* 正则表达式:中文字符
*/
private static final String REGEX_CHINESE = "^[\\u4e00-\\u9fa5]+$";
/**
* 验证邮箱
*
* @param email 邮箱
* @return 是否有效
*/
public static boolean isEmail(String email) {
if (email == null || email.isEmpty()) {
return false;
}
return Pattern.matches(REGEX_EMAIL, email);
}
/**
* 验证手机号(中国大陆)
*
* @param phone 手机号
* @return 是否有效
*/
public static boolean isPhone(String phone) {
if (phone == null || phone.isEmpty()) {
return false;
}
return Pattern.matches(REGEX_PHONE, phone);
}
/**
* 验证身份证号18位
*
* @param idCard 身份证号
* @return 是否有效
*/
public static boolean isIdCard(String idCard) {
if (idCard == null || idCard.isEmpty()) {
return false;
}
// 基本格式验证
if (!Pattern.matches(REGEX_ID_CARD, idCard)) {
return false;
}
// 校验码验证
int[] weights = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
char[] checkCodes = { '1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2' };
int sum = 0;
for (int i = 0; i < 17; i++) {
sum += (idCard.charAt(i) - '0') * weights[i];
}
char checkCode = checkCodes[sum % 11];
return Character.toUpperCase(idCard.charAt(17)) == checkCode;
}
/**
* 验证URL
*
* @param url URL
* @return 是否有效
*/
public static boolean isUrl(String url) {
if (url == null || url.isEmpty()) {
return false;
}
return Pattern.matches(REGEX_URL, url);
}
/**
* 验证IPv4
*
* @param ip IPv4地址
* @return 是否有效
*/
public static boolean isIpv4(String ip) {
if (ip == null || ip.isEmpty()) {
return false;
}
return Pattern.matches(REGEX_IPV4, ip);
}
/**
* 验证密码至少8位包含字母和数字
*
* @param password 密码
* @return 是否有效
*/
public static boolean isPassword(String password) {
if (password == null || password.isEmpty()) {
return false;
}
return Pattern.matches(REGEX_PASSWORD, password);
}
/**
* 验证强密码至少8位包含大写字母、小写字母和数字
*
* @param password 密码
* @return 是否有效
*/
public static boolean isStrongPassword(String password) {
if (password == null || password.isEmpty()) {
return false;
}
return Pattern.matches(REGEX_STRONG_PASSWORD, password);
}
/**
* 验证用户名4-20位字母、数字、下划线
*
* @param username 用户名
* @return 是否有效
*/
public static boolean isUsername(String username) {
if (username == null || username.isEmpty()) {
return false;
}
return Pattern.matches(REGEX_USERNAME, username);
}
/**
* 验证中文字符
*
* @param str 字符串
* @return 是否有效
*/
public static boolean isChinese(String str) {
if (str == null || str.isEmpty()) {
return false;
}
return Pattern.matches(REGEX_CHINESE, str);
}
/**
* 验证字符串是否为空
*
* @param str 字符串
* @return 是否为空
*/
public static boolean isEmpty(String str) {
return str == null || str.isEmpty();
}
/**
* 验证字符串是否不为空
*
* @param str 字符串
* @return 是否不为空
*/
public static boolean isNotEmpty(String str) {
return !isEmpty(str);
}
/**
* 验证字符串长度是否在指定范围内
*
* @param str 字符串
* @param min 最小长度
* @param max 最大长度
* @return 是否在指定范围内
*/
public static boolean isLengthBetween(String str, int min, int max) {
if (str == null) {
return false;
}
int length = str.length();
return length >= min && length <= max;
}
/**
* 验证数字是否在指定范围内
*
* @param num 数字
* @param min 最小值
* @param max 最大值
* @return 是否在指定范围内
*/
public static boolean isNumberBetween(int num, int min, int max) {
return num >= min && num <= max;
}
/**
* 验证数字是否在指定范围内
*
* @param num 数字
* @param min 最小值
* @param max 最大值
* @return 是否在指定范围内
*/
public static boolean isNumberBetween(long num, long min, long max) {
return num >= min && num <= max;
}
/**
* 验证数字是否为正数
*
* @param num 数字
* @return 是否为正数
*/
public static boolean isPositiveNumber(Number num) {
if (num == null) {
return false;
}
return num.doubleValue() > 0;
}
/**
* 验证数字是否为非负数
*
* @param num 数字
* @return 是否为非负数
*/
public static boolean isNonNegativeNumber(Number num) {
if (num == null) {
return false;
}
return num.doubleValue() >= 0;
}
}

View File

@@ -0,0 +1,24 @@
spring:
application:
name: ai-spring-example
# 动态多数据源配置
datasource:
dynamic:
primary: master
strict: false
datasource:
master:
url: # 请替换为您的数据库URL
username: # 请替换为您的数据库用户名
password: # 请替换为您的数据库密码
driver-class-name: com.mysql.cj.jdbc.Driver
# Redis配置
data:
redis:
host: # 请替换为您的Redis主机
port: 6379
password: # 请替换为您的Redis密码
database: 0
server:
port: 8080