专业的编程技术博客社区

网站首页 > 博客文章 正文

高效编程Hutool工具分析:Hutool设计方案与使用案例(第一部分)

baijin 2024-11-01 11:16:17 博客文章 7 ℃ 0 评论

Hutool 是一个 Java 工具包集合,旨在提供一系列简单、易用的工具类,帮助开发者在项目开发中减少重复代码,提高开发效率。它涵盖了文件操作、日期处理、加密解密、HTTP通信等多个领域,通过静态方法封装,使得 Java 代码更加简洁。Hutool 以其小而全的特点,成为 Java 开发者的工具箱,无论是大型项目还是小型应用,都能从中受益。

  1. 支持多种构建工具:与 Maven、Gradle 等多种构建工具兼容。

肖哥弹架构 跟大家“弹弹” 框架注解使用,需要代码关注

欢迎 点赞,关注,评论。

关注公号Solomon肖哥弹架构获取更多精彩内容

历史热点文章

  • 28个验证注解,通过业务案例让你精通Java数据校验(收藏篇)
  • Java 8函数式编程全攻略:43种函数式业务代码实战案例解析(收藏版)
  • 69 个Spring mvc 全部注解:真实业务使用案例说明(必须收藏)
  • 24 个Spring bean 全部注解:真实业务使用案例说明(必须收藏)
  • MySQL索引完全手册:真实业务图文讲解17种索引运用技巧(必须收藏)
  • 一个项目代码讲清楚DO/PO/BO/AO/E/DTO/DAO/ POJO/VO

0. Hutool设计方案

1. StrUtil - 字符串工具类

常用方法

  1. 字符串空值检查 ( StrUtil.isBlank): 检查用户名是否为空。
  2. 长度验证 ( StrUtil.isBetween): 验证用户名长度是否在指定范围内。
  3. 正则表达式匹配 ( StrUtil.isMatch): 检查密码是否符合特定的格式要求。
  4. 邮箱格式验证 ( StrUtil.isEmail): 确保邮箱地址符合标准格式。
  5. 手机号格式验证 ( StrUtil.isMobile): 确保手机号符合标准格式。
  6. 字符串格式化 ( StrUtil.format): 用于生成欢迎信息和日志记录。
  7. 随机字符串生成 ( StrUtil.randomString): 生成随机验证码。
  8. 日志记录: 记录用户注册的详细信息。
import cn.hutool.core.util.StrUtil;
public class RegistrationSystem {
    public void registerUser(String username, String password, String email, String phoneNumber) {
        // 验证用户名:非空且长度在5到20之间
        if (StrUtil.isBlank(username)) {
            throw new IllegalArgumentException("用户名不能为空");
        }
        if (!StrUtil.isBetween(username, 5, 20)) {
            throw new IllegalArgumentException("用户名长度必须在5到20之间");
        }

        // 验证密码:非空且包含数字和字母
        if (StrUtil.isBlank(password)) {
            throw new IllegalArgumentException("密码不能为空");
        }
        if (!StrUtil.isMatch(password, "^(?=.*[0-9])(?=.*[a-zA-Z]).{6,}#34;)) {
            throw new IllegalArgumentException("密码必须包含至少一个数字和一个字母,长度至少6位");
        }

        // 验证邮箱:格式正确
        if (!StrUtil.isEmail(email)) {
            throw new IllegalArgumentException("邮箱格式不正确");
        }

        // 验证电话号码:格式正确
        if (!StrUtil.isMobile(phoneNumber)) {
            throw new IllegalArgumentException("电话号码格式不正确");
        }

        // 格式化欢迎信息
        String welcomeMessage = StrUtil.format("欢迎 {}, 感谢您注册我们的服务!", username);
        System.out.println(welcomeMessage);

        // 记录日志
        logRegistration(username, email, phoneNumber);

        // 模拟发送验证邮件
        sendVerificationEmail(email);
    }

    private void logRegistration(String username, String email, String phoneNumber) {
        String logMessage = StrUtil.format("新用户注册: 用户名: {}, 邮箱: {}, 电话: {}",
                                            username, email, phoneNumber);
        System.out.println("日志记录: " + logMessage);
    }

    private void sendVerificationEmail(String email) {
        String verificationCode = StrUtil.randomString(6);
        String subject = "验证您的邮箱";
        String content = StrUtil.format("您的验证码是: {}", verificationCode);
        System.out.println("发送邮件到: " + email);
        System.out.println("邮件主题: " + subject);
        System.out.println("邮件内容: " + content);
    }

    public static void main(String[] args) {
        RegistrationSystem system = new RegistrationSystem();
        system.registerUser("john_doe", "Password123", "john@example.com", "12345678901");
    }
}

2. ArrayUtil - 数组工具类

常用方法

