Skip to content

后端工具类

Vben Admin 提供了 12 个后端工具类,覆盖常见的业务场景。

工具类列表

工具类说明主要功能
ExcelUtilsExcel 处理导入、导出、模板下载
FileDownloadUtils文件下载本地文件、网络文件、ZIP 打包
DesensitizeUtils数据脱敏8 种脱敏类型
CacheUtils缓存工具Redis 操作
ValidationUtils数据验证手机号、身份证等验证
LockUtils分布式锁Redis 分布式锁
IpUtilsIP 工具获取真实 IP、判断内网
JsonUtilsJSON 工具序列化、格式化
DateUtils日期工具日期格式化、计算
StringUtils字符串工具字符串处理
CollectionUtils集合工具集合操作
BeanUtilsBean 工具对象拷贝、转换

ExcelUtils

基于 EasyExcel 的 Excel 处理工具。

导出 Excel

java
@GetMapping("/export")
public void exportUsers(HttpServletResponse response) {
    List<User> users = userService.list();
    ExcelUtils.exportExcel(users, User.class, "用户列表", response);
}

导入 Excel

java
@PostMapping("/import")
public R<Void> importUsers(@RequestParam("file") MultipartFile file) {
    List<User> users = ExcelUtils.importExcel(file, User.class);
    userService.saveBatch(users);
    return R.ok();
}

下载模板

java
@GetMapping("/template")
public void downloadTemplate(HttpServletResponse response) {
    ExcelUtils.downloadTemplate(User.class, "用户导入模板", response);
}

自定义导出

java
@GetMapping("/export/custom")
public void exportCustom(HttpServletResponse response) {
    List<User> users = userService.list();
    
    ExcelUtils.exportExcel(
        users,
        User.class,
        "用户列表",
        "Sheet1",
        response,
        new ExcelWriterBuilder()
            .registerWriteHandler(new CustomCellWriteHandler())
            .build()
    );
}

FileDownloadUtils

文件下载工具类。

下载本地文件

java
@GetMapping("/download/local")
public void downloadLocal(HttpServletResponse response) {
    String filePath = "/data/files/document.pdf";
    FileDownloadUtils.downloadFile(filePath, "文档.pdf", response);
}

下载网络文件

java
@GetMapping("/download/remote")
public void downloadRemote(HttpServletResponse response) {
    String url = "https://example.com/file.pdf";
    FileDownloadUtils.downloadFromUrl(url, "文件.pdf", response);
}

打包下载

java
@GetMapping("/download/zip")
public void downloadZip(HttpServletResponse response) {
    Map<String, String> files = new HashMap<>();
    files.put("文件1.txt", "/data/files/file1.txt");
    files.put("文件2.pdf", "/data/files/file2.pdf");
    
    FileDownloadUtils.downloadZip(files, "打包文件.zip", response);
}

下载字节数组

java
@GetMapping("/download/bytes")
public void downloadBytes(HttpServletResponse response) {
    byte[] data = generateReport();
    FileDownloadUtils.downloadBytes(data, "报告.pdf", response);
}

DesensitizeUtils

数据脱敏工具类。

支持的脱敏类型

java
public enum DesensitizeType {
    PHONE,      // 手机号:138****1234
    ID_CARD,    // 身份证:110***********1234
    EMAIL,      // 邮箱:abc***@example.com
    BANK_CARD,  // 银行卡:6222 **** **** 1234
    NAME,       // 姓名:张*
    ADDRESS,    // 地址:北京市朝阳区****
    PASSWORD,   // 密码:******
    CAR_NO      // 车牌号:京A****1
}

使用示例

java
// 手机号脱敏
String phone = "13812341234";
String masked = DesensitizeUtils.desensitize(phone, DesensitizeType.PHONE);
// 输出:138****1234

// 身份证脱敏
String idCard = "110101199001011234";
String masked = DesensitizeUtils.desensitize(idCard, DesensitizeType.ID_CARD);
// 输出:110***********1234

// 邮箱脱敏
String email = "example@gmail.com";
String masked = DesensitizeUtils.desensitize(email, DesensitizeType.EMAIL);
// 输出:exa***@gmail.com

注解方式

java
@Data
public class UserVO {
    private Long id;
    private String username;
    
    @Desensitize(type = DesensitizeType.PHONE)
    private String phone;
    
    @Desensitize(type = DesensitizeType.ID_CARD)
    private String idCard;
    
    @Desensitize(type = DesensitizeType.EMAIL)
    private String email;
}

CacheUtils

Redis 缓存工具类。

基础操作

java
// 设置缓存
CacheUtils.set("key", "value");
CacheUtils.set("key", "value", 3600); // 设置过期时间(秒)

// 获取缓存
String value = CacheUtils.get("key");

// 删除缓存
CacheUtils.delete("key");

// 判断是否存在
boolean exists = CacheUtils.exists("key");

Hash 操作

java
// 设置 Hash
CacheUtils.hSet("user:1", "name", "张三");
CacheUtils.hSet("user:1", "age", "25");

// 获取 Hash
String name = CacheUtils.hGet("user:1", "name");

// 获取所有 Hash
Map<String, String> user = CacheUtils.hGetAll("user:1");

// 删除 Hash 字段
CacheUtils.hDelete("user:1", "age");

Set 操作

java
// 添加到 Set
CacheUtils.sAdd("tags", "Java", "Spring", "Redis");

// 获取 Set 成员
Set<String> tags = CacheUtils.sMembers("tags");

// 判断是否是成员
boolean isMember = CacheUtils.sIsMember("tags", "Java");

