java部分util公用方法

2019-05-07 14:30:54 浏览数 (1)

  • 获取Ip地址
代码语言:javascript复制
/**
     * 获取Ip地址
     * @param request
     * @return
     */
    public  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 ip.equals("0:0:0:0:0:0:0:1")?"127.0.0.1":ip;
    }
  • 懒加载模式
代码语言:javascript复制
public class Lazy<T> {
    private transient Supplier<T> supplier;
    private volatile T value;

    private Lazy(){}
    private Lazy(Supplier<T> supplier) {
        this.supplier = Objects.requireNonNull(supplier);
    }

    public T get() {
        if (value == null) {
            synchronized (this) {
                if (value == null) {
                    value = Objects.requireNonNull(supplier.get());
                    supplier = null;
                }
            }
        }
        return value;
    }
    public <R> Lazy<R> map(Function<T, R> mapper) {
        return new Lazy<>(() -> mapper.apply(this.get()));
    }
    public <R> Lazy<R> flatMap(Function<T, Lazy<R>> mapper) {
        return new Lazy<>(() -> mapper.apply(this.get()).get());
    }
    public Lazy<Optional<T>> filter(Predicate<T> predicate) {
        return new Lazy<>(() -> Optional.of(get()).filter(predicate));
    }

    public static <T> Lazy<T> of(Supplier<T> supplier) {
        return new Lazy<>(supplier);
    }
}
  • try-catch 通用模式
代码语言:javascript复制
public class CatchUtil {

    public static <T,R> R tryDo(T t, Function<T,R> func) {
        try {
            return func.apply(t);
        } catch (Exception e) {
            e.printStackTrace();  // for log
            throw new RuntimeException(e.getCause());
        }
    }

    public static <T> void tryDo(T t, Consumer<T> func) {
        try {
            func.accept(t);
        } catch (Exception e) {
            e.printStackTrace();  // for log
            throw new RuntimeException(e.getCause());
        }
    }

}
  • 多线程执行
代码语言:javascript复制
public class ExecutorUtil {

    private ExecutorUtil() {}

    private static final int CORE_CPUS = Runtime.getRuntime().availableProcessors();
    private static final int TASK_SIZE = 1000;

    // a throol pool may be managed by spring
    private static ExecutorService executor = new ThreadPoolExecutor(
            CORE_CPUS, 10, 60L, TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(60));

    /**
     * 根据指定的列表关键数据及列表数据处理器,并发地处理并返回处理后的列表数据集合
     * @param allKeys 列表关键数据
     * @param handleBizDataFunc 列表数据处理器
     * @param <T> 待处理的数据参数类型
     * @param <R> 待返回的数据结果类型
     * @return 处理后的列表数据集合
     *
     * NOTE: 类似实现了 stream.par.map 的功能,不带延迟计算
     */
    public static <T,R> List<R> exec(List<T> allKeys, Function<List<T>, List<R>> handleBizDataFunc) {
        List<String> parts = TaskUtil.divide(allKeys.size(), TASK_SIZE);
        //获取
        CompletionService<List<R>>
                completionService = new ExecutorCompletionService<>(executor);

        ForeachUtil.foreachDone(parts, (part) -> {
            final List<T> tmpRowkeyList = TaskUtil.getSubList(allKeys, part);
            completionService.submit(
                    // lambda replace inner class
                    () -> handleBizDataFunc.apply(tmpRowkeyList));
        });

        // foreach code refining
        List<R> result = ForeachUtil.foreachAddWithReturn(parts.size(), (ind) -> get(ind, completionService));
        return result;
    }

    /**
     * 根据指定的列表关键数据及列表数据处理器,并发地处理
     * @param allKeys 列表关键数据
     * @param handleBizDataFunc 列表数据处理器
     * @param <T> 待处理的数据参数类型
     *
     * NOTE: foreachDone 的并发版
     */
    public static <T> void exec(List<T> allKeys, Consumer<List<T>> handleBizDataFunc) {
        List<String> parts = TaskUtil.divide(allKeys.size(), TASK_SIZE);

        ForeachUtil.foreachDone(parts, (part) -> {
            final List<T> tmpRowkeyList = TaskUtil.getSubList(allKeys, part);
            // lambda replace inner class
            executor.execute(
                    () -> handleBizDataFunc.accept(tmpRowkeyList));
        });
    }


    public static <T> List<T> get(int ind, CompletionService<List<T>> completionService) {
        // lambda cannot handler checked exception
        try {
            return completionService.take().get();
        } catch (Exception e) {
            e.printStackTrace();  // for log
            throw new RuntimeException(e.getCause());
        }

    }

}

//循环通用
public class ForeachUtil {

    public static <T> List<T> foreachAddWithReturn(int num, Function<Integer, List<T>> getFunc) {
        List<T> result = new ArrayList<T>();
        for (int i=0; i< num; i  ) {

            result.addAll(CatchUtil.tryDo(i, getFunc));
        }
        return result;
    }


    public static <T> Lazy<List<T>> foreachAddReturn(int num, Function<Integer,T> getFunc){
        List<T> result = new ArrayList<>();

        IntStream.of(num).forEach( i->
                result.add(CatchUtil.tryDo(i,getFunc))
        );
        return Lazy.of(()-> result);
    }

    public static <T> void foreachDone(List<T> data, Consumer<T> doFunc) {
        for (T part: data) {
            CatchUtil.tryDo(part, doFunc);
        }
    }

}
  • List<T> stream转换List<R>
代码语言:javascript复制
public class StreamUtil {

    public static <T,R> List<R> map(List<T> data, Function<T, R> mapFunc) {
        // stream replace foreach
        return data.stream().map(mapFunc).collect(Collectors.toList());

    }

}

0 人点赞