  1. 数组是否为空 ( ArrayUtil.isEmpty)
  2. 数组转换为列表 ( ArrayUtil.asList)
  3. 查找数组中元素的索引 ( ArrayUtil.indexOf)
  4. 数组填充 ( ArrayUtil.fill)
  5. 数组合并 ( ArrayUtil.addAll)
  6. 数组切割 ( ArrayUtil.subarray)
  7. 数组内容比较 ( ArrayUtil.equals)
import cn.hutool.core.collection.ArrayUtil;
import java.util.List;

public class LibraryManagementSystem {

    /**
     * 搜索书籍是否存在
     * 
     * @param bookArray 书籍数组
     * @param bookTitle 要搜索的书籍标题
     * @return 存在返回 true,否则返回 false
     */
    public boolean searchBook(String[] bookArray, String bookTitle) {
        // 使用 ArrayUtil.indexOf 查找书籍是否存在
        int index = ArrayUtil.indexOf(bookArray, bookTitle);
        return index != -1;
    }

    /**
     * 添加新书到书籍数组
     * 
     * @param bookArray 书籍数组
     * @param newBook 新书标题
     * @return 更新后的书籍数组
     */
    public String[] addBook(String[] bookArray, String newBook) {
        // 使用 ArrayUtil.addAll 合并数组
        return ArrayUtil.addAll(bookArray, newBook);
    }

    /**
     * 从数组中移除书籍
     * 
     * @param bookArray 书籍数组
     * @param bookToRemove 要移除的书籍标题
     * @return 更新后的书籍数组
     */
    public String[] removeBook(String[] bookArray, String bookToRemove) {
        // 使用 ArrayUtil.remove 移除元素
        return ArrayUtil.remove(bookArray, bookToRemove);
    }

    /**
     * 显示所有书籍
     * 
     * @param bookArray 书籍数组
     */
    public void displayBooks(String[] bookArray) {
        // 使用 ArrayUtil.isNotEmpty 检查数组是否非空
        if (ArrayUtil.isNotEmpty(bookArray)) {
            for (String book : bookArray) {
                System.out.println(book);
            }
        } else {
            System.out.println("No books available.");
        }
    }

    public static void main(String[] args) {
        LibraryManagementSystem library = new LibraryManagementSystem();
        String[] books = {"Book One", "Book Two", "Book Three"};

        // 搜索书籍
        boolean isBookFound = library.searchBook(books, "Book Two");
        System.out.println("Is 'Book Two' found? " + isBookFound);

        // 添加新书
        books = library.addBook(books, "Book Four");
        library.displayBooks(books);

        // 移除书籍
        books = library.removeBook(books, "Book One");
        library.displayBooks(books);
    }
}

3、ArrayUtil - 数组工具类

常用方法