// 删除成员
CacheUtils.sRemove("tags", "Redis");

List 操作

java
// 添加到 List
CacheUtils.lPush("logs", "log1", "log2", "log3");

// 获取 List
List<String> logs = CacheUtils.lRange("logs", 0, -1);

// 获取 List 长度
long size = CacheUtils.lSize("logs");

ValidationUtils

数据验证工具类。

手机号验证

java
boolean isValid = ValidationUtils.isPhone("13812341234");
// 返回:true

boolean isValid = ValidationUtils.isPhone("12345678901");
// 返回:false

身份证验证

java
boolean isValid = ValidationUtils.isIdCard("110101199001011234");
// 返回:true(验证格式和校验位)

邮箱验证

java
boolean isValid = ValidationUtils.isEmail("example@gmail.com");
// 返回:true

银行卡验证

java
boolean isValid = ValidationUtils.isBankCard("6222021234567890123");
// 返回:true(验证 Luhn 算法)

车牌号验证

java
boolean isValid = ValidationUtils.isCarNo("京A12345");
// 返回:true

URL 验证

java
boolean isValid = ValidationUtils.isUrl("https://www.example.com");
// 返回:true

LockUtils

分布式锁工具类。

基础用法

java
// 获取锁并执行
LockUtils.executeWithLock("order:" + userId, () -> {
    // 业务逻辑
    orderService.createOrder(order);
});

自定义超时时间

java
// 锁超时时间 30 秒
LockUtils.executeWithLock("order:" + userId, 30, () -> {
    // 业务逻辑
    orderService.createOrder(order);
});

手动加锁解锁

java
String lockKey = "order:" + userId;
boolean locked = LockUtils.tryLock(lockKey, 30);

if (locked) {
    try {
        // 业务逻辑
        orderService.createOrder(order);
    } finally {
        LockUtils.unlock(lockKey);
    }
} else {
    throw new BusinessException("操作过于频繁,请稍后再试");
}

可重入锁

java
LockUtils.executeWithReentrantLock("order:" + userId, () -> {
    // 支持重入的业务逻辑
    orderService.createOrder(order);
    orderService.updateInventory(order);
});

IpUtils

IP 工具类。

获取真实 IP

java
@GetMapping("/info")
public R<String> getInfo(HttpServletRequest request) {
    String ip = IpUtils.getIpAddr(request);
    return R.ok(ip);
}

判断内网 IP

java
String ip = "192.168.1.1";
boolean isInner = IpUtils.isInnerIp(ip);
// 返回:true

IP 转长整型

java
String ip = "192.168.1.1";
long ipLong = IpUtils.ipToLong(ip);
// 返回:3232235777

String ip2 = IpUtils.longToIp(ipLong);
// 返回:"192.168.1.1"

JsonUtils

JSON 工具类。

对象转 JSON

java
User user = new User();
user.setName("张三");
user.setAge(25);

String json = JsonUtils.toJson(user);
// 返回:{"name":"张三","age":25}

JSON 转对象

java
String json = "{\"name\":\"张三\",\"age\":25}";
User user = JsonUtils.parseObject(json, User.class);

JSON 转 List

java
String json = "[{\"name\":\"张三\"},{\"name\":\"李四\"}]";
List<User> users = JsonUtils.parseArray(json, User.class);

格式化 JSON

java
String json = "{\"name\":\"张三\",\"age\":25}";
String formatted = JsonUtils.formatJson(json);
// 返回格式化后的 JSON

完整示例

用户导出示例

java
@RestController
@RequestMapping("/api/users")
public class UserController {
    
    @Autowired
    private UserService userService;
    
    @GetMapping("/export")
    @RateLimit(count = 1, time = 60)
    public void export(HttpServletResponse response) {
        List<User> users = userService.list();
        
        // 转换为 VO 并脱敏
        List<UserVO> voList = users.stream()
            .map(user -> {
                UserVO vo = new UserVO();
                BeanUtils.copyProperties(user, vo);
                return vo;
            })
            .collect(Collectors.toList());
        
        // 导出 Excel
        ExcelUtils.exportExcel(voList, UserVO.class, "用户列表", response);
    }
    
    @PostMapping("/import")
    public R<Void> importUsers(@RequestParam("file") MultipartFile file) {
        // 导入 Excel
        List<UserVO> voList = ExcelUtils.importExcel(file, UserVO.class);
        
        // 验证数据
        for (UserVO vo : voList) {
            if (!ValidationUtils.isPhone(vo.getPhone())) {
                throw new BusinessException("手机号格式错误:" + vo.getPhone());
            }
            if (!ValidationUtils.isEmail(vo.getEmail())) {
                throw new BusinessException("邮箱格式错误:" + vo.getEmail());
            }
        }
        
        // 保存数据
        List<User> users = voList.stream()
            .map(vo -> {
                User user = new User();
                BeanUtils.copyProperties(vo, user);
                return user;
            })
            .collect(Collectors.toList());
        
        userService.saveBatch(users);
        
        // 清除缓存
        CacheUtils.delete("user:list");
        
        return R.ok();
    }
}

注意事项

注意

  1. ExcelUtils 需要引入 EasyExcel 依赖
  2. CacheUtils 需要配置 Redis 连接
  3. LockUtils 基于 Redis 实现,需要确保 Redis 可用
  4. 文件下载时注意设置正确的 Content-Type

提示

  • 使用 ExcelUtils 时建议设置合理的数据量限制
  • 分布式锁要注意设置合理的超时时间
  • 数据脱敏要根据实际需求选择合适的脱敏类型

相关链接

MIT License