You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

字符串转整数的Java NumberFormatException及Joda Time唯一密钥生成问题

2. 基于Joda Time生成唯一密钥的程序优化(含邮箱Base64编解码)

我先把你没写完的解码方法补全,再加上用Joda Time生成唯一密钥的逻辑,同时做了一些实用优化:

import org.apache.commons.codec.binary.Base64;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import java.nio.charset.StandardCharsets;
import java.util.Random;

public class EnDecoding {

    // 邮箱Base64编码,指定UTF-8字符集避免乱码
    public String encodeRecieverAddress(String emailaddress) {
        if (emailaddress == null || emailaddress.trim().isEmpty()) {
            throw new IllegalArgumentException("邮箱地址不能为空");
        }
        byte[] encodedBytes = Base64.encodeBase64(emailaddress.trim().getBytes(StandardCharsets.UTF_8));
        return new String(encodedBytes, StandardCharsets.UTF_8);
    }

    // 补全你未完成的邮箱Base64解码方法
    public String decodeRecieverAddress(String encodedemail) {
        if (encodedemail == null || encodedemail.trim().isEmpty()) {
            throw new IllegalArgumentException("编码后的邮箱不能为空");
        }
        byte[] decodedBytes = Base64.decodeBase64(encodedemail.trim().getBytes(StandardCharsets.UTF_8));
        return new String(decodedBytes, StandardCharsets.UTF_8);
    }

    // 结合Joda Time生成唯一密钥:编码邮箱+毫秒级时间戳
    public String generateUniqueKey(String email) {
        String encodedEmail = encodeRecieverAddress(email);
        // 获取当前时间的毫秒级时间戳,保证同一毫秒内不同邮箱的密钥不同
        long currentTimestamp = DateTime.now().getMillis();
        return encodedEmail + "_" + currentTimestamp;
    }

    // 进阶版:加随机数,进一步避免极端情况下的重复(比如同一毫秒同一邮箱多次生成)
    public String generateUniqueKeyWithRandom(String email) {
        String encodedEmail = encodeRecieverAddress(email);
        DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyyMMddHHmmssSSS");
        String formattedTime = DateTime.now().toString(formatter);
        // 生成0-999的随机数
        int randomNum = new Random().nextInt(1000);
        return encodedEmail + "_" + formattedTime + "_" + randomNum;
    }
}

几个关键点要注意:

  • 指定字符集:原代码里getBytes()没指定字符集,不同系统可能用不同的默认编码,容易导致乱码,加上StandardCharsets.UTF_8更稳妥。
  • 空值校验:增加了参数的非空判断,避免空指针异常,同时抛出明确的非法参数异常,方便排查问题。
  • 唯一性保障:Joda Time的DateTime.now().getMillis()能拿到精确到毫秒的时间戳,结合编码后的邮箱,基本能保证密钥唯一;如果业务要求极高的唯一性,加上随机数就能进一步降低重复概率。
  • 代码规范:方法名改成了小驼峰格式,符合Java编码规范,可读性更好。

内容的提问来源于stack exchange,提问作者burhanuddin abbas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:15:35