  1. 检查数组是否为空 ( ArrayUtil.isEmpty)
  2. 检查数组是否非空 ( ArrayUtil.isNotEmpty)
  3. 数组转换为列表 ( ArrayUtil.asList)
  4. 查找数组中元素的索引 ( ArrayUtil.indexOf)
  5. 数组填充 ( ArrayUtil.fill)
  6. 数组合并 ( ArrayUtil.addAll)
  7. 数组切割 ( ArrayUtil.subarray)
  8. 数组内容比较 ( ArrayUtil.equals)
  9. 创建数组 ( ArrayUtil.newArray)
  10. 数组去重 ( ArrayUtil.unique)
  11. 数组排序 ( ArrayUtil.sort)
import cn.hutool.core.collection.ArrayUtil;
import cn.hutool.core.util.RandomUtil;

public class LibraryManagementSystem {

    /**
     * 搜索书籍是否存在
     * 
     * @param bookArray 书籍数组
     * @param bookTitle 要搜索的书籍标题
     * @return 存在返回 true,否则返回 false
     */
    public boolean searchBook(String[] bookArray, String bookTitle) {
        // 使用 ArrayUtil.indexOf 查找书籍是否存在
        return ArrayUtil.indexOf(bookArray, bookTitle) > -1;
    }

    /**
     * 添加新书到书籍数组
     * 
     * @param bookArray 书籍数组
     * @param newBook 新书标题
     * @return 更新后的书籍数组
     */
    public String[] addBook(String[] bookArray, String newBook) {
        // 使用 ArrayUtil.addAll 合并数组
        return ArrayUtil.addAll(bookArray, newBook);
    }

    /**
     * 从数组中移除书籍
     * 
     * @param bookArray 书籍数组
     * @param bookToRemove 要移除的书籍标题
     * @return 更新后的书籍数组
     */
    public String[] removeBook(String[] bookArray, String bookToRemove) {
        // 使用 ArrayUtil.remove 移除元素
        return ArrayUtil.remove(bookArray, bookToRemove);
    }

    /**
     * 显示所有书籍
     * 
     * @param bookArray 书籍数组
     */
    public void displayBooks(String[] bookArray) {
        // 使用 ArrayUtil.isNotEmpty 检查数组是否非空
        if (ArrayUtil.isNotEmpty(bookArray)) {
            for (String book : bookArray) {
                System.out.println(book);
            }
        } else {
            System.out.println("No books available.");
        }
    }

    /**
     * 创建一个新的书籍数组
     * 
     * @param count 数组大小
     * @return 新的书籍数组
     */
    public String[] createBooks(int count) {
        // 使用 ArrayUtil.newArray 创建新数组
        return ArrayUtil.newArray(String.class, count);
    }

    /**
     * 填充书籍数组
     * 
     * @param bookArray 书籍数组
     * @param value 填充值
     */
    public void fillBooks(String[] bookArray, String value) {
        // 使用 ArrayUtil.fill 填充数组
        ArrayUtil.fill(bookArray, value);
    }

    /**
     * 切割书籍数组
     * 
     * @param bookArray 书籍数组
     * @param start 开始索引
     * @param end 结束索引
     * @return 切割后的数组
     */
    public String[] sliceBooks(String[] bookArray, int start, int end) {
        // 使用 ArrayUtil.subarray 切割数组
        return ArrayUtil.subarray(bookArray, start, end);
    }

    /**
     * 比较两个书籍数组是否相等
     * 
     * @param array1 第一个数组
     * @param array2 第二个数组
     * @return 是否相等
     */
    public boolean compareBooks(String[] array1, String[] array2) {
        // 使用 ArrayUtil.equals 比较数组
        return ArrayUtil.equals(array1, array2);
    }

    /**
     * 排序书籍数组
     * 
     * @param bookArray 书籍数组
     */
    public void sortBooks(String[] bookArray) {
        // 使用 ArrayUtil.sort 对数组进行排序
        ArrayUtil.sort(bookArray);
        System.out.println("Sorted Books: " + ArrayUtil.toString(bookArray));
    }

