栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

高质量java常用util类

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

高质量java常用util类

自定义断言工具类
package com.wlc.doc.util;

import com.wlc.doc.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import java.util.Collection;
import java.util.Map;


@Slf4j
public class AssertUtil extends Assert {

    
    public static void isEquals(Object o1, Object o2 ,String message) {
        if (!o1.toString().equals(o2.toString())) {
            throw new BusinessException(message);
        }
    }

    
    public static void isNotEquals(Object o1, Object o2 ,String message) {
        if (o1.toString().equals(o2.toString())) {
            throw new BusinessException(message);
        }
    }
    
    public static void isTrue(boolean expression, String message, Object logInfo) {
        if (!expression) {
            if (!ObjectUtils.isEmpty(logInfo)){
                log.error(logInfo.toString());
            }
            throw new BusinessException(message);
        }
    }

    
    public static void isTrue(boolean expression, String message) {
        if (!expression) {
            throw new BusinessException(message);
        }
    }
    
    public static void isNotTrue(boolean expression, String message) {
        if (expression) {
            throw new BusinessException(message);
        }
    }
    
    public static void isNotTrue(boolean expression, String message, Object logInfo) {
        if (expression) {
            if (!ObjectUtils.isEmpty(logInfo)){
                log.error(logInfo.toString());
            }
            throw new BusinessException(message);
        }
    }
    
    public static void isNull(@Nullable Object object, String message, Object logInfo) {
        if (object != null) {
            if (!ObjectUtils.isEmpty(logInfo)){
                log.error(logInfo.toString());
            }
            throw new BusinessException(message);
        }
    }

    
    public static void isNull(@Nullable Object object, String message) {
        if (object != null) {
            throw new BusinessException(message);
        }
    }

    
    public static void notNull(@Nullable Object object, String message, Object logInfo) {
        if (object == null) {
            if (!ObjectUtils.isEmpty(logInfo)){
                log.error(logInfo.toString());
            }
            throw new BusinessException(message);
        }
    }

    
    public static void notNull(@Nullable Object object, String message) {
        if (ObjectUtils.isEmpty(object)) {
            throw new BusinessException(message);
        }
    }

    
    public static void doesNotContain(@Nullable String textToSearch, String substring, String message, Object logInfo) {
        if (StringUtils.hasLength(textToSearch) && StringUtils.hasLength(substring) && textToSearch.contains(substring)) {
            if (!ObjectUtils.isEmpty(logInfo)){
                log.error(logInfo.toString());
            }
            throw new BusinessException(message);
        }
    }
    
    public static void doesNotContain(@Nullable String textToSearch, String substring, String message) {
        if (StringUtils.hasLength(textToSearch) && StringUtils.hasLength(substring) && textToSearch.contains(substring)) {
            throw new BusinessException(message);
        }
    }

    
    public static void notEmpty(@Nullable Object[] array, String message) {
        if (ObjectUtils.isEmpty(array)) {
            throw new BusinessException(message);
        }
    }

    
    public static void notEmpty(@Nullable Object[] array, String message, Object logInfo) {
        if (ObjectUtils.isEmpty(array)) {
            if (!ObjectUtils.isEmpty(logInfo)){
                log.error(logInfo.toString());
            }
            throw new BusinessException(message);
        }
    }

    
    public static void notEmpty(@Nullable Collection collection, String message, Object logInfo) {
        if (CollectionUtils.isEmpty(collection)) {
            if (!ObjectUtils.isEmpty(logInfo)){
                log.error(logInfo.toString());
            }
            throw new BusinessException(message);
        }
    }

    
    public static void notEmpty(@Nullable Collection collection, String message) {
        if (CollectionUtils.isEmpty(collection)) {
            throw new BusinessException(message);
        }
    }

    
    public static void notEmpty(@Nullable Map map, String message, Object logInfo) {
        if (CollectionUtils.isEmpty(map)) {
            if (!ObjectUtils.isEmpty(logInfo)){
                log.error(logInfo.toString());
            }
            throw new BusinessException(message);
        }
    }

    
    public static void notEmpty(@Nullable Map map, String message) {
        if (CollectionUtils.isEmpty(map)) {
            throw new BusinessException(message);
        }
    }

}
bean 拷贝工具类
package com.wlc.doc.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class BeanCopierUtil {
    private static final Logger log = LoggerFactory.getLogger(BeanCopierUtil.class);

    
    private static Map beanCopierCacheMap = new HashMap<>();

    
    public static void copyProperties(Object source, Object target) {
        String cacheKey = source.getClass().toString() + target.getClass().toString();
        if (!beanCopierCacheMap.containsKey(cacheKey)) {
            synchronized (BeanCopierUtil.class) {
                if (!beanCopierCacheMap.containsKey(cacheKey)) {
                    BeanCopier beanCopier = BeanCopier.create(source.getClass(), target.getClass(), false);
                    beanCopierCacheMap.put(cacheKey, beanCopier);
                }
            }
        }
        beanCopierCacheMap.get(cacheKey).copy(source, target, null);
    }

    
    public static  T copyProperties(Object source, Class clazz) {
        T target = null;
        try {
            target = clazz.newInstance();
            BeanCopierUtil.copyProperties(source, target);
        } catch (Exception e) {
            log.error("error", e);
        }
        return target;
    }

    
    public static  List copyList(List source, Class clazz) {
        List target = new ArrayList<>();
        if (!CollectionUtils.isEmpty(source)) {
            for (Object c : source) {
                T obj = copyProperties(c, clazz);
                target.add(obj);
            }
        }
        return target;
    }
}
基于jackson的JsonUtil
package com.utils;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import java.io.IOException;
import java.io.StringWriter;
import java.util.List;
import java.util.Map;

