首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >java部分util公用方法

java部分util公用方法

作者头像
用户1418372
发布2019-05-07 14:30:54
9260
发布2019-05-07 14:30:54
举报
文章被收录于专栏:清晨我上码清晨我上码
  • 获取Ip地址
/**
     * 获取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;
    }
  • 懒加载模式
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 通用模式
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());
        }
    }

}
  • 多线程执行
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>
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());

    }

}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019.04.22 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档