Java 后端常用核心辅助组件
一、随机数值与集合抽样处理器
该组件封装了固定位数验证码的生成逻辑,并提供从数据源中无重复抽取指定样本的高效算法。底层采用洗牌算法替代原有的低效哈希映射方案,显著提升随机采样的准确性与执行效率。
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();
}
}