public class JsonUtil {

    public static final ObjectMapper OBJECT_MAPPER = createObjectMapper();
    
    private static ObjectMapper createObjectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
        objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.configure(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS, true);
        // 允许序列化空的POJO类(否则会抛出异常)
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        // 对象的所有字段全部列入。NON_NULL:不返回 null 值字段
        objectMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
        // 取消java.util.Date, Calendar默认转换timestamps形式
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS , false);
        objectMapper.registerModule(new JavaTimeModule());
        // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
        objectMapper.setVisibility(PropertyAccessor.ALL,JsonAutoDetect.Visibility.ANY);
        return objectMapper;
    }

    public static String object2Json(Object o) {
        StringWriter sw = new StringWriter();
        JsonGenerator gen = null;
        try {
            gen = new JsonFactory().createGenerator(sw);
            OBJECT_MAPPER.writeValue(gen, o);
        } catch (IOException e) {
            throw new RuntimeException("不能序列化对象为Json", e);
        } finally {
            if (null != gen) {
                try {
                    gen.close();
                } catch (IOException e) {
                    throw new RuntimeException("不能序列化对象为Json", e);
                }
            }
        }
        return sw.toString();
    }

    
    public static Map object2Map(Object o) {
        return OBJECT_MAPPER.convertValue(o,Map.class);
    }

    
    public static  T map2Object(Map map, Class clazz) {
        return OBJECT_MAPPER.convertValue(map,clazz);
    }


    
    public static  T json2Object(String json, Class clazz) {
        try {
            return OBJECT_MAPPER.readValue(json, clazz);
        } catch (IOException e) {
            throw new RuntimeException("将 Json 转换为对象时异常,数据是:" + json, e);
        }
    }

    
    public static  List json2List(String json,Class clazz) throws IOException {
        JavaType type = OBJECT_MAPPER.getTypeFactory().constructCollectionType(List.class, clazz);
        return OBJECT_MAPPER.readValue(json, type);
    }


    
    public static   T[] json2Array(String json,Class clazz) throws IOException {
        return OBJECT_MAPPER.readValue(json, clazz);

    }

    public static  T node2Object(JsonNode jsonNode, Class clazz) {
        try {
            T t = OBJECT_MAPPER.treeToValue(jsonNode, clazz);
            return t;
        } catch (JsonProcessingException e) {
            throw new RuntimeException("将 Json 转换为对象时异常,数据是:" + jsonNode.toString(), e);
        }
    }

    public static JsonNode object2Node(Object o) {
        try {
            if(o == null) {
                return OBJECT_MAPPER.createObjectNode();
            } else {
                return OBJECT_MAPPER.convertValue(o, JsonNode.class);
            }
        } catch (Exception e) {
            throw new RuntimeException("不能序列化对象为Json", e);
        }
    }

    
    public static  T json2GenericObject(String json, TypeReference tr) {
        if (json == null || "".equals(json)) {
            throw new RuntimeException("将 Json 转换为对象时异常,数据是:" + json);
        } else {
            try {
                return (T) OBJECT_MAPPER.readValue(json, tr);
            } catch (Exception e) {
                throw new RuntimeException("将 Json 转换为对象时异常,数据是:" + json, e);
            }
        }
    }

}
request请求util
package com.wlc.doc.util;