    public static void main(String[] args) {
        LibraryManagementSystem library = new LibraryManagementSystem();
        String[] books = {"Book One", "Book Two", "Book Three"};

        // 搜索书籍
        boolean isBookFound = library.searchBook(books, "Book Two");
        System.out.println("Is 'Book Two' found? " + isBookFound);

        // 添加新书
        books = library.addBook(books, "Book Four");
        library.displayBooks(books);

        // 移除书籍
        books = library.removeBook(books, "Book One");
        library.displayBooks(books);

        // 创建新书籍数组
        String[] newBooks = library.createBooks(5);
        library.fillBooks(newBooks, "New Book");
        library.displayBooks(newBooks);

        // 切割书籍数组
        String[] slicedBooks = library.sliceBooks(books, 1, 3);
        library.displayBooks(slicedBooks);

        // 比较书籍数组
        boolean areBooksEqual = library.compareBooks(books, slicedBooks);
        System.out.println("Are books equal? " + areBooksEqual);

        // 排序书籍
        library.sortBooks(books);
    }
}

4. RandomUtil - 随机工具类

常用方法

  1. 生成随机整数 ( RandomUtil.randomInt)
  2. 生成指定范围内的随机整数 ( RandomUtil.randomInt(intmin,intmax))
  3. 生成随机长整数 ( RandomUtil.randomLong)
  4. 生成指定范围内的随机长整数 ( RandomUtil.randomLong(longmin,longmax))
  5. 生成随机布尔值 ( RandomUtil.randomBoolean)
  6. 生成随机字符串 ( RandomUtil.randomString)
  7. 生成指定长度的随机字符串 ( RandomUtil.randomString(intlength))
  8. 生成随机UUID ( RandomUtil.randomUUID)
  9. 从数组中随机选取元素 ( RandomUtil.randomEle)
  10. 从集合中随机选取元素 ( RandomUtil.randomEle(Collection<?>collection))
import cn.hutool.core.util.RandomUtil;

import java.util.ArrayList;
import java.util.List;

public class LotterySystem {

    /**
     * 生成随机验证码
     * 
     * @param length 验证码长度
     * @return 随机验证码
     */
    public String generateVerificationCode(int length) {
        // 使用 RandomUtil.randomString 生成随机字符串作为验证码
        return RandomUtil.randomString(length);
    }

    /**
     * 从参与者列表中随机选择中奖者
     * 
     * @param participants 参与者名单
     * @return 中奖者
     */
    public String pickWinner(List<String> participants) {
        // 使用 RandomUtil.randomEle 从列表中随机选择一个元素
        return RandomUtil.randomEle(participants);
    }

    /**
     * 生成随机整数用于抽奖活动
     * 
     * @param min 最小值
     * @param max 最大值
     * @return 随机整数
     */
    public int generateLotteryNumber(int min, int max) {
        // 使用 RandomUtil.randomInt 生成指定范围内的随机整数
        return RandomUtil.randomInt(min, max);
    }

    /**
     * 生成随机UUID用于标识唯一参与者
     * 
     * @return 随机UUID
     */
    public String generateParticipantId() {
        // 使用 RandomUtil.randomUUID 生成随机UUID
        return RandomUtil.randomUUID();
    }

    public static void main(String[] args) {
        LotterySystem lottery = new LotterySystem();

        // 生成验证码
        String code = lottery.generateVerificationCode(6);
        System.out.println("Verification Code: " + code);

        // 参与者列表
        List<String> participants = new ArrayList<>();
        participants.add("Alice");
        participants.add("Bob");
        participants.add("Charlie");

        // 随机选择中奖者
        String winner = lottery.pickWinner(participants);
        System.out.println("Lottery Winner: " + winner);

        // 生成抽奖号码
        int lotteryNumber = lottery.generateLotteryNumber(1, 100);
        System.out.println("Lottery Number: " + lotteryNumber);

        // 生成参与者ID
        String participantId = lottery.generateParticipantId();
        System.out.println("Participant ID: " + participantId);
    }
}

5. DesUtil - DES 加密解密工具类

常用方法

