1. 程式人生 > >【spring】【spring mvc】【spring boot】獲取spring cloud項目中所有spring mvc的請求資源

【spring】【spring mvc】【spring boot】獲取spring cloud項目中所有spring mvc的請求資源

sea ams other figure upd ring false 調用 tom

實現的方法:

1.在父級項目中 或者 每個微服務都引用的項目中添加實體類Resource

2.在父級項目中 或者 每個為服務都引用的項目中寫一個工具類,作用是用來獲取請求資源

3.在每一個微服務的啟動類添加註解@RestController ,並且寫一個請求方法調用 工具類的請求資源的方法

4.將獲取到的JSON字符串 保存在文件中

5.最後,在需要存儲這些信息到數據庫中的對應微服務 提供一個請求方法,參數就傳遞這一個一個的JSON字符串,而請求方法做的事情就是解析JSON,並批量保存到對應數據表中

1.先提供一個狀態這些結果的實體Resource.java

技術分享圖片
package com.pisen.cloud.luna.core.utils.beans;




public class Resource { public static final Integer GET_RESOURCE = 1; public static final Integer OTHER_RESOURCE = 2; public static final Integer ENABLE = 1;//啟用 public static final Integer DISENABLE = 0;//禁用 private String path;//資源URL private String name;//資源名 private String msName;//
資源所屬微服務 private Integer type;//資源類型 1代表數據資源 2代表功能資源 private Integer enable;//是否啟用 0 禁用 1 啟用 private String user;//資源被使用對象 private String remark;//資源備註 public String getPath() { return path; } public void setPath(String path) { this.path = path; } public
String getName() { return name; } public void setName(String name) { this.name = name; } public String getMsName() { return msName; } public void setMsName(String msName) { this.msName = msName; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public Resource(String path, String name, String msName, Integer type, String user, String remark,Integer enable) { this.path = path; this.name = name; this.msName = msName; this.type = type; this.user = user; this.remark = remark; this.enable = enable; } }
View Code

2.同樣在 所有微服務都能引用到的 地方 提供一個工具類MappingResourceUtil.java

技術分享圖片
package com.pisen.cloud.luna.core.utils;

import com.pisen.cloud.luna.core.utils.beans.Resource;
import com.pisen.cloud.luna.core.utils.beans.ResourceConfig;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition;
import org.springframework.web.servlet.mvc.condition.RequestMethodsRequestCondition;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class MappingResourceUtil {


    /**
     * 獲取本服務下 所有RequestMapping標記的資源信息
     * @param request
     * @param msName    需要傳入ms-name 微服務別名
     * @return
     */
    public static List<Resource> getMappingList(HttpServletRequest request,String msName){
        ServletContext servletContext = request.getSession().getServletContext();
        if (servletContext == null)
        {
            return null;
        }
        WebApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);

        //請求url和處理方法的映射
        List<Resource> requestToMethodItemList = new ArrayList<Resource>();
        //獲取所有的RequestMapping
        Map<String, HandlerMapping> allRequestMappings = BeanFactoryUtils.beansOfTypeIncludingAncestors(appContext,
                HandlerMapping.class, true, false);

        for (HandlerMapping handlerMapping : allRequestMappings.values())
        {
            //本項目只需要RequestMappingHandlerMapping中的URL映射
            if (handlerMapping instanceof RequestMappingHandlerMapping)
            {
                RequestMappingHandlerMapping requestMappingHandlerMapping = (RequestMappingHandlerMapping) handlerMapping;
                Map<RequestMappingInfo, HandlerMethod> handlerMethods = requestMappingHandlerMapping.getHandlerMethods();
                for (Map.Entry<RequestMappingInfo, HandlerMethod> requestMappingInfoHandlerMethodEntry : handlerMethods.entrySet())
                {
                    RequestMappingInfo requestMappingInfo = requestMappingInfoHandlerMethodEntry.getKey();
                    HandlerMethod mappingInfoValue = requestMappingInfoHandlerMethodEntry.getValue();

                    PatternsRequestCondition patternsCondition = requestMappingInfo.getPatternsCondition();
                    String requestUrl = patternsCondition.getPatterns() != null && patternsCondition.getPatterns().size()>0 ?
                            patternsCondition.getPatterns().stream().collect(Collectors.toList()).get(0).toString() : null;

                    RequestMethodsRequestCondition methodCondition = requestMappingInfo.getMethodsCondition();
                    String requestType = methodCondition.getMethods() != null && methodCondition.getMethods().size()>0 ?
                            methodCondition.getMethods().stream().collect(Collectors.toList()).get(0).toString() : null;

                    if (requestType == null){
                        continue;
                    }

                    String controllerName = mappingInfoValue.getBeanType().toString();
                    String requestMethodName = mappingInfoValue.getMethod().getName();
                    Class<?>[] methodParamTypes = mappingInfoValue.getMethod().getParameterTypes();

                    String name = getResourceName(requestType,requestMethodName);
                    Integer type = getType(requestType);
                    String path = msName+":"+requestUrl;
                    String user = getUser(requestUrl);
                    Integer enable = Resource.ENABLE;
                    Resource resource = new Resource(path,name,msName,type,user,null,enable);

                    requestToMethodItemList.add(resource);
                }
                break;
            }
        }

        return requestToMethodItemList;
    }