import cn.hutool.core.util.StrUtil;
import com.google.common.base.Joiner;
import com.sun.istack.internal.NotNull;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;
import java.util.Arrays;
import java.util.List;
import java.util.Map;


public class RequestUtil {
    
    public static String getServletPath(HttpServletRequest request, HttpServletResponse response){
        return request.getServletPath();
    }

    
    public static String getRealUrl(Object handler, String url){
        Annotation[][] parameterAnnotations = ((HandlerMethod) handler).getMethod().getParameterAnnotations();
        int i = 0;
        for (Annotation[] annotations : parameterAnnotations) {
            for (Annotation annotation : annotations) {
                if(annotation instanceof PathVariable){
                    i++;
                    break;
                }
            }
        }
        if (i == 0){
            return url;
        }
        List split = Arrays.asList(url.split("\/"));
        List subList = split.subList(0, split.size() - i);
        String join = Joiner.on("/").join(subList);
        return join;
    }

    
    public static String getServletRequestMapping(HttpServletRequest request, HttpServletResponse response){
        String servletPath = getServletPath(request, response);
        //Map parameterMap = getParameterMap(request, response);
        Map parameterMap = (Map) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
        if (CollectionUtils.isEmpty(parameterMap)){
            return servletPath;
        }
        Integer paramSize = parameterMap.size();
        int count = StrUtil.count(servletPath, "/");
        int subIndex = StrUtil.ordinalIndexOf(servletPath,"/", count - paramSize + 1);
        String result = servletPath.substring(0, subIndex);
        return result;
    }

    
    public static Map getParameterMap(HttpServletRequest request, HttpServletResponse response){
        return request.getParameterMap();
    }

    
    public static String[] getParameterArrayByParamKey(@NotNull String paramKey, HttpServletRequest request, HttpServletResponse response){
        Map parameterMap = getParameterMap(request, response);
        for (String key : parameterMap.keySet()) {
            if (key.equals(paramKey)){
               return parameterMap.get(key);
            }
        }
        return null;
    }
    
    public static String getIndexParameterByParamKey(@NotNull String paramKey, int index, HttpServletRequest request, HttpServletResponse response){
        String[] parameterArray = getParameterArrayByParamKey(paramKey, request, response);
        for (int i = 0, length = parameterArray.length; i < length; i++ ){
            if (i == index){
                return parameterArray[i];
            }
        }
        return null;
    }

    
    public static String getFirstParameterByParamKey(@NotNull String paramKey, HttpServletRequest request, HttpServletResponse response){
        return getIndexParameterByParamKey(paramKey, 0, request, response);
    }



}
随机编码util,适合唯一兑换码场景
package com.wlc.doc.util;

import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;


public class RnUtil {


    
    public static final long MAX = 1220096908800L; // 36*35*34*33*32*31*30*29


    
    public static final long P = 982451653L;

    
    public static final long Q = 9007;

    
    public static final int LEN = 8;

    
    public static final int RADIX = 33;

    public static List originalCharList = new LinkedList();

    private static char[] cb = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y'};

    static {
        if (CollectionUtils.isEmpty(originalCharList)) {
            for (char c : cb) {
                originalCharList.add(c);
            }
        }
    }

    
    public static String encode(long number) {
        if (number <= 0 || number > MAX) {
            throw new IllegalArgumentException();
        }
        long x = (number * P + Q) % MAX;

        return encode0(x, LEN);
    }

