PigCloud项目的使用解析二

1.mc-edu模块结构

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
这面一样是使用了熔断工厂类,远程调用下面第三方接口,失败则执行熔断器的异常逻辑处理。

FamousSchoolController:

package com.hst.mc.cms.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hst.mc.cms.api.dto.FamousSchoolDTO;
import com.hst.mc.cms.api.dto.SearchCondition;
import com.hst.mc.cms.api.entity.FamousSchool;
import com.hst.mc.cms.api.vo.FamousSchoolVO;
import com.hst.mc.cms.api.vo.FamousTeacherVO;
import com.hst.mc.cms.service.FamousSchoolService;
import com.pig4cloud.pig.admin.api.dto.UpdateOrgDTO;
import com.pig4cloud.pig.common.core.constant.SecurityConstants;
import com.pig4cloud.pig.common.core.constant.enums.OperateTypeEnum;
import com.pig4cloud.pig.common.core.constant.enums.OrgEnum;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.core.util.WebUtils;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.security.annotation.Inner;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import java.util.List;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


/**
 * 名校
 *
 * @author lixw
 * @date 2021-07-16 11:46:46
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/famousSchool")
@Api(value = "famousSchool", tags = "名校管理")
public class FamousSchoolController {

    private final FamousSchoolService famousSchoolService;

    /**
     * 前台查询名师信息 对外接口,不需要拦截
     *
     * @return R
     */
     //@Inner是对内部调用公开,拦截外部调用  @Inner(value = false)是对外部暴露,两者都会舍弃token鉴权,如果代码中需要用到token,建议不要使用
    @Inner(value = false)  
    @ApiOperation(value = "前台分页查询", notes = "前台分页查询")
    @ApiImplicitParams(value = {@ApiImplicitParam(name = "size", value = "每页数据量,填int最大值", required = true),
        @ApiImplicitParam(name = "searchCondition", value = "查询条件", required = true),
        @ApiImplicitParam(name = "orgId", value = "组织id", required = true)})
    @GetMapping("/page/fore")
    public R<IPage<FamousTeacherVO>> getFamousSchoolPageForReception(Page page, SearchCondition searchCondition) {
        String orgId = WebUtils.getHeader(SecurityConstants.DETAILS_ORG_ID);
        searchCondition.setOrgId((StrUtil.isNotEmpty(orgId) ? Long.valueOf(orgId) : OrgEnum.CUSTOMER.getId()));
        IPage pageFamousTeacherVO = famousSchoolService.getFamousSchoolPage(page, searchCondition);
        return R.ok(pageFamousTeacherVO);
    }

    /**
     * 分页查询
     *
     * @param page            分页对象
     * @param searchCondition 查询条件
     * @return r
     */
    @ApiOperation(value = "分页查询")
    @ApiImplicitParams(value = {@ApiImplicitParam(name = "size", value = "每页数据量,填int最大值", required = true),
        @ApiImplicitParam(name = "searchCondition", value = "查询条件", required = true),
        @ApiImplicitParam(name = "orgId", value = "组织id", required = true)})
    @GetMapping("/page")
    public R<IPage<FamousSchoolVO>> getFamousSchoolPage(Page page, SearchCondition searchCondition) {
        IPage pageFamousTeacherVO = famousSchoolService.getFamousSchoolPage(page, searchCondition);
        return R.ok(pageFamousTeacherVO);
    }

    /**
     * 新增名校
     *
     * @param famousSchoolDTO 名校
     * @return R
     */
    @ApiOperation(value = "新增名校", notes = "新增名校")
    @SysLog("新增名校")
    @PostMapping
    public R save(@RequestBody FamousSchoolDTO famousSchoolDTO) {
        famousSchoolDTO.setOrgId(SecurityUtils.getUser().getOrgId());
        return famousSchoolService.saveFamousSchool(famousSchoolDTO);
    }

    /**
     * 通过id删除名校
     *
     * @param fschoolId id
     * @return R
     */
    @ApiOperation(value = "通过fschoolId删除名校", notes = "通过fschoolId删除名校")
    @DeleteMapping("/{fschoolId}")
    public R removeById(@PathVariable Long fschoolId) {
        return famousSchoolService.removeFamousSchoolById(fschoolId);
    }

    /**
     * @param ids id数组
     * @return r
     */
    @ApiOperation(value = "通过ids删除名校", notes = "通过ids删除名校")
    @ApiImplicitParam(name = "ids", value = "id数组", required = true)
    @DeleteMapping
    public R removeByIdList(@RequestBody List<Long> ids) {
        boolean isSuccess = famousSchoolService.removeByIds(ids);
        if (isSuccess) {
            return R.ok();
        }
        return R.failed();
    }

    /**
     * 上移或下移
     *
     * @param fschoolId   名校id
     * @param operateType 操作类型
     * @return 是否成功
     */
    @ApiOperation(value = "上移或下移名校", notes = "名师id,操作类型:up、down")
    @ApiImplicitParams(value = {@ApiImplicitParam(name = "fschoolId", value = "名校id", required = true),
        @ApiImplicitParam(name = "operateType", value = "操作类型", required = true)})
    @PostMapping(value = "/sorted")
    public R sortedFamousTeacher(@RequestParam Long fschoolId, @RequestParam String operateType) {

        if (Objects.isNull(OperateTypeEnum.getType(operateType))) {
            return R.failed("操作类型未知");
        }

        FamousSchool famousSchool = this.famousSchoolService.getById(fschoolId);
        if (Objects.isNull(famousSchool)) {
            return R.failed("未找到对应的轮播图");
        }

        if (OperateTypeEnum.UP.getType().equals(operateType) && famousSchool.getSort() - 1 < 0) {
            // 如果上移的sort值小于0,则不操作
            return R.failed("非法操作");
        }

        if (OperateTypeEnum.DOWN.getType().equals(operateType)) {
            // 如果在最后一位,则无法下移
            int count = this.famousSchoolService.count(Wrappers.lambdaQuery(FamousSchool.class)
                .eq(FamousSchool::getOrgId, famousSchool.getOrgId()));
            if (famousSchool.getSort() + 1 >= count) {
                return R.failed("非法操作");
            }
        }
        return this.famousSchoolService.sortedFamousSchool(famousSchool, operateType);
    }


    /**
     * 移除名校
     *
     * @param updateOrgDTO 变更组织DTO
     * @return com.pig4cloud.pig.common.core.util.R 是否成功
     * @author Ben
     * @date 2021-12-13 17:04
     */
    @ApiOperation(value = "移除名校", notes = "upms远程调用使用", hidden = true)
    @PostMapping(value = "/removeFamousSchool")
    public R<Boolean> removeFamousSchool(@RequestBody UpdateOrgDTO updateOrgDTO) {
        return R.ok(this.famousSchoolService.removeFamousSchool(updateOrgDTO));
    }
}

