BaseController.java 19.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559
package com.huaheng.framework.web.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.huaheng.api.srm.domain.SRMResult;
import com.huaheng.common.utils.StringUtils;
import com.huaheng.common.utils.security.ShiroUtils;
import com.huaheng.framework.web.domain.AjaxResult;
import com.huaheng.framework.web.domain.AjaxResultTv;
import com.huaheng.framework.web.domain.ResultErp;
import com.huaheng.framework.web.page.PageDomain;
import com.huaheng.framework.web.page.TableDataInfo;
import com.huaheng.framework.web.page.TableSupport;
import com.huaheng.pc.system.user.domain.User;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import javax.annotation.Nonnull;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * web层通用数据处理
 *
 * @author huaheng
 */
public class BaseController {
    /**
     * 将前台传递过来的日期格式的字符串,自动转化为Date类型
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));

//        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//        LocalDateTime time = LocalDateTime.now();
//        String localTime = df.format(time);
//        将LocalDateTime转为String
    }

    /**
     * 设置请求分页数据
     */
    protected void startPage() {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            String orderBy = pageDomain.getOrderBy();
            PageHelper.startPage(pageNum, pageSize, orderBy);
        }
    }

    protected void startPages() {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize() / 2;
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            String orderBy = pageDomain.getOrderBy();
            PageHelper.startPage(pageNum, pageSize, orderBy);
        }
    }

    /**
     * 设置请求分页数据
     */
    protected void startPage(Integer pageNum, Integer pageSize, String orderBy) {
        PageHelper.startPage(pageNum, pageSize, orderBy);
    }

    /**
     * 响应请求分页数据
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    protected TableDataInfo getDataTable(List<?> list) {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(200);
        rspData.setData(list);
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }

    /**
     * 响应返回结果
     *
     * @param rows 影响行数
     * @return 操作结果
     */
    protected AjaxResult toAjax(int rows) {
        return rows > 0 ? success() : error();
    }

    /**
     * 响应返回结果
     *
     * @param succeed 是否成功
     * @return 操作结果
     */
    protected AjaxResult toAjax(boolean succeed) {
        return succeed ? success() : error();
    }

    /**
     * 返回成功
     */
    public AjaxResult success() {
        return AjaxResult.success("操作成功!");
    }

    /**
     * 返回失败消息
     */
    public AjaxResult error() {
        return AjaxResult.error("操作失败!");
    }

    /**
     * 返回成功消息
     */
    public AjaxResult success(String message) {
        return AjaxResult.success(message);
    }

    /**
     * 返回失败消息
     */
    public AjaxResult error(String message) {
        return AjaxResult.error(message);
    }