    private static String encode0(long x, int length) {
        List list = new LinkedList();
//        for (int i = 0; i < RADIX; i++) {
//            list.add(Character.toUpperCase(Character.forDigit(i, RADIX)));
//        }
        list.addAll(originalCharList);
        char[] codes = new char[length];
        int radix = RADIX;
        for (int i = length; i-- > 0; ) {
            int n = (int) (x % radix);
            codes[i] = list.remove(n);
            x /= radix;
            radix--;
        }

        return new String(codes);
    }


    
    public static HashSet getUkNumByLength(Long startNum, Integer length) {
        AssertUtil.isTrue(!ObjectUtils.isEmpty(startNum), "startNum不能为空");
        AssertUtil.isTrue((!ObjectUtils.isEmpty(length) || length != 0), "length不能为空或者length=0");
        HashSet hashSet = new HashSet<>(length);
        long startIndex = startNum + 1;
        long endIndex = startIndex + length;
        for (long i = startIndex; i < endIndex; i++) {
            hashSet.add(encode(i));
        }
        return hashSet;
    }

    
    public static String encode(long number, int length) {
        if (number <= 0 || number > MAX) {
            throw new IllegalArgumentException();
        }
        long x = (number * P + Q) % MAX;

        return encode0(x, length);
    }

}
分布式自增ID雪花算法
package com.wlc.doc.util;

import org.springframework.stereotype.Component;

import java.text.ParseException;


@Component
public class SnowFlake {

    
    private final static long START_STMP = 1609459200000L; // 2021-01-01 00:00:00

    
    private final static long SEQUENCE_BIT = 12; //序列号占用的位数
    private final static long MACHINE_BIT = 5;   //机器标识占用的位数
    private final static long DATACENTER_BIT = 5;//数据中心占用的位数

    
    private final static long MAX_DATACENTER_NUM = -1L ^ (-1L << DATACENTER_BIT);
    private final static long MAX_MACHINE_NUM = -1L ^ (-1L << MACHINE_BIT);
    private final static long MAX_SEQUENCE = -1L ^ (-1L << SEQUENCE_BIT);

    
    private final static long MACHINE_LEFT = SEQUENCE_BIT;
    private final static long DATACENTER_LEFT = SEQUENCE_BIT + MACHINE_BIT;
    private final static long TIMESTMP_LEFT = DATACENTER_LEFT + DATACENTER_BIT;

    private long datacenterId = 1;  //数据中心
    private long machineId = 1;     //机器标识
    private long sequence = 0L; //序列号
    private long lastStmp = -1L;//上一次时间戳

    public SnowFlake() {
    }

    public SnowFlake(long datacenterId, long machineId) {
        if (datacenterId > MAX_DATACENTER_NUM || datacenterId < 0) {
            throw new IllegalArgumentException("datacenterId can't be greater than MAX_DATACENTER_NUM or less than 0");
        }
        if (machineId > MAX_MACHINE_NUM || machineId < 0) {
            throw new IllegalArgumentException("machineId can't be greater than MAX_MACHINE_NUM or less than 0");
        }
        this.datacenterId = datacenterId;
        this.machineId = machineId;
    }

    
    public synchronized long nextId() {
        long currStmp = getNewstmp();
        if (currStmp < lastStmp) {
            throw new RuntimeException("Clock moved backwards.  Refusing to generate id");
        }

        if (currStmp == lastStmp) {
            //相同毫秒内,序列号自增
            sequence = (sequence + 1) & MAX_SEQUENCE;
            //同一毫秒的序列数已经达到最大
            if (sequence == 0L) {
                currStmp = getNextMill();
            }
        } else {
            //不同毫秒内,序列号置为0
            sequence = 0L;
        }

        lastStmp = currStmp;

        return (currStmp - START_STMP) << TIMESTMP_LEFT //时间戳部分
                | datacenterId << DATACENTER_LEFT       //数据中心部分
                | machineId << MACHINE_LEFT             //机器标识部分
                | sequence;                             //序列号部分
    }

    private long getNextMill() {
        long mill = getNewstmp();
        while (mill <= lastStmp) {
            mill = getNewstmp();
        }
        return mill;
    }

    private long getNewstmp() {
        return System.currentTimeMillis();
    }

    public static void main(String[] args) throws ParseException {
        // 时间戳
        // System.out.println(System.currentTimeMillis());
        // System.out.println(new Date().getTime());
        //
        // String dateTime = "2021-01-01 08:00:00";
        // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        // System.out.println(sdf.parse(dateTime).getTime());

        SnowFlake snowFlake = new SnowFlake(1, 1);

        long start = System.currentTimeMillis();
        for (int i = 0; i < 10; i++) {
            System.out.println(snowFlake.nextId());
            System.out.println(System.currentTimeMillis() - start);
        }
    }
}
 IP的util