主要看dockerfile文件:

FROM moxm/java:1.8-full as builder
WORKDIR /build
ARG JAR_FILE=target/mc-cms-biz.jar
COPY ${JAR_FILE} app.jar
RUN java -Djarmode=layertools -jar app.jar extract && rm app.jar

FROM moxm/java:1.8-full
LABEL maintainer="pig4cloud@qq.com"
ENV TZ=Asia/Shanghai JAVA_OPTS="-Xms512m -Xmx1024m -Djava.security.egd=file:/dev/./urandom"
WORKDIR mc-cms-biz

COPY --from=builder /build/dependencies/ ./
COPY --from=builder /build/snapshot-dependencies/ ./
COPY --from=builder /build/spring-boot-loader/ ./
COPY --from=builder /build/application/ ./

EXPOSE 7001

CMD sleep 60; java $JAVA_OPTS org.springframework.boot.loader.JarLauncher

配置学习链接

2.mc-file模块分析

package com.hst.mc.elfinder.command;

import com.hst.mc.elfinder.service.ElfinderStorage;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AbortCommand extends AbstractCommand implements ElfinderCommand {
    @Override
    public void execute(ElfinderStorage elfinderStorage, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        response.sendError(204, "No contents!");
    }
}

/*
 * #%L
 * %%
 * Copyright (C) 2015 Trustsystems Desenvolvimento de Sistemas, LTDA.
 * %%
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 * 
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 * 
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 * 
 * 3. Neither the name of the Trustsystems Desenvolvimento de Sistemas, LTDA. nor the names of its contributors
 *    may be used to endorse or promote products derived from this software without
 *    specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 * #L%
 */

package com.hst.mc.elfinder.command;

