当前位置:首页 > 技术 > 正文内容

Java 后端常用核心辅助组件

访客 技术 2026年10月19日 1

一、随机数值与集合抽样处理器

该组件封装了固定位数验证码的生成逻辑,并提供从数据源中无重复抽取指定样本的高效算法。底层采用洗牌算法替代原有的低效哈希映射方案,显著提升随机采样的准确性与执行效率。

import java.text.DecimalFormat;
import java.util.*;

public class RandomHelper {
    private static final Random GENERATOR = new Random();
    private static final DecimalFormat FMT_4 = new DecimalFormat("0000");
    private static final DecimalFormat FMT_6 = new DecimalFormat("000000");

    public static String createFourDigits() {
        return FMT_4.format(GENERATOR.nextInt(10000));
    }

    public static String createSixDigits() {
        return FMT_6.format(GENERATOR.nextInt(1000000));
    }

    public static <T> List<T> sampleElements(List<T> source, int count) {
        if (source == null || source.isEmpty()) {
            return Collections.emptyList();
        }
        List<T> copy = new ArrayList<>(source);
        Collections.shuffle(copy, GENERATOR);
        int limit = Math.min(count, copy.size());
        return new ArrayList<>(copy.subList(0, limit));
    }
}

二、统一网络请求执行客户端

基于 Apache HttpClient 构建的轻量级通信类,整合了 GET/POST 请求构造、表单数据提交、原始报文发送、连接超时控制以及 HTTPS 证书信任绕过功能。采用资源自动释放机制,避免连接泄漏,适用于常规 API 调用与第三方服务对接。

import org.apache.http.*;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.conn.ssl.*;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import javax.net.ssl.SSLContext;
import java.nio.charset.StandardCharsets;
import java.util.*;

public class NetworkCaller {
    private final RequestConfig requestConf;

    public NetworkCaller(int connectMs, int readMs) {
        this.requestConf = RequestConfig.custom()
                .setConnectTimeout(connectMs)
                .setSocketTimeout(readMs)
                .build();
    }

    public String fetchGet(String endpoint) throws Exception {
        HttpGet req = new HttpGet(endpoint);
        req.setConfig(requestConf);
        try (CloseableHttpClient client = buildClient(endpoint.startsWith("https"))) {
            HttpResponse res = client.execute(req);
            return EntityUtils.toString(res.getEntity(), StandardCharsets.UTF_8);
        }
    }

    public String submitForm(String endpoint, Map<String, String> params) throws Exception {
        HttpPost req = new HttpPost(endpoint);
        req.setConfig(requestConf);
        List<NameValuePair> pairList = new ArrayList<>();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            pairList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        req.setEntity(new UrlEncodedFormEntity(pairList, StandardCharsets.UTF_8));
        try (CloseableHttpClient client = buildClient(endpoint.startsWith("https"))) {
            HttpResponse res = client.execute(req);
            return EntityUtils.toString(res.getEntity(), StandardCharsets.UTF_8);
        }
    }

    public String sendRawPost(String endpoint, String payload, String mime) throws Exception {
        HttpPost req = new HttpPost(endpoint);
        req.setConfig(requestConf);
        if (payload != null && !payload.trim().isEmpty()) {
            ContentType ct = mime != null ? ContentType.create(mime, StandardCharsets.UTF_8) : ContentType.APPLICATION_JSON;
            req.setEntity(new StringEntity(payload, ct));
        }
        try (CloseableHttpClient client = buildClient(endpoint.startsWith("https"))) {
            HttpResponse res = client.execute(req);
            return EntityUtils.toString(res.getEntity(), StandardCharsets.UTF_8);
        }
    }

    private CloseableHttpClient buildClient(boolean bypassCert) throws Exception {
        if (bypassCert) {
            SSLContext ctx = new org.apache.http.ssl.SSLContextBuilder()
                    .loadTrustMaterial(null, (chain, authType) -> true).build();
            SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(ctx, NoopHostnameVerifier.INSTANCE);
            return HttpClients.custom().setSSLSocketFactory(factory).build();
        }
        return HttpClients.custom().setDefaultRequestConfig(requestConf).build();
    }
}