package com.wlc.doc.util;

import javax.servlet.http.HttpServletRequest;


public class IPUtil {
    private static final String UNKNOWN = "unknown";

    protected IPUtil(){
    
    }

    
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
    }
 
}
OkhttpUtils,http请求工具类
package com.utils;

import com.alibaba.fastjson.JSON;
import okhttp3.*;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;


public class OkHttpUtils {
    //OkHttp客户端
    private static volatile OkHttpClient okHttpClient = null;
    //OkHttp请求信号量*/
    private static volatile Semaphore semaphore = null;
    //OkHttp的requestHeader参数map
    private Map headerMap;
    //OkHttp的request参数map
    private Map paramMap;
    //OkHttp的请求url
    private String url;
    //OkHttp的Request
    private Request.Builder request;

    
    private OkHttpUtils() {
        if (okHttpClient == null) {
            synchronized (OkHttpUtils.class) {
                if (okHttpClient == null) {
                    TrustManager[] trustManagers = buildTrustManagers();
                    okHttpClient = new OkHttpClient.Builder()
                            .connectTimeout(15, TimeUnit.SECONDS)
                            .writeTimeout(20, TimeUnit.SECONDS)
                            .readTimeout(20, TimeUnit.SECONDS)
                            .sslSocketFactory(createSSLSocketFactory(trustManagers), (X509TrustManager) trustManagers[0])
                            .hostnameVerifier((hostName, session) -> true)
                            .retryOnConnectionFailure(true)
                            .build();
                    addHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
                }
            }
        }
    }

    
    private static Semaphore getSemaphoreInstance() {
        //只能1个线程同时访问
        synchronized (OkHttpUtils.class) {
            if (semaphore == null) {
                semaphore = new Semaphore(0);
            }
        }
        return semaphore;
    }

    
    public static OkHttpUtils builder() {
        return new OkHttpUtils();
    }

    
    public OkHttpUtils url(String url) {
        this.url = url;
        return this;
    }

    
    public OkHttpUtils addParam(String key, String value) {
        if (paramMap == null) {
            paramMap = new LinkedHashMap<>(16);
        }
        paramMap.put(key, value);
        return this;
    }

    
    public OkHttpUtils addHeader(String key, String value) {
        if (headerMap == null) {
            headerMap = new LinkedHashMap<>(16);
        }
        headerMap.put(key, value);
        return this;
    }

    
    public OkHttpUtils get() {
        request = new Request.Builder().get();
        StringBuilder urlBuilder = new StringBuilder(url);
        if (paramMap != null) {
            urlBuilder.append("?");
            try {
                for (Map.Entry entry : paramMap.entrySet()) {
                    urlBuilder.append(URLEncoder.encode(entry.getKey(), "utf-8")).
                            append("=").
                            append(URLEncoder.encode(entry.getValue().toString(), "utf-8")).
                            append("&");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            urlBuilder.deleteCharAt(urlBuilder.length() - 1);
        }
        request.url(urlBuilder.toString());
        return this;
    }

    
    public OkHttpUtils post(boolean isJsonPost) {
        RequestBody requestBody;
        if (isJsonPost) {
            String json = "";
            if (paramMap != null) {
                json = JSON.toJSONString(paramMap);
            } 
            requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
        } else {
            FormBody.Builder formBody = new FormBody.Builder();
            if (paramMap != null) {
                //paramMap.forEach(formBody::add());
                for (String key : paramMap.keySet()) {
                    formBody.add(key, paramMap.get(key).toString());
                }
            }
            requestBody = formBody.build();
        }
        request = new Request.Builder().post(requestBody).url(url);
        return this;
    }

    
    public OkHttpUtils uploadFile(File file, String fileName) throws Exception {
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", fileName, RequestBody.create(MediaType.parse("multipart/form-data"), file))
                .build();
        request = new Request.Builder().post(requestBody).url(url);
        return this;

    }



    
    public OkHttpUtils uploadFile(String filePath, String fileName) throws Exception {
        return uploadFile(new File(filePath), fileName);

    }


    
    public OkHttpUtils uploadFiles(HashMap filesMap) throws Exception {
        MultipartBody.Builder builder = new MultipartBody.Builder();
        for (String fileName : filesMap.keySet()) {
            builder.addFormDataPart("file", fileName, RequestBody.create(MediaType.parse("multipart/form-data"), filesMap.get(fileName)));
        }
        RequestBody requestBody = builder.setType(MultipartBody.FORM)
                .build();
        request = new Request.Builder().post(requestBody).url(url);
        return this;

    }



    
    public String sync() {
        setHeader(request);
        try {
            Response response = okHttpClient.newCall(request.build()).execute();
            assert response.body() != null;
            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
            return "请求失败:" + e.getMessage();
        }
    }

    
    public String async() {
        StringBuilder buffer = new StringBuilder("");
        setHeader(request);
        okHttpClient.newCall(request.build()).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                buffer.append("请求出错:").append(e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                assert response.body() != null;
                buffer.append(response.body().string());
                getSemaphoreInstance().release();
            }
        });
        try {
            getSemaphoreInstance().acquire();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }

    
    public void async(ICallBack callBack) {
        setHeader(request);
        okHttpClient.newCall(request.build()).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callBack.onFailure(call, e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                assert response.body() != null;
                callBack.onSuccessful(call, response.body().string());
            }
        });
    }

    
    private void setHeader(Request.Builder request) {
        if (headerMap != null) {
            try {
                for (Map.Entry entry : headerMap.entrySet()) {
                    request.addHeader(entry.getKey(), entry.getValue().toString());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    
    private static SSLSocketFactory createSSLSocketFactory(TrustManager[] trustAllCerts) {
        SSLSocketFactory ssfFactory = null;
        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new SecureRandom());
            ssfFactory = sc.getSocketFactory();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ssfFactory;
    }

    private static TrustManager[] buildTrustManagers() {
        return new TrustManager[]{
                new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(X509Certificate[] chain, String authType) {
                    }

                    @Override
                    public void checkServerTrusted(X509Certificate[] chain, String authType) {
                    }

                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return new X509Certificate[]{};
                    }
                }
        };
    }

    
    public interface ICallBack {

        void onSuccessful(Call call, String data);

        void onFailure(Call call, String errorMsg);

    }
}