  1. 加密 ( DES.encrypt)
  2. 解密 ( DES.decrypt)
  3. 加密为Hex字符串 ( DES.encryptHex)
  4. 从Hex字符串解密 ( DES.decryptHex)
  5. 加密为Base64字符串 ( DES.encryptBase64)
  6. 从Base64字符串解密 ( DES.decryptBase64)
import cn.hutool.crypto.symmetric.DES;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;

public class UserInfoManagementSystem {

    /**
     * 加密用户密码
     * 
     * @param password 明文密码
     * @return 加密后的密码
     */
    public String encryptPassword(String password) {
        // 使用 DesUtil.encryptHex 加密为Hex字符串
        return DES.encryptHex(password, "123456");
    }

    /**
     * 解密用户密码
     * 
     * @param encryptedPassword 加密后的密码
     * @return 明文密码
     */
    public String decryptPassword(String encryptedPassword) {
        // 使用 DesUtil.decryptStr 从Hex字符串解密
        return DES.decryptStr(encryptedPassword, "123456");
    }

    /**
     * 验证用户登录
     * 
     * @param username 用户名
     * @param password 明文密码
     * @return 登录成功返回 true,否则返回 false
     */
    public boolean verifyLogin(String username, String password) {
        String storedPassword = getStoredPassword(username);
        if (storedPassword == null) {
            return false;
        }
        return DES.decryptHex(storedPassword, "123456").equals(password);
    }

    /**
     * 获取存储的加密密码
     * 
     * @param username 用户名
     * @return 加密密码
     */
    private String getStoredPassword(String username) {
        // 模拟从数据库获取加密密码
        return "加密密码示例"; // 假设这是数据库中存储的加密密码
    }

    public static void main(String[] args) {
        UserInfoManagementSystem system = new UserInfoManagementSystem();

        // 加密密码
        String encryptedPassword = system.encryptPassword("userPassword123");
        System.out.println("Encrypted Password: " + encryptedPassword);

        // 解密密码
        String decryptedPassword = system.decryptPassword(encryptedPassword);
        System.out.println("Decrypted Password: " + decryptedPassword);

        // 验证登录
        boolean loginSuccess = system.verifyLogin("username", "userPassword123");
        System.out.println("Login Success: " + loginSuccess);
    }
}

6. RsaUtil - RSA 加密解密工具类

常用方法

  1. 生成密钥对 ( RSA.generateKeyPair)
  2. 加密 ( RSA.encrypt)
  3. 解密 ( RSA.decrypt)
  4. 加密为Hex字符串 ( RSA.encryptHex)
  5. 从Hex字符串解密 ( RSA.decryptHex)
  6. 加密为Base64字符串 ( RSA.encryptBase64)
  7. 从Base64字符串解密 ( RSA.decryptBase64)
import cn.hutool.crypto.asymmetric.RSA;
import cn.hutool.crypto.asymmetric.EncryptedData;

public class SecureCommunicationSystem {

    /**
     * 生成 RSA 密钥对
     * 
     * @return 密钥对
     */
    public RSA generateKeyPair() {
        // 使用 RsaUtil.generateKeyPair 生成密钥对
        return RSA.generateKeyPair(2048);
    }

    /**
     * 加密数据
     * 
     * @param data 待加密的数据
     * @param publicKey 公钥
     * @return 加密后的数据
     */
    public EncryptedData encryptData(String data, RSA.PublicKey publicKey) {
        // 使用 RsaUtil.encrypt 加密数据
        return RSA.encrypt(data.getBytes(), publicKey);
    }

    /**
     * 解密数据
     * 
     * @param encryptedData 加密后的数据
     * @param privateKey 私钥
     * @return 解密后的原始数据
     */
    public String decryptData(EncryptedData encryptedData, RSA.PrivateKey privateKey) {
        // 使用 RsaUtil.decrypt 解密数据
        byte[] decryptBytes = RSA.decrypt(encryptedData.getData(), privateKey);
        return new String(decryptBytes);
    }