三、分布式交易流水号生成器

针对订单或交易场景设计的唯一标识构造方法。通过线程安全的日期格式化与伪随机数结合,输出"年月日时分秒+三位随机数"格式的业务主键,有效降低多线程并发下的碰撞概率。

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ThreadLocalRandom;

public class TradeSequenceUtils {
    private static final ThreadLocal<SimpleDateFormat> FMT =
            ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyyMMddHHmmss"));

    public static String generateOrderSn() {
        String timeStr = FMT.get().format(new Date());
        int randomTail = ThreadLocalRandom.current().nextInt(1000);
        return String.format("%s%03d", timeStr, randomTail);
    }
}

四、日历计算与日期渲染组件

提供标准的日期转字符串功能,支持按天维度的前后推算。内部采用实例化隔离策略,确保在多线程环境下的格式化安全,适用于日志记录、数据过滤与时效性校验。

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class TimeProcessor {
    private static final String PATTERN = "yyyy-MM-dd";

    public static String renderDate(Date input) {
        return new SimpleDateFormat(PATTERN).format(input);
    }

    public static Date adjustDays(Date origin, int offset) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(origin);
        cal.add(Calendar.DATE, offset);
        return cal.getTime();
    }
}
返回列表

上一篇:选择性子数组求和问题

没有最新的文章了...

相关文章

Linux crontab 详解

1) crontab 是什么cron 是 Linux 的定时任务守护进程;crontab 是用来编辑/查看“按时间周期执行命令”的表(cron table)。常见两类:用户 crontab:每个用户一份(crontab -e 编辑)系统级 crontab / cron.d:可指定执行用户(/etc/crontab、/etc/cron.d/*)2) crontab 时间...

富文本里可以允许的 HTML 属性

一、所有标签默认允许的安全属性(极少)class        (可选)id           (通常建议禁用)title️ 注意:id 容易被滥用做锚点注入,很多系统直接禁用class 允许的话最好只允许固定前缀(如 editor-*)二、a 标签允许属性<a href="" t...

Mac 安装 Node.js 指南

方法一:通过官网安装包(最简单,适合初学者)如果你只是想快速安装并开始使用,这是最直接的方法。访问 Node.js 官网。页面会显示两个版本:LTS (Recommended For Most Users):长期支持版,最稳定。建议选这个。Current:最新特性版,包含最新功能但可能不够稳定。下载 .pkg 安装包并运行。按照安装向导点击“下一步”即可完成。方法二:使用 Homebrew 安装(...

Dom\HTML_NO_DEFAULT_NS 的副作用:自动加闭合标签

在使用Dom\HTMLDocument时,Dom\HTML_NO_DEFAULT_NS 将禁止在解析过程中设置元素的命名空间, 此设置是为了与DOMDocument向后兼容而存在的。当使用它时,已知的一个副作用就是:自动加闭合标签例如 </img> 为什么会这样?当你使用:Dom\HTML_NO_DEFAULT_NS文档会变成 无命名空间模式,此时内部更接近 XML...

Laravel 事件和监听器创建

在 Laravel 中,使用 Artisan 命令创建 Events(事件) 和 Listeners(监听器) 是非常高效的。你可以通过以下几种方式来实现:1. 手动创建单个 Event如果你只想创建一个事件类,可以使用 make:event 命令:Bashphp artisan make:event UserRegistered执行后,文件将生成在 app/Even...

自定义域名解析神器 dnsmasq

什么是 dnsmasq?dnsmasq 是一个轻量级、功能强大的网络服务工具,专为小型和中等规模网络设计。它是一个综合的网络基础设施解决方案[1]。dnsmasq 能做什么?功能说明应用场景DNS 转发与缓存将 DNS 查询转发到上游服务器(ISP、Google DNS 等),并在本地缓存结果加快 DNS 查询速度,减少外部 DNS 流量本地 DNS解析本地网络设备的主机名,无需编辑&n...

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。