使用示例:

package com.demo;

import com.utils.OkHttpUtils;
import okhttp3.Call;


public class OkHttpUtilDemo {

    public static void main(String[] args) {
        // get请求,方法顺序按照这种方式,切记选择post/get一定要放在倒数第二,同步或者异步倒数第一,才会正确执行
        String getData = OkHttpUtils.builder().url("请求地址,http/https都可以")
                // 有参数的话添加参数,可多个
                .addParam("参数名", "参数值")
                .addParam("参数名", "参数值")
                // 也可以添加多个
                .addHeader("Content-Type", "application/json; charset=utf-8")
                .get()
                // 可选择是同步请求还是异步请求
                //.async();
                .sync();

        // post请求,分为两种,一种是普通表单提交,一种是json提交
        String postData = OkHttpUtils.builder().url("请求地址,http/https都可以")
                // 有参数的话添加参数,可多个
                .addParam("参数名", "参数值")
                .addParam("参数名", "参数值")
                // 也可以添加多个
                .addHeader("Content-Type", "application/json; charset=utf-8")
                // 如果是true的话,会类似于postman中post提交方式的raw,用json的方式提交,不是表单
                // 如果是false的话传统的表单提交
                .post(true)
                .sync();

        // 选择异步有两个方法,一个是带回调接口,一个是直接返回结果
        OkHttpUtils.builder().url("")
                .post(false)
                .async(new OkHttpUtils.ICallBack() {
                    @Override
                    public void onSuccessful(Call call, String data) {
                        // 请求成功后的处理
                    }

                    @Override
                    public void onFailure(Call call, String errorMsg) {
                        // 请求失败后的处理
                    }
                });

        OkHttpUtils.builder().url("").post(false).async(new OkHttpUtils.ICallBack() {
            @Override
            public void onSuccessful(Call call, String data) {
                // 请求成功后的处理
            }

            @Override
            public void onFailure(Call call, String errorMsg) {
                // 请求失败后的处理
            }
        });
    }

}
文件上传demo

package com.zxl.util;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


@Component
public class FileUtil {