    /**
     * 加密数据为Hex字符串
     * 
     * @param data 待加密的数据
     * @param publicKey 公钥
     * @return 加密后的Hex字符串
     */
    public String encryptDataToHex(String data, RSA.PublicKey publicKey) {
        // 使用 RsaUtil.encryptHex 加密为Hex字符串
        return RSA.encryptHex(data, publicKey);
    }

    /**
     * 从Hex字符串解密数据
     * 
     * @param hexEncryptedData 待解密的Hex字符串
     * @param privateKey 私钥
     * @return 解密后的原始数据
     */
    public String decryptHexData(String hexEncryptedData, RSA.PrivateKey privateKey) {
        // 使用 RsaUtil.decryptHex 从Hex字符串解密
        return RSA.decryptStr(hexEncryptedData, privateKey);
    }

    public static void main(String[] args) {
        SecureCommunicationSystem system = new SecureCommunicationSystem();

        // 生成密钥对
        RSA keyPair = system.generateKeyPair();

        // 加密数据
        String originalData = "Sensitive Data";
        EncryptedData encryptedData = system.encryptData(originalData, keyPair.getPublicKey());
        System.out.println("Encrypted Data: " + encryptedData);

        // 解密数据
        String decryptedData = system.decryptData(encryptedData, keyPair.getPrivateKey());
        System.out.println("Decrypted Data: " + decryptedData);

        // 加密为Hex字符串
        String hexEncryptedData = system.encryptDataToHex(originalData, keyPair.getPublicKey());
        System.out.println("Hex Encrypted Data: " + hexEncryptedData);

        // 从Hex字符串解密
        String hexDecryptedData = system.decryptHexData(hexEncryptedData, keyPair.getPrivateKey());
        System.out.println("Hex Decrypted Data: " + hexDecryptedData);
    }
}

7. HttpRequest - HTTP 请求工具类

常用方法

  1. 发送 GET 请求 ( HttpRequest.get)
  2. 发送 POST 请求 ( HttpRequest.post)
  3. 发送请求并获取响应体 ( body)
  4. 发送请求并获取响应状态码 ( statusCode)
  5. 设置请求参数 ( form)
  6. 设置请求头 ( header)
  7. 设置超时时间 ( timeout)
  8. 上传文件 ( upload)
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;

public class DataSyncSystem {

    /**
     * 从外部 API 获取数据
     * 
     * @param url 请求 URL
     * @return 响应体内容
     */
    public String fetchDataFromApi(String url) {
        // 使用 HttpRequest.get 发送 GET 请求
        HttpResponse response = HttpRequest.get(url);
        return response.body();
    }

    /**
     * 向外部 API 提交数据
     * 
     * @param url 请求 URL
     * @param data 提交的数据
     * @return 响应体内容
     */
    public String submitDataToApi(String url, String data) {
        // 使用 HttpRequest.post 发送 POST 请求
        HttpResponse response = HttpRequest.post(url)
            .body(data)
            .contentType("application/json");
        return response.body();
    }

    /**
     * 上传文件到服务器
     * 
     * @param url 请求 URL
     * @param filePath 文件路径
     * @return 响应体内容
     */
    public String uploadFile(String url, String filePath) {
        // 使用 HttpRequest.upload 上传文件
        HttpResponse response = HttpRequest.upload(url, filePath);
        return response.body();
    }

    /**
     * 设置请求头并发送请求
     * 
     * @param url 请求 URL
     * @param headerName 头名称
     * @param headerValue 头值
     * @return 响应体内容
     */
    public String sendRequestWithHeader(String url, String headerName, String headerValue) {
        // 设置请求头并发送 GET 请求
        HttpResponse response = HttpRequest.get(url)
            .header(headerName, headerValue);
        return response.body();
    }