import com.hst.mc.elfinder.ElFinderConstants;
import com.hst.mc.elfinder.core.ElfinderContext;
import com.hst.mc.elfinder.core.Target;
import com.hst.mc.elfinder.service.ElfinderStorage;
import com.hst.mc.elfinder.service.VolumeHandler;
import com.hst.mc.elfinder.support.archiver.ArchiverOption;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public abstract class AbstractCommand implements ElfinderCommand {

    // visible to subclasses
    protected final Logger logger = LoggerFactory.getLogger(getClass());

    private static final String CMD_TMB_TARGET = "?cmd=tmb&target=%s";
    private Map<String, Object> options = new HashMap<>();

    protected void addChildren(Map<String, VolumeHandler> map, VolumeHandler target) throws IOException {
        for (VolumeHandler f : target.listChildren()) {
            map.put(f.getHash(), f);
        }
    }

    protected void addSubFolders(Map<String, VolumeHandler> map, VolumeHandler target) throws IOException {
        for (VolumeHandler f : target.listChildren()) {
            if (f.isFolder()) {
                map.put(f.getHash(), f);
            }
        }
    }

    @Override
    public void execute(ElfinderContext context) throws Exception {
        ElfinderStorage elfinderStorage = context.getVolumeSourceFactory().getVolumeSource();
        execute(elfinderStorage, context.getRequest(), context.getResponse());
    }

    public abstract void execute(ElfinderStorage elfinderStorage, HttpServletRequest request,
            HttpServletResponse response) throws Exception;

    protected List<Map<String, Object>> buildJsonFilesArray(HttpServletRequest request,
            Collection<VolumeHandler> list) {

        ExecutorService executor = Executors.newCachedThreadPool();
        CountDownLatch latch = new CountDownLatch(list.size());
        List<Map<String, Object>> jsonFileList = new ArrayList<>();

        for (VolumeHandler itemHandler : list) {
            executor.execute(new Task(jsonFileList, request, itemHandler, latch));
        }

        try {
            latch.await();
            executor.shutdown();
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }

        return jsonFileList;
    }

    protected List<Map<String, Object>> buildJsonFilesArray(HttpServletRequest request, Collection<VolumeHandler> list,
            VolumeHandler parentTarget) {

        ExecutorService executor = Executors.newCachedThreadPool();
        CountDownLatch latch = new CountDownLatch(list.size());
        List<Map<String, Object>> jsonFileList = new ArrayList<>();

        for (VolumeHandler itemHandler : list) {
            executor.execute(new Task(jsonFileList, request, itemHandler, latch, parentTarget));
        }

        try {
            latch.await();
            executor.shutdown();
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }

        return jsonFileList;
    }

    protected VolumeHandler findCwd(ElfinderStorage elfinderStorage, String target) {
        VolumeHandler cwd = null;
        if (target != null) {
            cwd = findTarget(elfinderStorage, target);
        }

        if (cwd == null) {
            cwd = new VolumeHandler(elfinderStorage.getVolumes().get(0).getRoot(), elfinderStorage);
        }

        return cwd;
    }

    protected VolumeHandler findTarget(ElfinderStorage elfinderStorage, String hash) {
        Target target = elfinderStorage.fromHash(hash);
        if (target == null) {
            return null;
        }
        return new VolumeHandler(target, elfinderStorage);
    }

    protected List<Target> findTargets(ElfinderStorage elfinderStorage, String[] targetHashes) {
        if (elfinderStorage != null && targetHashes != null) {
            List<Target> targets = new ArrayList<>(targetHashes.length);
            for (String targetHash : targetHashes) {
                Target target = elfinderStorage.fromHash(targetHash);
                if (target != null) {
                    targets.add(target);
                }
            }
            return targets;
        }
        return Collections.emptyList();
    }

    protected Map<String, Object> getTargetInfo(final HttpServletRequest request, final VolumeHandler target)
            throws IOException {
        Map<String, Object> info = new HashMap<>();

        info.put(ElFinderConstants.ELFINDER_PARAMETER_URL, target.getExternalUrl());
        info.put(ElFinderConstants.ELFINDER_PARAMETER_CSS_CLASS, target.getCsscls());

        info.put(ElFinderConstants.ELFINDER_PARAMETER_HASH, target.getHash());
        info.put(ElFinderConstants.ELFINDER_PARAMETER_MIME, target.getMimeType());
        info.put(ElFinderConstants.ELFINDER_PARAMETER_TIMESTAMP, target.getLastModified());
        info.put(ElFinderConstants.ELFINDER_PARAMETER_SIZE, target.getSize());
        info.put(ElFinderConstants.ELFINDER_PARAMETER_READ,
                target.isReadable() ? ElFinderConstants.ELFINDER_TRUE_RESPONSE
                        : ElFinderConstants.ELFINDER_FALSE_RESPONSE);
        info.put(ElFinderConstants.ELFINDER_PARAMETER_WRITE,
                target.isWritable() ? ElFinderConstants.ELFINDER_TRUE_RESPONSE
                        : ElFinderConstants.ELFINDER_FALSE_RESPONSE);
        info.put(ElFinderConstants.ELFINDER_PARAMETER_LOCKED,
                target.isLocked() ? ElFinderConstants.ELFINDER_TRUE_RESPONSE
                        : ElFinderConstants.ELFINDER_FALSE_RESPONSE);

        if (target.getMimeType() != null && target.getMimeType().startsWith("image")) {
            StringBuffer qs = request.getRequestURL();
            info.put(ElFinderConstants.ELFINDER_PARAMETER_THUMBNAIL,
                    qs.append(String.format(CMD_TMB_TARGET, target.getHash())));
        } else if (target.getMimeType() != null && target.getMimeType().contains("zip")) {
            info.put(ElFinderConstants.ELFINDER_PARAMETER_ARCHIVERS_KEY, target.getHash());
        }

        if (target.isRoot()) {
            info.put(ElFinderConstants.ELFINDER_PARAMETER_DIRECTORY_FILE_NAME, target.getVolumeAlias());
            info.put(ElFinderConstants.ELFINDER_PARAMETER_VOLUME_ID, target.getVolumeId());
        } else {
            info.put(ElFinderConstants.ELFINDER_PARAMETER_DIRECTORY_FILE_NAME, target.getName());
            info.put(ElFinderConstants.ELFINDER_PARAMETER_PARENTHASH, target.getParent().getHash());
        }

        if (target.isFolder()) {
            info.put(ElFinderConstants.ELFINDER_PARAMETER_HAS_DIR,
                    target.hasChildFolder() ? ElFinderConstants.ELFINDER_TRUE_RESPONSE
                            : ElFinderConstants.ELFINDER_FALSE_RESPONSE);
        }
        return info;
    }

    /**
     * 带父节点
     * 
     * @param request      请求参数
     * @param target       当前节点
     * @param parentTarget 父节点
     * @return 返回json
     * @throws IOException 异常
     */
    protected Map<String, Object> getTargetInfo(final HttpServletRequest request, final VolumeHandler target,
            final VolumeHandler parentTarget) throws IOException {
        Map<String, Object> info = new HashMap<>();

        info.put(ElFinderConstants.ELFINDER_PARAMETER_URL, target.getExternalUrl());
        info.put(ElFinderConstants.ELFINDER_PARAMETER_CSS_CLASS, target.getCsscls());

        info.put(ElFinderConstants.ELFINDER_PARAMETER_HASH, target.getHash());
        info.put(ElFinderConstants.ELFINDER_PARAMETER_MIME, target.getMimeType());
        info.put(ElFinderConstants.ELFINDER_PARAMETER_TIMESTAMP, target.getLastModified());
        info.put(ElFinderConstants.ELFINDER_PARAMETER_SIZE, target.getSize());
        info.put(ElFinderConstants.ELFINDER_PARAMETER_READ,
                target.isReadable() ? ElFinderConstants.ELFINDER_TRUE_RESPONSE
                        : ElFinderConstants.ELFINDER_FALSE_RESPONSE);
        info.put(ElFinderConstants.ELFINDER_PARAMETER_WRITE,
                target.isWritable() ? ElFinderConstants.ELFINDER_TRUE_RESPONSE
                        : ElFinderConstants.ELFINDER_FALSE_RESPONSE);
        info.put(ElFinderConstants.ELFINDER_PARAMETER_LOCKED,
                target.isLocked() ? ElFinderConstants.ELFINDER_TRUE_RESPONSE
                        : ElFinderConstants.ELFINDER_FALSE_RESPONSE);

        if (target.getMimeType() != null && target.getMimeType().startsWith("image")) {
            StringBuffer qs = request.getRequestURL();
            info.put(ElFinderConstants.ELFINDER_PARAMETER_THUMBNAIL,
                    qs.append(String.format(CMD_TMB_TARGET, target.getHash())));
        } else if (target.getMimeType() != null && target.getMimeType().contains("zip")) {
            info.put(ElFinderConstants.ELFINDER_PARAMETER_ARCHIVERS_KEY, target.getHash());
        }

        if (target.isRoot()) {
            info.put(ElFinderConstants.ELFINDER_PARAMETER_DIRECTORY_FILE_NAME, target.getVolumeAlias());
            info.put(ElFinderConstants.ELFINDER_PARAMETER_VOLUME_ID, target.getVolumeId());
        } else {
            info.put(ElFinderConstants.ELFINDER_PARAMETER_DIRECTORY_FILE_NAME, target.getName());
            info.put(ElFinderConstants.ELFINDER_PARAMETER_PARENTHASH, parentTarget.getHash());
        }

        if (target.isFolder()) {
            info.put(ElFinderConstants.ELFINDER_PARAMETER_HAS_DIR,
                    target.hasChildFolder() ? ElFinderConstants.ELFINDER_TRUE_RESPONSE
                            : ElFinderConstants.ELFINDER_FALSE_RESPONSE);
        }
        return info;
    }

    protected Map<String, Object> getOptions(VolumeHandler cwd) {
        options.put(ElFinderConstants.ELFINDER_PARAMETER_PATH, cwd.getName());
        options.put(ElFinderConstants.ELFINDER_PARAMETER_COMMAND_DISABLED, cwd.getDisabledCmds());
        options.put(ElFinderConstants.ELFINDER_PARAMETER_FILE_SEPARATOR,
                ElFinderConstants.ELFINDER_PARAMETER_FILE_SEPARATOR);
        options.put(ElFinderConstants.ELFINDER_PARAMETER_OVERWRITE_FILE, ElFinderConstants.ELFINDER_TRUE_RESPONSE);
        options.put(ElFinderConstants.ELFINDER_PARAMETER_ARCHIVERS, ArchiverOption.JSON_INSTANCE);
        return options;
    }

    class Task implements Runnable {

        private HttpServletRequest request;

        private VolumeHandler itemHandler;

        private List<Map<String, Object>> jsonFileList;

        private CountDownLatch downLatch;

        private VolumeHandler parentTarget;

        public Task(List<Map<String, Object>> jsonFileList, HttpServletRequest request, VolumeHandler itemHandler,
                CountDownLatch downLatch) {
            this.jsonFileList = jsonFileList;
            this.request = request;
            this.itemHandler = itemHandler;
            this.downLatch = downLatch;
        }

        public Task(List<Map<String, Object>> jsonFileList, HttpServletRequest request, VolumeHandler itemHandler,
                CountDownLatch downLatch, VolumeHandler parentTarget) {
            this.jsonFileList = jsonFileList;
            this.request = request;
            this.itemHandler = itemHandler;
            this.downLatch = downLatch;
            this.parentTarget = parentTarget;
        }

        @Override
        public void run() {
            try {
                jsonFileList.add(getTargetInfo(request, itemHandler));
                downLatch.countDown();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}
/*
 * #%L
 * %%
 * Copyright (C) 2015 Trustsystems Desenvolvimento de Sistemas, LTDA.
 * %%
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 * 
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 * 
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 * 
 * 3. Neither the name of the Trustsystems Desenvolvimento de Sistemas, LTDA. nor the names of its contributors
 *    may be used to endorse or promote products derived from this software without
 *    specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 * #L%
 */

package com.hst.mc.elfinder.command;

import com.hst.mc.elfinder.core.ElfinderContext;

public interface ElfinderCommand {

    void execute(ElfinderContext context) throws Exception;

}

实际就是我们一个类继承另一个类并实现一个接口。

3.mc-file-biz模块分析

@Configuration的多种使用用途:

赋值过程:

package com.hst.mc.file.biz.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

@Data
@Configuration
@ConfigurationProperties(prefix = "storage.aliyun")
public class AliyunStorageConfig {

    /**
     * Endpoint名称
     */
    private String endpoint;

    /**
     * AccessKey
     */
    private String accessKeyId;

    /**
     * Access密钥
     */
    private String accessKeySecret;


    /**
     * bucket名称
     */
    private String bucketName;

}

application-aliyun.yml配置:

storage:
  aliyun:
    endpoint: oss-cn-shenzhen.aliyuncs.com
    accessKeyId: LTAI5tCdSb7agmBTWE6UXBi5
    accessKeySecret: NKzk0JFkJWnAXz9Yd4p7kG3ny0XSA5
    bucketName: rtw-001
  

初始化配置类:

package com.hst.mc.file.biz.config;

import com.hst.mc.elfinder.ElFinderConstants;
import com.hst.mc.elfinder.command.CommandFactory;
import com.hst.mc.elfinder.core.Volume;
import com.hst.mc.elfinder.core.VolumeSecurity;
import com.hst.mc.elfinder.core.impl.DefaultVolumeSecurity;
import com.hst.mc.elfinder.core.impl.SecurityConstraint;
import com.hst.mc.elfinder.param.Node;
import com.hst.mc.elfinder.service.ElfinderStorage;
import com.hst.mc.elfinder.service.ElfinderStorageFactory;
import com.hst.mc.elfinder.service.VolumeSources;
import com.hst.mc.elfinder.service.impl.DefaultElfinderStorage;
import com.hst.mc.elfinder.service.impl.DefaultElfinderStorageFactory;
import com.hst.mc.elfinder.service.impl.DefaultThumbnailWidth;
import com.hst.mc.elfinder.support.locale.LocaleUtils;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.unit.DataSize;
import org.springframework.util.unit.DataUnit;

import javax.servlet.MultipartConfigElement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

@Configuration
public class ElFinderConfig {

    // @Autowired
    // private ElfinderConfiguration elfinderConfiguration;

    /**
     * 实例化命令工厂
     * 
     * @return 命令工厂
     */
    @Bean(name = "commandFactory")
    public CommandFactory getCommandFactory() {
        CommandFactory commandFactory = new CommandFactory();
        commandFactory.setClassNamePattern("com.hst.mc.elfinder.command.%sCommand");
        return commandFactory;
    }

    /**
     * 设置文件上传大小
     * 
     * @return 文件配置
     */
    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        // 单个文件最大
        factory.setMaxFileSize(DataSize.of(5L, DataUnit.GIGABYTES)); // KB,MB
        /// 设置总上传数据总大小
        factory.setMaxRequestSize(DataSize.of(5L, DataUnit.GIGABYTES));
        return factory.createMultipartConfig();
    }

    /**
     * 
     * @param elfinderConfiguration 配置
     * @return 配置工厂
     */
    @Bean(name = "elfinderStorageFactory")
    public ElfinderStorageFactory getElfinderStorageFactory(ElfinderConfiguration elfinderConfiguration) {
        DefaultElfinderStorageFactory elfinderStorageFactory = new DefaultElfinderStorageFactory();
        elfinderStorageFactory.setElfinderStorage(getElfinderStorage(elfinderConfiguration));
        return elfinderStorageFactory;
    }

    /**
     * 获取配置
     * 
     * @param elfinderConfiguration 配置
     * @return 某个配置
     */
    @Bean(name = "elfinderStorage")
    public ElfinderStorage getElfinderStorage(ElfinderConfiguration elfinderConfiguration) {

        DefaultElfinderStorage defaultElfinderStorage = new DefaultElfinderStorage();

        // creates thumbnail
        DefaultThumbnailWidth defaultThumbnailWidth = new DefaultThumbnailWidth();
        defaultThumbnailWidth.setThumbnailWidth(elfinderConfiguration.getThumbnail().getWidth().intValue());

        // creates volumes, volumeIds, volumeLocale and volumeSecurities
        Character defaultVolumeId = 'A';
        List<Node> elfinderConfigurationVolumes = elfinderConfiguration.getVolumes();
        List<Volume> elfinderVolumes = new ArrayList<>(elfinderConfigurationVolumes.size());
        Map<Volume, String> elfinderVolumeIds = new HashMap<>(elfinderConfigurationVolumes.size());
        Map<Volume, Locale> elfinderVolumeLocales = new HashMap<>(elfinderConfigurationVolumes.size());
        List<VolumeSecurity> elfinderVolumeSecurities = new ArrayList<>();

        // creates volumes
        for (Node elfinderConfigurationVolume : elfinderConfigurationVolumes) {

            final String alias = elfinderConfigurationVolume.getAlias();
            final String path = elfinderConfigurationVolume.getPath();
            final String source = elfinderConfigurationVolume.getSource();
            final String locale = elfinderConfigurationVolume.getLocale();
            final boolean isLocked = elfinderConfigurationVolume.getConstraint().isLocked();
            final boolean isReadable = elfinderConfigurationVolume.getConstraint().isReadable();
            final boolean isWritable = elfinderConfigurationVolume.getConstraint().isWritable();

            // creates new volume
            Volume volume = VolumeSources.of(source).newInstance(alias, path, elfinderConfigurationVolume);

            elfinderVolumes.add(volume);
            elfinderVolumeIds.put(volume, Character.toString(defaultVolumeId));
            elfinderVolumeLocales.put(volume, LocaleUtils.toLocale(locale));

            // creates security constraint
            SecurityConstraint securityConstraint = new SecurityConstraint();
            securityConstraint.setLocked(isLocked);
            securityConstraint.setReadable(isReadable);
            securityConstraint.setWritable(isWritable);

            // creates volume pattern and volume security
            final String volumePattern = Character.toString(defaultVolumeId)
                    + ElFinderConstants.ELFINDER_VOLUME_SERCURITY_REGEX;
            elfinderVolumeSecurities.add(new DefaultVolumeSecurity(volumePattern, securityConstraint));

            // prepare next volumeId character
            defaultVolumeId++;
        }

        defaultElfinderStorage.setThumbnailWidth(defaultThumbnailWidth);
        defaultElfinderStorage.setVolumes(elfinderVolumes);
        defaultElfinderStorage.setVolumeIds(elfinderVolumeIds);
        defaultElfinderStorage.setVolumeLocales(elfinderVolumeLocales);
        defaultElfinderStorage.setVolumeSecurities(elfinderVolumeSecurities);

        return defaultElfinderStorage;
    }

}

初始化一个分页插件:

package com.hst.mc.file.biz.config;//package com.hst.mc.oss.config;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;

@Configuration
@MapperScan("com.hst.mc.oss.dao")
public class MybatisPlusConfig {

    /**
     * 分页插件
     * 
     * @return 分页拦截器
     */
    @Bean
    public MybatisPlusInterceptor paginationInterceptor() {
        return new MybatisPlusInterceptor();
    }
}

枚举的定义:

package com.hst.mc.file.biz.enums;

import lombok.AllArgsConstructor;
import lombok.Getter;

@Getter
@AllArgsConstructor
public enum FileTypeDirEnum {

    DOC("docs", "文档"), VIDEO("videos", "视频"), IMAGE("images", "图像");

    private final String type;

    private final String desc;

}

拦截器做的处理,对请求路径做处理:

package com.hst.mc.file.biz.interceptor;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hst.mc.file.api.constant.Constants;
import com.hst.mc.file.api.entity.StorageInfo;
import com.hst.mc.file.biz.config.OssConfig;
import com.hst.mc.file.biz.vo.ReturnVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

/**
 * key校验拦截器
 *
 * @author Ben
 */
@Slf4j
public class CheckKeyInterceptor implements HandlerInterceptor {

    @Resource
    private OssConfig ossConfig;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        try {
            String requestUrl = request.getRequestURI();
            log.info("请求url:{}", requestUrl);

            String userAgent = CharSequenceUtil.isNotBlank(request.getHeader("user-agent"))
                    ? request.getHeader("user-agent").toLowerCase()
                    : "";
            log.info("请求userAgent:{}", userAgent);

            // allowUrls 全部放行
            for (String urlStr : ossConfig.getAllowUrls()) {
                if (requestUrl.contains(urlStr)) {
                    return true;
                }
            }

            // 存储方式
            String mode = ossConfig.getMode();
            if (CharSequenceUtil.isBlank(mode)) {
                log.error("invalid config for storage mode!!!");
                return false;
            }

            // 获取请求参数Data
            String uniqueIdentifier = request.getParameter("uniqueIdentifier");
            String resBucket = request.getParameter("resBucket");
            String filePath = request.getParameter("filePath");
            String fileId = request.getParameter("fileId");
            if (CharSequenceUtil.hasBlank(filePath)) {
                outPutClient(JSON.toJSONString(new ReturnVo(Constants.FAIL, "缺少必要参数")), response);
                return false;
            }
            StorageInfo storageInfo = new StorageInfo();
            storageInfo.setMode(ossConfig.getMode());
            storageInfo.setUniqueIdentifier(uniqueIdentifier);
            storageInfo.setBucketName(resBucket);
            storageInfo.setFilePath(filePath);
            storageInfo.setFileId(fileId);
            request.setAttribute("storageInfo", storageInfo);

            return true;
        } catch (Exception ex) {
            log.error("校验key出错:", ex);
        }

        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {}

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {}

    private void outPutClient(String jsonStr, HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.write(jsonStr);
        out.flush();
        out.close();
    }

    private String getRequestData(HttpServletRequest request) {
        try (BufferedReader bf = new BufferedReader(new InputStreamReader(request.getInputStream()));) {
            StringBuilder sb = new StringBuilder();
            char[] cbs = new char[1024];
            int len;
            while ((len = bf.read(cbs, 0, cbs.length)) != -1) {
                sb.append(cbs, 0, len);
            }
            return sb.toString();
        } catch (Exception ex) {
            log.error("获取请求流错误:", ex);
        }
        return StrUtil.EMPTY;
    }

    public static void main(String[] args) {
        JSONObject reqData = JSON.parseObject("{\"aa\":\"11\"}");
        System.out.println(reqData);
    }

}

总的拦截器(可以控制分拦截器):

package com.hst.mc.file.biz.interceptor;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 拦截器 Config
 * 
 * @author Ben
 *
 */
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

    /**
     * 添加拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(getCheckKeyInterceptor()).addPathPatterns("/**");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    @Bean
    public CheckKeyInterceptor getCheckKeyInterceptor() {
        return new CheckKeyInterceptor();
    }
}

有多个application.yml文件,怎么全部配置进来:
在这里插入图片描述
首先项目启动顶级访问bootstrap.yml,然后访问application.yml,在application.yml里面引:

server:
  servlet:
    encoding:
      charset: utf-8
      force: true
      enabled: true
  tomcat:
    connection-timeout: -1
    accept-count: 1024
    threads:
      min-spare: 256
      max: 4096
spring:
  profiles:
    include: oss,local,ftp,aliyun   //这个地方引入其他配置

  #datasource:
    # 当前数据源操作类型
    #type: com.alibaba.druid.pool.DruidDataSource
    # mysql驱动类
    #driver-class-name: com.mysql.cj.jdbc.Driver
    # 如果是Mysql5.7+,建议加上url的指定
    #url: jdbc:mysql://127.0.0.1:3306/mc?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8
    #username: root
    #password: linux

  freemarker: 
    suffix: .html
    request-context-attribute: request
  mvc:
   static-path-pattern: /static/**

file:
  local:
    limitSize: 50
  paas:
    limitSize: 2047

linux:
 nginx-location: /opt/fsmeeting/docker/mc-file-nginx.conf
 network-interface-location: /etc/network/interfaces
 netplan-location: /etc/netplan/01-netcfg.yaml


bootstrap.yml:

server:
  port: 8886

spring:
  application:
    name: '@artifactId@'
  cloud:
    nacos:
      discovery:
        server-addr: ${NACOS-HOST:pig-register}:${NACOS-PORT:8848}
      config:
        server-addr: ${spring.cloud.nacos.discovery.server-addr}
        file-extension: yml
        shared-configs:
          -
            data-id: application-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}
            refresh: true
  profiles:
    active: '@profiles.active@'

logback-spring.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ /*
  ~  *  Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com).
  ~  *  <p>
  ~  *  Licensed under the GNU Lesser General Public License 3.0 (the "License");
  ~  *  you may not use this file except in compliance with the License.
  ~  *  You may obtain a copy of the License at
  ~  *  <p>
  ~  * https://www.gnu.org/licenses/lgpl.html
  ~  *  <p>
  ~  * Unless required by applicable law or agreed to in writing, software
  ~  * distributed under the License is distributed on an "AS IS" BASIS,
  ~  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~  * See the License for the specific language governing permissions and
  ~  * limitations under the License.
  ~  */
  -->

<configuration debug="false" scan="false">
	<springProperty scop="context" name="spring.application.name" source="spring.application.name" defaultValue=""/>
	<property name="log.path" value="logs/${spring.application.name}"/>
	<!-- 彩色日志格式 -->
	<property name="CONSOLE_LOG_PATTERN"
			  value="${CONSOLE_LOG_PATTERN:-%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m${LOG_EXCEPTION_CONVERSION_WORD:-%wEx} -- %file:%line %n}"/>
	<!-- 彩色日志依赖的渲染类 -->
	<conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter"/>
	<conversionRule conversionWord="wex"
					converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter"/>
	<conversionRule conversionWord="wEx"
					converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter"/>
	<!-- Console log output -->
	<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
		<encoder>
			<pattern>${CONSOLE_LOG_PATTERN}</pattern>
		</encoder>
	</appender>

	<!-- Log file debug output -->
	<appender name="debug" class="ch.qos.logback.core.rolling.RollingFileAppender">
		<file>${log.path}/debug.log</file>
		<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
			<fileNamePattern>${log.path}/%d{yyyy-MM, aux}/debug.%d{yyyy-MM-dd}.%i.log.gz</fileNamePattern>
			<maxFileSize>50MB</maxFileSize>
			<maxHistory>30</maxHistory>
		</rollingPolicy>
		<encoder>
			<pattern>${CONSOLE_LOG_PATTERN}</pattern>
		</encoder>
	</appender>

	<!-- Log file error output -->
	<appender name="error" class="ch.qos.logback.core.rolling.RollingFileAppender">
		<file>${log.path}/error.log</file>
		<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
			<fileNamePattern>${log.path}/%d{yyyy-MM}/error.%d{yyyy-MM-dd}.%i.log.gz</fileNamePattern>
			<maxFileSize>50MB</maxFileSize>
			<maxHistory>30</maxHistory>
		</rollingPolicy>
		<encoder>
			<pattern>${CONSOLE_LOG_PATTERN}</pattern>
		</encoder>
		<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
			<level>ERROR</level>
		</filter>
	</appender>

	<!--nacos 心跳 INFO 屏蔽-->
	<logger name="com.alibaba.nacos" level="OFF">
		<appender-ref ref="error"/>
	</logger>

	<!-- Level: FATAL 0  ERROR 3  WARN 4  INFO 6  DEBUG 7 -->
	<root level="INFO">
		<appender-ref ref="console"/>
		<appender-ref ref="debug"/>
		<appender-ref ref="error"/>
	</root>
</configuration>

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

bst@微胖子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值