    private static void upLoadFile() throws Exception {
        File file = new File("D:\test.json");
        File file1 = new File("D:\test1.json");
        HashMap fileMap = new HashMap<>();
        fileMap.put("test", file);
        fileMap.put("test1", file1);
    //对文件上传
        String result = OkHttpUtils.builder().addParam("Authorization", "Client-ID " + UUID.randomUUID())
                .url("http://127.0.0.1:18000/file/uploadsMinio")
                .uploadFiles(fileMap)
                .sync();
        System.out.println(result);

    }

    public static void main(String[] args) throws Exception {
        upLoadFile();
    }

}
 redis操作类util
package com.utils;

import java.nio.charset.StandardCharsets;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import com.redisKeydelay.LiveRedisKeyConstant;
import com.redisKeydelay.RedisLockDefinitionHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;


@Slf4j
@Component
public final class RedisUtil {
    @Autowired
    private RedisTemplate redisTemplate;

    // =============================common============================
    
    public boolean expire(String key, long time) {
        try {
            if (time > 0) {
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    public long getExpire(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }
    
    public boolean hasKey(String key) {
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    @SuppressWarnings("unchecked")
    public void del(String... key) {
        if (key != null && key.length > 0) {
            if (key.length == 1) {
                redisTemplate.delete(key[0]);
            } else {
                redisTemplate.delete(CollectionUtils.arrayToList(key));
            }
        }
    }
    // ============================String=============================
    
    public Object get(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }
    
    public boolean set(String key, Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    
    public HashMap keys( String pattern){
        //根据通配符获取key的set集合
        Set set=redisTemplate.keys(pattern);
        if (CollectionUtils.isEmpty(set)){
            return null;
        }
        HashMap map = new HashMap<>();
        //遍历key的set集合,获取对应的value
        for (String key : set){
            //通过查到的key值获取value,并放入result
            map.put(key, redisTemplate.opsForValue().get(key));
        }
        return map;
    }


    
    public Set scanKeys(String pattern) {
        Set set = redisTemplate.execute((RedisCallback>) connection -> {
            Set binaryKeys = new HashSet<>();
            Cursor cursor = connection.scan(new ScanOptions.ScanOptionsBuilder().match(pattern).count(Integer.MAX_VALUE).build());
            while (cursor.hasNext()) {
                binaryKeys.add(new String(cursor.next()));
            }
            return binaryKeys;
        });
        if (CollectionUtils.isEmpty(set)){
            return null;
        }
        HashMap k_v_map = new HashMap<>();
        for (String key : set) {
            //通过查到的key值获取value,并放入result
            k_v_map.put(key, redisTemplate.opsForValue().get(key));
        }
        for (String key : k_v_map.keySet()) {
            System.out.println("key = " + key + "   val = " + k_v_map.get(key));
        }
        return set;
    }

    
    public boolean set(String key, Object value, long time) {
        try {
            if (time > 0) {
                redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
                //设置当前线程的redis的key到续命队列
                LiveRedisKeyConstant.addLiveRedisKeyHolderList(new RedisLockDefinitionHolder(key, time, System.currentTimeMillis(),
                        Thread.currentThread(), LiveRedisKeyConstant.getDefaultTryCount()));
            } else {
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    public long incr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("递增因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(key, delta);
    }
    
    public long decr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("递减因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(key, -delta);
    }
    
    public Object hget(String key, String item) {
        return redisTemplate.opsForHash().get(key, item);
    }
    
    public Map hmget(String key) {
        return redisTemplate.opsForHash().entries(key);
    }
    
    public boolean hmset(String key, Map map) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    public boolean hmset(String key, Map map, long time) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    public boolean hset(String key, String item, Object value) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    public boolean hset(String key, String item, Object value, long time) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    public void hdel(String key, Object... item) {
        redisTemplate.opsForHash().delete(key, item);
    }
    
    public boolean hHasKey(String key, String item) {
        return redisTemplate.opsForHash().hasKey(key, item);
    }
    
    public double hincr(String key, String item, double by) {
        return redisTemplate.opsForHash().increment(key, item, by);
    }
    
    public double hdecr(String key, String item, double by) {
        return redisTemplate.opsForHash().increment(key, item, -by);
    }
    
    public Set sGet(String key) {
        try {
            return redisTemplate.opsForSet().members(key);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    public boolean sHasKey(String key, Object value) {
        try {
            return redisTemplate.opsForSet().isMember(key, value);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    public long sSet(String key, Object... values) {
        try {
            return redisTemplate.opsForSet().add(key, values);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
    
    public long sSetAndTime(String key, long time, Object... values) {
        try {
            Long count = redisTemplate.opsForSet().add(key, values);
            if (time > 0)
            expire(key, time);
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
    
    public long sGetSetSize(String key) {
        try {
            return redisTemplate.opsForSet().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
    
    public long setRemove(String key, Object... values) {
        try {
            Long count = redisTemplate.opsForSet().remove(key, values);
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
    // ===============================list=================================
    
    public List lGet(String key, long start, long end) {
        try {
            return redisTemplate.opsForList().range(key, start, end);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    public long lGetListSize(String key) {
        try {
            return redisTemplate.opsForList().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
    
    public Object lGetIndex(String key, long index) {
        try {
            return redisTemplate.opsForList().index(key, index);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    public boolean lSet(String key, Object value) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    public boolean lSet(String key, Object value, long time) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            if (time > 0)
            expire(key, time);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    public boolean lSet(String key, List value) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    
    public boolean lSet(String key, List value, long time) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            if (time > 0)
            expire(key, time);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    public boolean lUpdateIndex(String key, long index, Object value) {
        try {
            redisTemplate.opsForList().set(key, index, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    public long lRemove(String key, long count, Object value) {
        try {
            Long remove = redisTemplate.opsForList().remove(key, count, value);
            return remove;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    public boolean setIfAbsent(String key, Object value, long exptime) {
        Boolean result = (Boolean) redisTemplate.execute(new RedisCallback() {
            @Override
            public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
                RedisSerializer valueSerializer = redisTemplate.getValueSerializer();
                RedisSerializer keySerializer = redisTemplate.getKeySerializer();
                Object obj = connection.execute("set", keySerializer.serialize(key),
                        valueSerializer.serialize(value),
                        "NX".getBytes(StandardCharsets.UTF_8),
                        "EX".getBytes(StandardCharsets.UTF_8),
                        String.valueOf(exptime).getBytes(StandardCharsets.UTF_8));
                return obj != null;
            }
        });
        return result;
    }

    
    public boolean pfadd (String key, Object value){
        try {
            HyperLogLogOperations hyperLogLog = redisTemplate.opsForHyperLogLog();
            hyperLogLog.add(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    
    public long pfcount(String key){
        try {
            HyperLogLogOperations hyperLogLog = redisTemplate.opsForHyperLogLog();
            Long size = hyperLogLog.size(key);
            return size;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    
    public boolean pfdelete(String key){
        try {
            HyperLogLogOperations hyperLogLog = redisTemplate.opsForHyperLogLog();
            hyperLogLog.delete(key);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    //设置6自增6位,用于补全操作
    private static final String STR_FORMAT = "000000";

    
    public String incrSerialNum(String key, long liveTime) {
        RedisAtomicLong entityIdCounter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
        Long increment = entityIdCounter.getAndIncrement();

        if ((null == increment || increment.longValue() == 0) && liveTime > 0) {//初始设置过期时间
            entityIdCounter.expire(liveTime, TimeUnit.SECONDS);    //设置自增值过期时间,liveTime 过期时间;TimeUnit.DAYS 过期时间单位,我这边设置为天
            //entityIdCounter.expire(liveTime, TimeUnit.DAYS);    //设置自增值过期时间,liveTime 过期时间;TimeUnit.DAYS 过期时间单位,我这边设置为天
        }
        if (increment == 0) {
            increment = increment + 1;
        } else if (increment > 999999){
            increment = 1L;
        }
        //位数不够,前面补0
        DecimalFormat df = new DecimalFormat(STR_FORMAT);
        return df.format(increment);
    }


    public String getOrderNo(String prefixFlag){
        StringBuffer sb = new StringBuffer();
        sb.append(prefixFlag);        //标志位
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        sb.append(sdf.format(new Date()));     //年月日时分秒
        String prefixStr = sb.toString();
        String no = incrSerialNum(prefixStr, 1);
        sb.append(no);
        return sb.toString();
    }




} 

更多精彩分享请移步:IT学习道场

更多分享关注公众号【IT学习道场】

 

转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号