//    /**
//     * 返回错误码消息
//     */
//    public AjaxResult error(int code, String message)
//    {
//        return AjaxResult.error(code, message);
//    }

    /**
     * 页面跳转
     */
    public String redirect(String url) {
        return StringUtils.format("redirect:{}", url);
    }

    public User getUser() {
        return ShiroUtils.getUser();
    }

    public void setUser(User user) {
        ShiroUtils.setUser(user);
    }

    public Integer getUserId() {
        return getUser().getId();
    }

    public String getLoginName() {
        return getUser().getLoginName();
    }

    /**
     * mybatis-plus响应请求分页数据
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    protected TableDataInfo getMpDataTable(List<?> list, Long total) {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(200);
        rspData.setData(list);
        rspData.setTotal(total);
        return rspData;
    }

    Semaphore semaphore = new Semaphore(1);

    public AjaxResult handleMultiProcess(MultiProcessListener multiProcessListener) {
        AjaxResult ajaxResult = null;
        int max_time = 30 * 1000;
        int now = 0;
        boolean avail = true;
        while (avail) {
            int availablePermits = semaphore.availablePermits();
            if (availablePermits > 0) {
                avail = false;
                try {
                    semaphore.acquire(1);
                    ajaxResult = multiProcessListener.doProcess();
                } catch (Exception e) {
                    e.printStackTrace();
                    ajaxResult = AjaxResult.error(e.getMessage());
                } finally {
                    semaphore.release(1);
                }
            } else {
                ajaxResult = AjaxResult.error("多线程处理异常");
                try {
                    now = now + 200;
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (now >= max_time) {
                    avail = false;
                }
            }
        }
        return ajaxResult;
    }

    public interface MultiProcessListener {
        AjaxResult doProcess();
    }

    // 下发任务并发控制
    Map<String, Boolean> multiProcessMap = new HashMap<>();

    public AjaxResult handleMultiProcessV1(String taskKey, MultiProcessListener multiProcessListener) {
        AjaxResult ajaxResult = null;
        int max_time = 50 * 1000;
        int now = 0;
        boolean avail = true;
        while (avail) {
            boolean availablePermits = MapUtils.getBoolean(multiProcessMap, taskKey, false);
            if (!availablePermits) {
                avail = false;
                try {
                    multiProcessMap.put(taskKey, true);
                    ajaxResult = multiProcessListener.doProcess();
                } catch (Exception e) {
                    e.printStackTrace();
//                    throw new RuntimeException(e);
                    ajaxResult = AjaxResult.error(e.getMessage());
                } finally {
                    multiProcessMap.put(taskKey, false);
                }
            } else {
                ajaxResult = AjaxResult.error("多线程处理异常, 待处理现场太多,等待时间超出30秒");
                try {
                    now = now + 200;
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (now >= max_time) {
                    avail = false;
                }
            }
        }
        return ajaxResult;
    }
    public AjaxResult handleMultiProcessV2(String taskKey, MultiProcessListener multiProcessListener) {
        AjaxResult ajaxResult = null;
        int max_time = 10*60*1000;
        int now = 0;
        boolean avail = true;
        while (avail) {
            boolean availablePermits = MapUtils.getBoolean(multiProcessMap, taskKey, false);
            if (!availablePermits) {
                avail = false;
                try {
                    multiProcessMap.put(taskKey, true);
                    ajaxResult = multiProcessListener.doProcess();
                } catch (Exception e) {
                    e.printStackTrace();
//                    throw new RuntimeException(e);
                    ajaxResult = AjaxResult.error(e.getMessage());
                } finally {
                    multiProcessMap.put(taskKey, false);
                }
            } else {
                ajaxResult = AjaxResult.error("多线程处理异常, 待处理现场太多,等待时间超出60秒");
                try {
                    now = now + 200;
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (now >= max_time) {
                    avail = false;
                }
            }
        }
        return ajaxResult;
    }

    public AjaxResult handleMultiProcessV3(String taskKey, MultiProcessListener multiProcessListener) {
        AjaxResult ajaxResult = null;
        int max_time = 10*90*1000;
        int now = 0;
        boolean avail = true;
        while (avail) {
            boolean availablePermits = MapUtils.getBoolean(multiProcessMap, taskKey, false);
            if (!availablePermits) {
                avail = false;
                try {
                    multiProcessMap.put(taskKey, true);
                    ajaxResult = multiProcessListener.doProcess();
                } catch (Exception e) {
                    e.printStackTrace();
//                    throw new RuntimeException(e);
                    ajaxResult = AjaxResult.error(e.getMessage());
                } finally {
                    multiProcessMap.put(taskKey, false);
                }
            } else {
                ajaxResult = AjaxResult.error("多线程处理异常, 待处理现场太多,等待时间超出90秒");
                try {
                    now = now + 200;
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (now >= max_time) {
                    avail = false;
                }
            }
        }
        return ajaxResult;
    }

    /**
     * 获取分布式锁,自定义锁等待,释放时间</br>
     * 注意锁与事务的顺序:获取分布式锁 -> 开启事务 -> 执行业务 -> 提交事务 -> 释放分布式锁
     * @param      lockKey
     * @param      multiProcessListener
     * @return
     */
    public AjaxResult handleMultiProcessLock(String taskKey,String lockKey,MultiProcessListener multiProcessListener ) {
        AjaxResult ajaxResult = null;
        int max_time = 10*90*1000;
        int now = 0;
        String key=taskKey+"_"+lockKey;
        boolean avail = true;
        while (avail) {
            boolean availablePermits = MapUtils.getBoolean(multiProcessMap, key, false);
            if (!availablePermits) {
                avail = false;
                try {
                    multiProcessMap.put(key, true);
                    ajaxResult = multiProcessListener.doProcess();
                } catch (Exception e) {
                    e.printStackTrace();
//                    throw new RuntimeException(e);
                    ajaxResult = AjaxResult.error(e.getMessage());
                } finally {
                    multiProcessMap.put(key, false);
                }
            } else {
                ajaxResult = AjaxResult.error("多线程处理异常, 待处理现场太多,等待时间超出90秒");
                try {
                    now = now + 200;
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (now >= max_time) {
                    avail = false;
                }
            }
        }
        return ajaxResult;
    }
    public interface MultiProcessListenerErp {
        ResultErp doProcess();
    }
    public ResultErp handleMultiProcessErp(String taskKey, MultiProcessListenerErp multiProcessListener) {
        ResultErp ajaxResult = null;
        int max_time = 30 * 1000;
        int now = 0;
        boolean avail = true;
        while (avail) {
            boolean availablePermits = MapUtils.getBoolean(multiProcessMap, taskKey, false);
            if (!availablePermits) {
                avail = false;
                try {
                    multiProcessMap.put(taskKey, true);
                    ajaxResult = multiProcessListener.doProcess();
                } catch (Exception e) {
                    e.printStackTrace();
//                    throw new RuntimeException(e);
                    ajaxResult = ResultErp.error(e.getMessage());
                } finally {
                    multiProcessMap.put(taskKey, false);
                }
            } else {
                ajaxResult = ResultErp.error("多线程处理异常, 待处理现场太多,等待时间超出30秒");
                try {
                    now = now + 200;
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (now >= max_time) {
                    avail = false;
                }
            }
        }
        return ajaxResult;
    }
    public interface MultiProcessListenerTv {
        AjaxResultTv doProcess();
    }
    public AjaxResultTv handleMultiProcessTv(String taskKey, MultiProcessListenerTv multiProcessListener) {
        AjaxResultTv ajaxResult = null;
        int max_time = 30 * 1000;
        int now = 0;
        boolean avail = true;
        while (avail) {
            boolean availablePermits = MapUtils.getBoolean(multiProcessMap, taskKey, false);
            if (!availablePermits) {
                avail = false;
                try {
                    multiProcessMap.put(taskKey, true);
                    ajaxResult = multiProcessListener.doProcess();
                } catch (Exception e) {
                    e.printStackTrace();
//                    throw new RuntimeException(e);
                    ajaxResult = AjaxResultTv.error(e.getMessage());
                } finally {
                    multiProcessMap.put(taskKey, false);
                }
            } else {
                ajaxResult = AjaxResultTv.error("多线程处理异常, 待处理现场太多,等待时间超出30秒");
                try {
                    now = now + 200;
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (now >= max_time) {
                    avail = false;
                }
            }
        }
        return ajaxResult;
    }
    public interface MultiProcessListenerSrm {
        SRMResult doProcess();
    }
    public SRMResult handleMultiProcessSrm(String taskKey, MultiProcessListenerSrm multiProcessListener) {
        SRMResult ajaxResult = new SRMResult();
        int max_time = 30 * 1000;
        int now = 0;
        boolean avail = true;
        while (avail) {
            boolean availablePermits = MapUtils.getBoolean(multiProcessMap, taskKey, false);
            if (!availablePermits) {
                avail = false;
                try {
                    multiProcessMap.put(taskKey, true);
                    ajaxResult = multiProcessListener.doProcess();
                } catch (Exception e) {
                    e.printStackTrace();
//                    throw new RuntimeException(e);
                    ajaxResult.setSuccess(false);
                    ajaxResult.setMessage(e.getMessage());
                } finally {
                    multiProcessMap.put(taskKey, false);
                }
            } else {
                ajaxResult.setSuccess(false);
                ajaxResult.setMessage("多线程处理异常, 待处理现场太多,等待时间超出30秒");
//                ajaxResult = ResultErp.error("多线程处理异常, 待处理现场太多,等待时间超出30秒");
                try {
                    now = now + 200;
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (now >= max_time) {
                    avail = false;
                }
            }
        }
        return ajaxResult;
    }

    // 存放每个 key 对应的独立锁
    private static final Map<String, ReentrantLock> lockMap = new ConcurrentHashMap<>();

    /**
     * 手工锁控制并发,带最大等待时间
     */
    public AjaxResult handleMultiProcessLock1(String taskKey, String lockKey, MultiProcessListener multiProcessListener) {
        String key = taskKey + "_" + lockKey;
        ReentrantLock lock = lockMap.computeIfAbsent(key, k -> new ReentrantLock());

        boolean locked = false;
        try {
            // 最长等待 90 秒尝试获取锁
            locked = lock.tryLock(90, TimeUnit.SECONDS);

            if (locked) {
                // 拿到锁后执行逻辑
                return multiProcessListener.doProcess();
            } else {
                return AjaxResult.error("多线程处理异常:等待超时(超过90秒未获取锁)");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("执行异常:" + e.getMessage());
        } finally {
            // 只有成功获取锁后才能释放
            if (locked) {
                lock.unlock();
            }
            // 可选:清理无用锁对象,防止内存堆积
            if (!lock.hasQueuedThreads()) {
                lockMap.remove(key);
            }
        }
    }

    // 使用线程安全的ConcurrentHashMap存储锁状态
    private final Map<String, Boolean> lockMap1 = new ConcurrentHashMap<>();
    /**
     * 基于手工锁的并发控制处理
     * @param lockKey 锁标识(方法名称+唯一号组合)
     * @param task 需要执行的任务
     * @return 处理结果
     */
    public AjaxResult handleSingleNodeLock(String lockKey, Runnable task) {
        // 1. 原子操作获取锁(使用putIfAbsent实现CAS效果)
        Boolean lockAcquired = lockMap1.putIfAbsent(lockKey,  Boolean.TRUE) == null;

        // 2. 未获取到锁直接返回
        if (!lockAcquired) {
            return AjaxResult.error(" 系统处理中,请稍后重试");
        }

        try {
            // 3. 执行任务
            task.run();
            return AjaxResult.success();
        } catch (Exception e) {
            // 4. 捕获任务执行异常
            return AjaxResult.error(" 任务执行失败: " + e.getMessage());
        } finally {
            // 5. 确保锁释放(无论成功失败都执行)
            lockMap1.remove(lockKey);
        }
//        AjaxResult ajaxResult1 =handleSingleNodeLock("complete",() -> {
//            // 这里编写具体业务逻辑
//            // ...订单处理代码...
//        });
    }

}