    /**
     * GET 代表數據資源 1
     * 其他 代表功能資源 2
     * @param type
     * @return
     */
    public static Integer getType(String type){
        return "GET".equals(type) ? Resource.GET_RESOURCE : Resource.OTHER_RESOURCE;
    }

    /**
     * 按照請求地址和請求方法 獲取資源名稱
     * @param requestType
     * @param requestMethodName
     * @return
     */
    public static String getResourceName(String requestType,String requestMethodName){
        requestMethodName = requestMethodName.toLowerCase();
        if ("GET".equals(requestType)){
            return ResourceConfig.GET+requestMethodName;
        }else{
            if (requestMethodName.contains("page")){
                return ResourceConfig.PAGE+requestMethodName;
            }
            if(requestMethodName.contains("list")){
                return ResourceConfig.GET+requestMethodName+ResourceConfig.LIST;
            }
            if (requestMethodName.contains("insert")){
                return ResourceConfig.INSERT+requestMethodName;
            }
            if (requestMethodName.contains("delete")){
                return ResourceConfig.DELETE+requestMethodName;
            }
            if (requestMethodName.contains("update")){
                return ResourceConfig.UPDATE+requestMethodName;
            }
            if (requestMethodName.contains("add")){
                return ResourceConfig.ADD+requestMethodName;
            }
            if (requestMethodName.contains("enable")){
                return ResourceConfig.ENABLE+requestMethodName;
            }
            if (requestMethodName.contains("init")){
                return ResourceConfig.INIT+requestMethodName;
            }
            if (requestMethodName.contains("verify")){
                return ResourceConfig.VERIFY+requestMethodName;
            }
            if (requestMethodName.contains("find")){
                return ResourceConfig.FIND+requestMethodName;
            }

            return requestMethodName;

        }
    }

    /**
     * 獲取資源使用者身份
     * @param requestUrl
     * @return
     */
    public static String getUser(String requestUrl){
        if (StringUtils.isNotBlank(requestUrl)){
            String[] pathArr = requestUrl.split("/");
            if (pathArr.length > 0 ){
                if ("ten".equals(pathArr[0])){
                    return ResourceConfig.USER_TEN;
                }
                if ("admin".equals(pathArr[0])) {
                    return ResourceConfig.USER_ADMIN;
                }
                if ("member".equals(pathArr[0])){
                    return ResourceConfig.USER_MEMBER;
                }
                if ("free".equals(pathArr[0])){
                    return ResourceConfig.USER_FREE;
                }
                if ("dealer".equals(pathArr[0])){
                    return ResourceConfig.USER_DEALER;
                }
            }
        }
        return "未知使用者";

    }

}
View Code

3.然後就可以在每一個微服務的啟動類上加註解,加下面這段代碼,然後啟動這個微服務,訪問就能拿到這個微服務下的所有請求資源 為一個JSON字符串了

舉個例子,我現在獲取這個微服務的所有請求資源:【紅色部分就是 任意粘貼到每一個啟動類的代碼】【紫色部分就是需要更改的每一個不同微服務的不同服務名】

package pisen.cloud.luna.ms.account;

import com.alibaba.fastjson.JSON;
import com.pisen.cloud.luna.core.result.AjaxResult;
import com.pisen.cloud.luna.core.utils.MappingResourceUtil;

import com.pisen.cloud.luna.core.utils.beans.Resource;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


@EnableDiscoveryClient
@SpringBootApplication
@EnableFeignClients
@EnableTransactionManagement // 啟註解事務管理,等同於xml配置方式的
@RestController
public class PisenLunaMSAccountApp {
    
    public static void main(String[] args) {
//        String str = MappingResourceUtil.getMappingList(PisenLunaMSAccountApp.class);

        SpringApplication.run(PisenLunaMSAccountApp.class, args);
    }

    @RequestMapping("/test/index")
    public AjaxResult<String> getAccout(HttpServletRequest request){
        AjaxResult<String> result = new AjaxResult<>();
        List<Resource> list = MappingResourceUtil.getMappingList(request,"ms-account");

        String account = JSON.toJSONString(list);

        result.initTrue(account);
        return result;
    }
}

然後啟動本微服務後,postman請求即可:

技術分享圖片

4.將請求到的 JSON字符串,保存下來一會用

技術分享圖片

5.最後,在想要將這些JSON字符串轉化為數據庫數據的微服務中,提供一個批量插入的方法,然後將JSON字符串當作參數傳入即可

@RequestMapping("batchInsert2")
    public AjaxResult<List<Resource>> batchInsert2(@RequestBody String  json) {
        AdminUser adminUser = RequestData.ADMIN_USER.get();
        String adminUid = adminUser.getUid();
        AjaxResult<List<Resource>> res = new AjaxResult<>();
        List<Resource> list = JSONArray.parseArray(json,Resource.class);
        for (Resource resource : list) {
            resource.setCreateId(adminUid);
        }
        service.batchInsert(list);
        res.initTrue(list);
        return res;
    }

批量插入方法 使用JPA的save()即可,使用mybatis的批量插入也可以

技術分享圖片

完成!!!!!!!

【spring】【spring mvc】【spring boot】獲取spring cloud項目中所有spring mvc的請求資源