    public static void main(String[] args) {
        DataSyncSystem syncSystem = new DataSyncSystem();

        // 从 API 获取数据
        String fetchData = syncSystem.fetchDataFromApi("http://api.example.com/data");
        System.out.println("Fetched Data: " + fetchData);

        // 提交数据到 API
        String submitData = syncSystem.submitDataToApi("http://api.example.com/submit", "{"key":"value"}");
        System.out.println("Submitted Data Response: " + submitData);

        // 上传文件
        String fileUploadResponse = syncSystem.uploadFile("http://api.example.com/upload", "/path/to/file.txt");
        System.out.println("File Upload Response: " + fileUploadResponse);

        // 发送带有自定义头的请求
        String customHeaderResponse = syncSystem.sendRequestWithHeader("http://api.example.com/header", "Authorization", "Bearer token");
        System.out.println("Custom Header Response: " + customHeaderResponse);
    }
}

8. CacheUtil - 缓存工具类

常用方法

  1. 创建缓存 ( CacheUtil.newCache)
  2. 创建带过期时间的缓存 ( CacheUtil.newTimedCache)
  3. 获取缓存值 ( CacheUtil.get)
  4. 写入缓存值 ( CacheUtil.put)
  5. 删除缓存 ( CacheUtil.remove)
  6. 清空缓存 ( CacheUtil.clear)
  7. 检查缓存是否包含键 ( CacheUtil.containsKey)
  8. 获取缓存大小 ( CacheUtil.size)
import cn.hutool.cache.Cache;
import cn.hutool.cache.CacheUtil;
import java.util.concurrent.TimeUnit;

public class ProductInfoCacheSystem {

    /**
     * 创建商品信息缓存
     * 
     * @param <K> 键类型
     * @param <V> 值类型
     * @return 商品信息缓存
     */
    public <K, V> Cache<K, V> createProductInfoCache() {
        // 使用 CacheUtil.newCache 创建一个简单的缓存
        return CacheUtil.newCache();
    }

    /**
     * 创建带过期时间的商品信息缓存
     * 
     * @param <K> 键类型
     * @param <V> 值类型
     * @return 带过期时间的商品信息缓存
     */
    public <K, V> Cache<K, V> createTimedProductInfoCache() {
        // 使用 CacheUtil.newTimedCache 创建一个带过期时间的缓存
        return CacheUtil.newTimedCache(1000 * 60 * 60, 1000 * 60 * 60); // 1小时存活期
    }

    /**
     * 获取商品信息
     * 
     * @param cache 缓存
     * @param productId 商品ID
     * @return 商品信息
     */
    public String getProductInfo(Cache<String, String> cache, String productId) {
        // 使用 CacheUtil.get 从缓存中获取商品信息
        return cache.get(productId, key -> "Product Info for " + key);
    }

    /**
     * 更新商品信息缓存
     * 
     * @param cache 缓存
     * @param productId 商品ID
     * @param productInfo 商品信息
     */
    public void updateProductInfo(Cache<String, String> cache, String productId, String productInfo) {
        // 使用 CacheUtil.put 更新缓存中的商品信息
        cache.put(productId, productInfo);
    }

    /**
     * 清除过时的商品信息缓存
     * 
     * @param cache 缓存
     * @param productId 商品ID
     */
    public void clearProductInfo(Cache<String, String> cache, String productId) {
        // 使用 CacheUtil.remove 从缓存中删除过时的商品信息
        cache.remove(productId);
    }

    public static void main(String[] args) {
        ProductInfoCacheSystem system = new ProductInfoCacheSystem();

        // 创建带过期时间的商品信息缓存
        Cache<String, String> productCache = system.createTimedProductInfoCache();

        // 获取商品信息
        String productInfo = system.getProductInfo(productCache, "123");
        System.out.println("Product Info: " + productInfo);

        // 更新商品信息
        system.updateProductInfo(productCache, "123", "Updated Product Info for 123");

        // 再次获取商品信息
        productInfo = system.getProductInfo(productCache, "123");
        System.out.println("Updated Product Info: " + productInfo);

        // 清除过时的商品信息
        system.clearProductInfo(productCache, "123");
    }
}

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表