xff-is-a-cool-guy 5 gadi atpakaļ
revīzija
e4e9beb6c3

+ 57 - 0
compare/ConversionNum.java

@@ -0,0 +1,57 @@
+
+package com.zkh360.api.brand.util;
+
+import com.zkh360.api.brand.dto.BrandInfoResult;
+import org.apache.commons.lang.StringUtils;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+
+public class ConversionNum {
+
+    public static List<BrandInfoResult> getCollectionsResult(List<BrandInfoResult> brands){
+
+        Comparator<BrandInfoResult> brandComparator = new Comparator<BrandInfoResult>() {
+            @Override
+            public int compare(BrandInfoResult o1, BrandInfoResult o2) {
+                if (o1 == o2) {
+                    return 0;
+                }
+                String firstWord1 = o1.getFirstWord();
+                String firstWord2 = o2.getFirstWord();
+
+                String brandName1 = o1.getBrandName();
+                String brandName2 = o2.getBrandName();
+
+                int result = stringCompare(firstWord1, firstWord2);
+
+                if (result == 0) {
+                    return stringCompare(brandName1, brandName2);
+                } else {
+                    return result;
+                }
+            }
+        };
+        Collections.sort(brands, brandComparator);
+        return brands;
+    }
+
+    public static int stringCompare(String str1, String str2) {
+        if (str1 == str2) {
+            return 0;
+        }
+
+        if (str1 == null && str2 != null) {
+            return -1;
+        }
+
+        if (str1 != null && str2 == null) {
+            return 1;
+        }
+
+        return str1.compareTo(str2);
+    }
+
+}

+ 116 - 0
filter/SessionFilter.java

@@ -0,0 +1,116 @@
+package com.zkh360.api.user.filter;
+
+import com.zkh360.core.util.redis.RedisService;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+
+import javax.servlet.*;
+import javax.servlet.annotation.WebFilter;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+import java.io.IOException;
+
+@WebFilter(filterName = "SessionFilter",urlPatterns = {"/*"})
+public class SessionFilter implements Filter {
+
+    @Autowired
+    private RedisService redisService;
+
+    //标示符:表示当前用户未登录(可根据自己项目需要改为json样式)
+    String LOGIN_EXPIRED = "{\"stateCode\":\"1002\",\"message\":\"用户信息失效\"}";
+
+    //必须要登陆后才可以访问的接口
+    String[] includeUrls = new String[]{
+            "/h5/shoppingCart",
+            "/h5/order",
+            "/h5/shoppingCart/add",
+            "/h5/shoppingCart/delete",
+            "/h5/shoppingCart/update",
+            "/h5/shoppingCart/inquiry",
+            "/h5/inquiry",
+            "h5/list",
+            "/h5/invoice",
+            "/h5/ReceiveAddress",
+            "/h5/logistics",
+            "/h5/password/update",
+            "/h5/userinfo",
+            "token"
+    };
+
+
+    @Override
+    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
+        HttpServletRequest request = (HttpServletRequest) servletRequest;
+        HttpServletResponse response = (HttpServletResponse) servletResponse;
+        HttpSession session = request.getSession(false);
+        ServletContext servletContext = request.getServletContext();
+        //获取请求的token
+        String requestAuthorization = request.getHeader("Authorization");
+        String method = request.getMethod();
+
+        String uri = request.getRequestURI();
+        if(isNeedAuthorization(uri) && !"options".equalsIgnoreCase(request.getMethod())){
+            if(StringUtils.isBlank(requestAuthorization)){
+                // Authorization不存在,返回登陆过期
+                setResponseParam(response);
+                return;
+            }
+        }
+
+        if(StringUtils.isBlank(requestAuthorization)){
+            // 未登录过 发票ID为null
+            filterChain.doFilter(servletRequest, servletResponse);
+            return;
+        }
+        //获取与token绑定的invoiceId
+        if (!redisService.exists(requestAuthorization)){
+            // Authorization不存在,返回登陆过期
+            setResponseParam(response);
+            return;
+        }
+        String invoiceIdValue = redisService.get(requestAuthorization).toString();
+        //验证invoceId是否可用
+        if(StringUtils.isNotBlank(invoiceIdValue)){
+            // 已登陆 给发票ID赋值
+            servletContext.setAttribute(requestAuthorization,invoiceIdValue);
+            filterChain.doFilter(servletRequest, servletResponse);
+            return;
+        }else{
+            // 登陆过期,重新登陆
+            setResponseParam(response);
+            return;
+        }
+    }
+
+    private void setResponseParam(HttpServletResponse response)throws IOException{
+        response.setCharacterEncoding("UTF-8");
+        response.setContentType("application/json");
+        response.setHeader("Access-Control-Allow-Origin","*");
+        response.getWriter().write(this.LOGIN_EXPIRED);
+    }
+
+    /**
+     * @Description: 是否必须要登陆
+     * @param uri
+     */
+    public boolean isNeedAuthorization(String uri) {
+
+        for (String includeUrl : includeUrls) {
+            if(uri.contains(includeUrl)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    @Override
+    public void init(FilterConfig filterConfig) throws ServletException {
+
+    }
+
+    @Override
+    public void destroy() {
+
+    }
+}

+ 366 - 0
future/HomeServiceImpl.java

@@ -0,0 +1,366 @@
+package com.zkh360.api.home.service.impl;
+
+import com.alibaba.fastjson.JSON;
+import com.zkh360.api.dto.GWResponseEnum;
+import com.zkh360.api.dto.GWResponseVO;
+import com.zkh360.api.dto.ResponseCode;
+import com.zkh360.api.dto.ResultResponse;
+import com.zkh360.api.home.dto.*;
+import com.zkh360.api.home.service.IHomeService;
+import com.zkh360.api.home.util.PedestalResponseMSG;
+import com.zkh360.core.exception.ZkhRuntimeException;
+import com.zkh360.core.util.ZkhApiUtil;
+import com.zkh360.core.util.ZkhGWInvoiceId;
+import com.zkh360.core.util.ZkhGWapiEnum;
+import com.zkh360.core.util.redis.RedisService;
+import lombok.extern.slf4j.Slf4j;
+import net.sf.json.JSONArray;
+import net.sf.json.JSONObject;
+import org.apache.commons.lang.StringUtils;
+import org.springframework.beans.BeanUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.http.ResponseEntity;
+import org.springframework.stereotype.Service;
+import org.springframework.web.client.RestTemplate;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.Future;
+
+/**
+ * 首页实现类
+ */
+@Service
+@Slf4j
+public class HomeServiceImpl implements IHomeService {
+
+    @Autowired
+    private ZkhApiUtil zkhApiUtil;
+
+    @Autowired
+    private RedisService redisService;
+    @Value("${zkh.website.url}")
+    private  String domainUrl;
+
+    @Autowired
+    private RestTemplate restTemplate;
+
+    @Override
+    public ResultResponse getHome() throws Exception {
+
+        HomeResultDto homeResultDto = new HomeResultDto();
+        String message = null;
+        final String invoiceId = getInvoiceId();
+        //多线程请求官网api
+        Future<List> futureBannerList = CompletableFuture.supplyAsync(() -> getBanner(restTemplate,invoiceId));
+        Future<List> futureBrandList = CompletableFuture.supplyAsync(() -> getAuthenticBrand(restTemplate,invoiceId));
+        Future<List> futureCatalogueList = CompletableFuture.supplyAsync(() -> getCatalogue(restTemplate,invoiceId));
+        Future<List> futureTopCatalogueList = CompletableFuture.supplyAsync(() -> getTopCatalogue(restTemplate,invoiceId));
+        Future<List> futureRecommendList = CompletableFuture.supplyAsync(() -> getRecommends(restTemplate,invoiceId));
+        List<Banner> bannerList = futureBannerList.get();
+        List<Brand> brandList =  futureBrandList.get();
+        List<FineCategory> catalogueList = futureCatalogueList.get();
+        List<Category> topCatalogueList = futureTopCatalogueList.get();
+        List<RecommendProduct> recommends = futureRecommendList.get();
+        homeResultDto.setBanners(bannerList);
+        homeResultDto.setBrands(brandList);
+        homeResultDto.setCategorys(topCatalogueList);
+        homeResultDto.setFineCategorys(catalogueList);
+        homeResultDto.setRecommends(recommends);
+        ResultResponse rs = new ResultResponse();
+        rs.setStateCode(ResponseCode.CODE_0);
+        rs.setMessage(message);
+        rs.setData(homeResultDto);
+        return rs;
+    }
+
+
+    /**
+     * 获取首页banner图
+     * @return
+     */
+    public List<Banner> getBanner(RestTemplate restTemplate,String invoiceId){
+        List<Banner> bannerList = new ArrayList<>();
+        List<BannerDto> list = null;
+        String url = domainUrl + ZkhGWapiEnum.RECOMMENT_BANNER.getApi()+"?access_token="+redisService.get("access_token")+"&userInvoiceId="+invoiceId;
+        JSONArray result = requestGWApi(restTemplate, url);
+        if(result != null && result.size()>0) {
+            String jsonString = JSON.toJSONString(result);
+            list = JSON.parseArray(jsonString, BannerDto.class);
+        }
+        if(list != null && list.size() > 0){
+            for (BannerDto bannerDto : list) {
+                Banner banner = new Banner();
+                BeanUtils.copyProperties(bannerDto,banner);
+                bannerList.add(banner);
+            }
+        }
+        return bannerList;
+    }
+
+
+    /**
+     * 获取正品大牌
+     * @return
+     */
+    public List<Brand> getAuthenticBrand(RestTemplate restTemplate, String invoiceId){
+        List<Brand> brandList = new ArrayList<>();
+        List<BannerDto> list = null;
+        String url = domainUrl + ZkhGWapiEnum.RECOMMENT_BRAND.getApi()+"?access_token="+redisService.get("access_token")+"&userInvoiceId="+invoiceId;
+        JSONArray result = requestGWApi(restTemplate, url);
+        if(result != null && result.size()>0) {
+            String jsonString = JSON.toJSONString(result);
+            list = JSON.parseArray(jsonString, BannerDto.class);
+        }
+        if(list != null && list.size() > 0){
+            for (BannerDto bannerDto : list) {
+                Brand brand = new Brand();
+                brand.setDetail(Integer.parseInt(bannerDto.getDetail()));
+                brand.setThumbnail(bannerDto.getThumbnail());
+                String title = bannerDto.getTitle();
+                brand.setBrandName(title.substring(0,title.indexOf("^")));
+                brandList.add(brand);
+            }
+        }
+        return brandList;
+    }
+
+
+    /**
+     * 获取精选品类
+     * @return
+     */
+    public List<FineCategory> getCatalogue(RestTemplate restTemplate,String invoiceId){
+        List<FineCategory> catalogueList = new ArrayList<>();
+        List<BannerDto> list = null;
+        String url = domainUrl + ZkhGWapiEnum.RECOMMENT_CATALOGUE.getApi()+"?access_token="+redisService.get("access_token")+"&userInvoiceId="+invoiceId;
+        JSONArray result = requestGWApi(restTemplate, url);
+        if(result != null && result.size()>0) {
+            String jsonString = JSON.toJSONString(result);
+            list = JSON.parseArray(jsonString, BannerDto.class);
+        }
+        if(list != null && list.size() > 0){
+            for (BannerDto bannerDto : list) {
+                FineCategory fineCategory = new FineCategory();
+                fineCategory.setId(bannerDto.getId());
+                fineCategory.setThumbnail(bannerDto.getThumbnail());
+                fineCategory.setDetail(Integer.parseInt(bannerDto.getDetail()));
+                String title = bannerDto.getTitle();
+                int i = title.indexOf("^");
+                int index = title.indexOf("|");
+                String titleName = title.substring(0,i);
+                String subTitle = title.substring(index+1);
+                fineCategory.setSubTitle(subTitle);
+                fineCategory.setTitle(titleName);
+                fineCategory.setTitleName(titleName);
+                catalogueList.add(fineCategory);
+            }
+        }
+        return catalogueList;
+    }
+
+
+    /**
+     * 获取一级目录推荐
+     * @return
+     */
+    public List<Category> getTopCatalogue(RestTemplate restTemplate,String invoiceId){
+        List<Category>  topCatalogueList = new ArrayList<>();
+        List<BannerDto> list = null;
+        String url = domainUrl + ZkhGWapiEnum.RECOMMENT_TOPCATALOGUE.getApi()+"?access_token="+redisService.get("access_token")+"&userInvoiceId="+invoiceId;
+        JSONArray result = requestGWApi(restTemplate, url);
+        if(result != null && result.size()>0) {
+            String jsonString = JSON.toJSONString(result);
+            list = JSON.parseArray(jsonString, BannerDto.class);
+        }
+
+        if(list != null && list.size() > 0){
+            for (BannerDto bannerDto : list) {
+                Category category = new Category();
+                category.setThumbnail(bannerDto.getThumbnail());
+                int detail = Integer.parseInt(bannerDto.getDetail());
+                int id = detail < 0 ? 0 : detail;
+                category.setDetail(id);
+                String title = bannerDto.getTitle();
+                category.setTitle(title.substring(0,title.indexOf("^")));
+                topCatalogueList.add(category);
+            }
+        }
+        return topCatalogueList;
+    }
+
+    /**
+     *
+     * 获取热销产品推荐
+     * @return
+     */
+    public List<RecommendProduct> getRecommends(RestTemplate restTemplate,String invoiceId){
+        List<RecommendProduct> list = new ArrayList<>();
+        String url = domainUrl + ZkhGWapiEnum.RECOMMENT_PRODUCT.getApi()+"?access_token="+redisService.get("access_token")+"&userInvoiceId="+invoiceId;
+        log.info("请求官网url===>"+url);
+        long startTime = System.currentTimeMillis();
+        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
+        String body = responseEntity.getBody();
+        log.info("耗时 : " + (System.currentTimeMillis() - startTime));
+        JSONObject resultBody = JSONObject.fromObject(body);
+        Boolean success = (Boolean)resultBody.get("success");
+        if(!success){
+            throw new ZkhRuntimeException((String)resultBody.get("message"));
+        }
+        JSONObject result = resultBody.getJSONObject("result");
+        if(null != result && result.has("content")){
+            JSONArray content = result.getJSONArray("content");
+            if(content != null && content.size()>0) {
+                String s = JSON.toJSONString(content);
+                list = JSON.parseArray(s,RecommendProduct.class);
+            }
+        }
+        if(list != null && list.size() > 0){
+            for (RecommendProduct recommend : list) {
+                recommend.setGoodsThumb(recommend.getLeftImageList().get(0));
+            }
+        }
+        return list;
+    }
+
+
+    @Override
+    public ResultResponse changePedestalForJava(PedestalInfo pedestalInfo) {
+        ResultResponse resultResponse = new ResultResponse();
+        resultResponse.setStateCode(ResponseCode.CODE_0);
+        resultResponse.setMessage("修改成功");
+        if(pedestalInfo.getPassCode().hashCode() != PedestalResponseMSG.PASSCODE){
+            resultResponse.setStateCode(ResponseCode.CODE_1);
+            resultResponse.setMessage(PedestalResponseMSG.PASSCODE_WRONG);
+            return resultResponse;
+        }
+        if(!pedestalInfo.getDevice().equals(PedestalResponseMSG.ANDROID) && !pedestalInfo.getDevice().equals(PedestalResponseMSG.IOS)){
+            resultResponse.setStateCode(ResponseCode.CODE_1);
+            resultResponse.setMessage(PedestalResponseMSG.DEVICE_WRONG);
+            return resultResponse;
+        }
+        if(!pedestalInfo.getNativeOrH5().equals(PedestalResponseMSG.NATIVE) && !pedestalInfo.getNativeOrH5().equals(PedestalResponseMSG.H5)){
+            resultResponse.setStateCode(ResponseCode.CODE_1);
+            resultResponse.setMessage(PedestalResponseMSG.PEDESTAL_WRONG);
+            return resultResponse;
+        }
+        if(pedestalInfo.getDevice().equals(PedestalResponseMSG.ANDROID)){
+            if(pedestalInfo.getNativeOrH5().equals(PedestalResponseMSG.NATIVE)){
+                redisService.set(PedestalResponseMSG.PEDESTAL_FOR_ANDRIOD,PedestalResponseMSG.NATIVE_CODE);
+            }else{
+                redisService.set(PedestalResponseMSG.PEDESTAL_FOR_ANDRIOD,PedestalResponseMSG.H5_CODE);
+            }
+        }
+        if(pedestalInfo.getDevice().equals(PedestalResponseMSG.IOS)){
+            if(pedestalInfo.getNativeOrH5().equals(PedestalResponseMSG.NATIVE)){
+                redisService.set(PedestalResponseMSG.PEDESTAL_FOR_IOS,PedestalResponseMSG.NATIVE_CODE);
+            }else{
+                redisService.set(PedestalResponseMSG.PEDESTAL_FOR_IOS,PedestalResponseMSG.H5_CODE);
+            }
+        }
+        return resultResponse;
+    }
+
+    @Override
+    public ResultResponse getNoticeList() throws Exception {
+        String url = ZkhGWapiEnum.GLOBALCONFIG_ANNOUNCEMENT.getApi();
+        GWResponseVO<Object> gwResponseVO = new GWResponseVO<>();
+        List<Notice> list = new ArrayList<>();
+        try {
+            gwResponseVO = zkhApiUtil.callZKHGWGet(url, new HashMap<>(0), null);
+        }catch (ZkhRuntimeException zkhRuntimeException){
+            //首页公告配置过期
+            if(GWResponseEnum.CONFIG_ANNOUNCEMENT.getMessage().equals(zkhRuntimeException.getMessage())){
+                return new ResultResponse(list);
+            }
+        }
+        //首页公告没有配置
+        if(gwResponseVO.getResult() == null){
+            return new ResultResponse(list);
+        }
+        String noticeContent = gwResponseVO.getResult().toString();
+        Notice notice = new Notice();
+        notice.setNoticeContent(noticeContent);
+        list.add(notice);
+        return new ResultResponse(list);
+    }
+
+    @Override
+    public ResultResponse getBannerInfo(Integer id) throws Exception {
+        String invoiceId = getInvoiceId();
+        String url = domainUrl + ZkhGWapiEnum.RECOMMENT_BANNER.getApi()+"?access_token="+redisService.get("access_token")+"&userInvoiceId="+invoiceId;
+        String html = "";
+        JSONArray jsonArray = requestGWApi(restTemplate, url);
+        if(null != jsonArray && jsonArray.size() >0){
+            for (int i = 0; i < jsonArray.size(); i++) {
+                JSONObject jsonObject = jsonArray.getJSONObject(i);
+                if(null != jsonObject && jsonObject.getInt("id") == id){
+                    html = jsonObject.getString("detail");
+                }
+            }
+        }
+
+        return new ResultResponse(html);
+    }
+
+    @Override
+    public ResultResponse changePedestal(String device) throws Exception {
+        ResultResponse resultResponse = new ResultResponse();
+        resultResponse.setStateCode(ResponseCode.CODE_0);
+        resultResponse.setMessage("成功");
+        Map resultMap = new HashMap();
+        if(!device.equals(PedestalResponseMSG.ANDROID) && !device.equals(PedestalResponseMSG.IOS)){
+            resultResponse.setStateCode(ResponseCode.CODE_1);
+            resultResponse.setMessage(PedestalResponseMSG.DEVICE_WRONG);
+            return resultResponse;
+        }
+        Integer pedestalCode = 1;
+        if(device.equals(PedestalResponseMSG.ANDROID)){
+            if(!redisService.exists(PedestalResponseMSG.PEDESTAL_FOR_ANDRIOD)){
+                pedestalCode = 1;
+            }else{
+                pedestalCode = (Integer) redisService.get(PedestalResponseMSG.PEDESTAL_FOR_ANDRIOD);
+            }
+        }else{
+            if(!redisService.exists(PedestalResponseMSG.PEDESTAL_FOR_IOS)){
+                pedestalCode = 1;
+            }else{
+                pedestalCode = (Integer) redisService.get(PedestalResponseMSG.PEDESTAL_FOR_IOS);
+            }
+        }
+        resultMap.put("nativeOrH5",pedestalCode);
+        resultResponse.setData(resultMap);
+        return resultResponse;
+    }
+    @Override
+    public JSONArray requestGWApi(RestTemplate restTemplate,String url){
+        log.info("请求官网url===>"+url);
+        long startTime = System.currentTimeMillis();
+        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
+        String body = responseEntity.getBody();
+        log.info("耗时 : " + (System.currentTimeMillis() - startTime));
+        JSONObject resultBody = JSONObject.fromObject(body);
+        Boolean success = (Boolean)resultBody.get("success");
+        if(!success){
+            throw new ZkhRuntimeException((String)resultBody.get("message"));
+        }
+        JSONArray result = resultBody.getJSONArray("result");
+        return result;
+    }
+
+    //获取发票ID
+    public String getInvoiceId(){
+        String invoiceId = null;
+        String authorization = ZkhGWInvoiceId.getInvoiceId();
+        if(StringUtils.isNotBlank(authorization)){
+            invoiceId = redisService.get(authorization).toString();
+        }
+        return invoiceId==null?"":invoiceId;
+
+    }
+
+}

+ 287 - 0
http/ZkhApiUtil.java

@@ -0,0 +1,287 @@
+/*
+ * CopyRight © 2018 ZKH All Rights Reserved.
+ */
+package com.zkh360.core.util;
+
+import com.alibaba.fastjson.JSON;
+import com.zkh360.api.dto.GWResponseEnum;
+import com.zkh360.api.dto.GWResponseVO;
+import com.zkh360.api.dto.ResponseCode;
+import com.zkh360.core.exception.TokenPassException;
+import com.zkh360.core.exception.WebsiteRuntimeException;
+import com.zkh360.core.exception.ZkhRuntimeException;
+import com.zkh360.core.task.TokenScheduled;
+import com.zkh360.core.util.redis.RedisService;
+import lombok.extern.log4j.Log4j;
+import net.sf.json.JSONObject;
+import org.apache.commons.lang.StringUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import java.lang.reflect.ParameterizedType;
+import java.lang.reflect.Type;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+@Component
+@Log4j
+public class ZkhApiUtil {
+
+    @Autowired
+    private ZkhHttpUtil zkhHttpUtil;
+
+    private static RedisService redisService;
+    private static TokenScheduled tokenScheduled;
+
+    private static final String post = "POST";
+    private static final String get = "GET";
+    private static final String put = "PUT";
+    private static final String delete = "DELETE";
+
+    String[] needInvoiceUrls = new String[]{
+            "/zkhUserInvoices/"+"/invoiceInfoTitleType",
+    };
+
+    public <T> GWResponseVO<T> callZKHGWPost(String api, Map<String, Object> params, Class<T> clazz) throws Exception{
+        String method = post;
+        String resultJson = callGWMethod(method,api, params);
+        return (GWResponseVO<T>) dealReseponse(api,resultJson);
+    }
+
+    public <T> GWResponseVO<T> callZKHGWPut(String api, Map<String, Object> params, Class<T> clazz) throws Exception{
+        String method = put;
+        String resultJson = callGWMethod(method,api, params);
+        return (GWResponseVO<T>) dealReseponse(api,resultJson);
+    }
+
+    public <T> GWResponseVO<T> callZKHGWPostByJA(String api, List<T> list, Class<T> clazz)throws Exception {
+        String resultJson = callGWPostByJA(api, list);
+        return (GWResponseVO<T>) dealReseponse(api,resultJson);
+    }
+
+
+    public <T> GWResponseVO<T> callZKHGWGet(String api, Map<String, Object> params, Class<T> clazz) throws Exception {
+        String method = get;
+        String resultJson = callGWMethod(method,api, params);
+        return (GWResponseVO<T>) dealReseponse(api,resultJson);
+    }
+
+    public <T> GWResponseVO<T> callZKHGWDelete(String api, Map<String, Object> params, Class<T> clazz) throws Exception{
+        String method = delete;
+        String resultJson = callGWMethod(method,api, params);
+        return (GWResponseVO<T>) dealReseponse(api,resultJson);
+    }
+
+    public <T> GWResponseVO<T> callZKHGWPutNoInvoice(String api, Map<String, Object> params, Class<T> clazz) throws Exception{
+        String method = put;
+        String resultJson = callGWMethodNoInvoice(method,api, params);
+        return (GWResponseVO<T>) dealReseponse(api,resultJson);
+    }
+
+    private String callGWMethod(String method,String api, Map<String, Object> params) {
+        assert api != null;
+        Map<String,Object> map = getMapParams(params);
+        String newApi = "";
+        //登录接口
+        if(api.equals("/zkhUser/login")){
+            map.put("invoiceInfoId", map.get("invoiceInfoId"));
+            newApi = api + "?access_token="+ redisService.get("access_token");
+        }else{
+            newApi = spliceTokenAndUserInvoiceId(api);
+        }
+        try {
+            long startTime = System.currentTimeMillis();
+            String s = zkhHttpUtil.requestWithJSON(method, newApi, map);
+            log.info("耗时 : " + (System.currentTimeMillis() - startTime));
+            return s;
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return null;
+    }
+
+    private String callGWMethodNoInvoice(String method,String api, Map<String, Object> params) {
+        assert api != null;
+        Map<String,Object> map = getMapParams(params);
+        String newApi = "";
+        try {
+            String token = getToken();
+            newApi = api + "&access_token="+ token;
+            long startTime = System.currentTimeMillis();
+            String s = zkhHttpUtil.requestWithJSON(method, newApi, map);
+            log.info("耗时 : " + (System.currentTimeMillis() - startTime));
+            return s;
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return null;
+    }
+
+
+        private String postByJA(String api, List list) {
+            assert api != null;
+            String newApi = spliceTokenAndUserInvoiceId(api);
+            try {
+                return zkhHttpUtil.postRequestWithJSONArray(newApi,list);
+            } catch (Exception e) {
+            }
+        return null;
+    }
+
+
+    private static Map<String,Object> getMapParams(Map<String, Object> params){
+        Map<String, Object> map;
+        if(params != null) {
+            map = params;
+        } else {
+            map = new HashMap<>();
+        }
+        return map;
+    }
+    private String spliceTokenAndUserInvoiceId(String api){
+        String newApi = "";
+        String token = getToken();
+        if(isNeedInvoiceId(api)){
+            newApi = api + "?access_token="+ token;
+        }else{
+            if(ZkhGWInvoiceId.getInvoiceId() == null){
+                newApi = api + "?access_token="+ token +"&userInvoiceId="+ "";
+            }else{
+                newApi = api + "?access_token="+ token +"&userInvoiceId="+ redisService.get(ZkhGWInvoiceId.getInvoiceId());
+            }
+        };
+
+        return newApi;
+    }
+
+    /**
+     * @Description: 发票ID是否作为单独的参数
+     * @param uri
+     */
+    private boolean isNeedInvoiceId(String uri) {
+
+        for (String needInvoiceUrls : needInvoiceUrls) {
+            if(uri.contains(needInvoiceUrls)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    private GWResponseVO<Object> dealReseponse(String api,String resultJson)throws Exception{
+        GWResponseVO<Object> gwResponseVO = new GWResponseVO<>();
+            log.info("官网返回值:"+resultJson);
+            String apiName = "";
+            if(StringUtils.isBlank(resultJson)){
+                throw new RuntimeException("接口异常");
+            }
+            gwResponseVO = JSON.parseObject(resultJson, GWResponseVO.class);
+            for (ZkhGWapiEnum e : ZkhGWapiEnum.values()) {
+                if (api.equals(e.getApi())) {
+                    apiName = e.getDesc();
+                }
+            }
+            if(null != gwResponseVO.getCode() && GWResponseEnum.CONFIG_ANNOUNCEMENT.getCode().equals(gwResponseVO.getCode())
+                    && gwResponseVO.getMessage().equals(GWResponseEnum.CONFIG_ANNOUNCEMENT.getMessage())){
+                throw new ZkhRuntimeException(GWResponseEnum.CONFIG_ANNOUNCEMENT.getMessage());
+            }
+            if(null != gwResponseVO.getCode() && GWResponseEnum.MIN_SKU_COUNT_ERROR.getCode().equals(gwResponseVO.getCode())){
+                throw new WebsiteRuntimeException(ResponseCode.CODE_1601, GWResponseEnum.MIN_SKU_COUNT_ERROR.getMessage());
+            }
+            if(null != gwResponseVO.getCode() && GWResponseEnum.SKU_STOCK_NOT_USE.getCode().equals(gwResponseVO.getCode())){
+                throw new WebsiteRuntimeException(ResponseCode.CODE_1602, GWResponseEnum.SKU_STOCK_NOT_USE.getMessage());
+            }
+            if(null != gwResponseVO.getCode() && GWResponseEnum.SKU_SELLED.getCode().equals(gwResponseVO.getCode())){
+                throw new WebsiteRuntimeException(ResponseCode.CODE_1603, GWResponseEnum.SKU_SELLED.getMessage());
+            }
+            if (null != gwResponseVO.getCode() && gwResponseVO.getCode().equals(1)) {
+                throw new TokenPassException(gwResponseVO.getCode(), apiName + gwResponseVO.getMessage());
+            }
+            if (!gwResponseVO.isSuccess()) {
+                throw new RuntimeException(apiName + gwResponseVO.getMessage());
+            }
+        return gwResponseVO;
+    }
+
+
+
+    public String callGWPostByJA(String api, List list) {
+        return postByJA(api, list);
+    }
+
+    public static boolean isJson(String content) {
+        try {
+            JSONObject.fromObject(content);
+            return true;
+        } catch (Exception e) {
+            return false;
+        }
+    }
+
+
+    interface GenericType {
+        Type genericType(Class<?> rawClass, Class<?> actualTypeClass);
+    }
+
+    static class GenericTypeImpl implements GenericType {
+        @Override
+        public Type genericType(final Class<?> rawClass, final Class<?> actualTypeClass) {
+            return new ParameterizedType() {
+                @Override
+                public Type[] getActualTypeArguments() {
+                    return new Type[] { actualTypeClass };
+                }
+
+                @Override
+                public Type getRawType() {
+                    return rawClass;
+                }
+
+                @Override
+                public Type getOwnerType() {
+                    return null;
+                }
+            };
+        }
+    }
+
+
+    @Autowired
+    public void setRedisService(RedisService redisService) {
+        ZkhApiUtil.redisService = redisService;
+    }
+    @Autowired
+    public void setTokenScheduled(TokenScheduled tokenScheduled) {
+        ZkhApiUtil.tokenScheduled = tokenScheduled;
+    }
+
+    /**
+     * 获取token
+     * @return
+     */
+    public String getToken(){
+        String token = "";
+        if(null != redisService){
+            try{
+                boolean tokenExists = redisService.exists("access_token");
+                if(!tokenExists){
+                    token = tokenScheduled.getToken();
+                    redisService.set("access_token",token,7200L);
+                }else{
+                    token = (String) redisService.get("access_token");
+                }
+            }catch (Exception e){
+                token = tokenScheduled.getToken();
+            }
+        }else{
+            token = tokenScheduled.getToken();
+        }
+        return token;
+    }
+
+
+
+
+
+}

+ 171 - 0
http/ZkhHttpUtil.java

@@ -0,0 +1,171 @@
+/*
+ * CopyRight © 2018 ZKH All Rights Reserved.
+ */
+package com.zkh360.core.util;
+
+import lombok.extern.slf4j.Slf4j;
+import net.sf.json.JSONArray;
+import net.sf.json.JSONObject;
+import net.sf.json.JsonConfig;
+import net.sf.json.processors.DefaultDefaultValueProcessor;
+import org.apache.http.HttpEntity;
+import org.apache.http.HttpException;
+import org.apache.http.HttpResponse;
+import org.apache.http.client.methods.*;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.message.BasicHeader;
+import org.apache.http.util.EntityUtils;
+import org.springframework.stereotype.Component;
+
+import javax.annotation.Resource;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+@Slf4j
+@Component
+public class ZkhHttpUtil {
+
+    @Resource(name = "httpClientManager")
+    private CloseableHttpClient client;
+
+    JsonConfig jsonConfig = new JsonConfig();
+
+
+    public String requestWithJSON(String method,String newApi, Map<String, Object> params) throws Exception {
+        CloseableHttpResponse response = null;
+        jsonConfig.registerDefaultValueProcessor(Double.class,new DefaultDefaultValueProcessor(){
+            @Override
+            public Object getDefaultValue(Class type) {
+            return null;
+        }});
+        JSONObject jsonObject = JSONObject.fromObject(params,jsonConfig);
+        String json = jsonObject.toString();
+        if(method.equals("POST")){
+            HttpPost httpPost = new HttpPost(GWdomain.ZKHWebsiteUrl.concat(newApi));
+            httpPost.addHeader("Content-Type", "application/json");
+            httpPost.setEntity(setPostOrPutRequestHttpContent(json));
+            log.info("POST请求官网的uri:"+httpPost.getURI());
+            log.info("POST请求官网的param:"+json);
+            response = client.execute(httpPost);
+        } else if (method.equals("GET")) {
+            StringBuffer sb = getOrDeleteRequestParams(newApi,params);
+            log.info("GET请求官网的地址:"+sb.toString());
+            HttpGet httpGet = new HttpGet(sb.toString());
+            response = client.execute(httpGet);
+        }else if(method.equals("PUT")){
+            HttpPut httpPut = new HttpPut(GWdomain.ZKHWebsiteUrl.concat(newApi));
+            httpPut.addHeader("Content-Type", "application/json");
+            httpPut.setEntity(setPostOrPutRequestHttpContent(json));
+            log.info("PUT请求官网uri:"+httpPut.getURI());
+            log.info("PUT请求官网param:"+json);
+            response = client.execute(httpPut);
+        }else if(method.equals("DELETE")){
+            StringBuffer sb = getOrDeleteRequestParams(newApi,params);
+            log.info("DELETE请求官网的地址:"+sb.toString());
+            HttpDelete httpDelete = new HttpDelete(sb.toString());
+            response = client.execute(httpDelete);
+        }
+        return judgeResult(response);
+    }
+
+    public String postRequestWithJSONArray(String newApi, List list) throws Exception {
+        HttpPost httpPost = new HttpPost(GWdomain.ZKHWebsiteUrl.concat(newApi));
+        httpPost.addHeader("Content-Type", "application/json");
+        return doPostWithJSONArray(list, httpPost);
+    }
+
+    private static StringBuffer getOrDeleteRequestParams(String newApi, Map<String, Object> params){
+        StringBuffer sb = new StringBuffer(GWdomain.ZKHWebsiteUrl.concat(newApi));
+        Iterator<Map.Entry<String,Object>> it = params.entrySet().iterator();
+        if(params != null || !params.isEmpty()){
+            while (it.hasNext())
+            {
+                Map.Entry<String,Object> entry = it.next();
+                Object key = entry.getKey();
+                sb.append("&");
+                sb.append(key);
+                sb.append('=');
+                Object value = entry.getValue();
+                if(isArray(value)){
+                    Integer[] value1 = (Integer[]) value;
+                    for(int i = 0; i < value1.length; i++){
+                        sb.append(value1[i]);
+                        if(i == value1.length -1){
+                            break;
+                        }
+                        sb.append("&");
+                        sb.append(key);
+                        sb.append('=');
+
+                    }
+                }else{
+                    sb.append(value);
+                }
+
+                if (!it.hasNext())
+                {
+                    break;
+                }
+            }
+        }
+        return sb;
+    }
+
+    private static boolean isArray(Object obj) {
+        if(obj == null) {
+            return false;
+        }
+        return obj.getClass().isArray();
+    }
+
+    private String doPostWithJSONArray(List list, HttpPost httpPost) throws Exception {
+        JSONArray jsonArray = new JSONArray();
+        if(list != null && list.size() > 0) {
+            jsonArray = JSONArray.fromObject(list);
+        }
+        httpPost.setEntity(setPostOrPutRequestHttpContent(jsonArray.toString()));
+        log.info("POST请求官网uri:"+httpPost.getURI());
+        log.info("POST请求官网param:"+jsonArray.toString());
+        HttpResponse response = client.execute(httpPost);
+        return judgeResult(response);
+    }
+
+    private static StringEntity setPostOrPutRequestHttpContent(String param){
+        StringEntity se = new StringEntity(param, "UTF-8");
+        se.setContentType("text/json");
+        se.setContentEncoding(new BasicHeader("Content-Type", "application/json"));
+        return se;
+    }
+
+    private String judgeResult(HttpResponse response)throws Exception{
+        String result = null;
+        HttpEntity resEntity = null;
+        try{
+            if (response != null) {
+                resEntity = response.getEntity();
+                if (resEntity != null) {
+                    result = EntityUtils.toString(resEntity, "UTF-8");
+                }
+            }
+        }catch (Exception e){
+            throw new HttpException("Http请求处理失败", e);
+        }finally {
+            closeHttpConnect(resEntity);
+        }
+        return result;
+    }
+
+    /**
+     * 释放连接
+     * @param response
+     */
+    private void closeHttpConnect(HttpEntity response) {
+        if(null != response){
+            EntityUtils.consumeQuietly(response);
+        }
+    }
+
+
+}

+ 358 - 0
jsonUtil/JSONUtils.java

@@ -0,0 +1,358 @@
+package com.zkh360.api.utils;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JavaType;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import net.sf.json.JSONArray;
+import net.sf.json.JSONObject;
+import org.apache.commons.beanutils.BeanUtils;
+public class JSONUtils {
+
+    /**
+     *
+     * @author wangwei JSON工具类
+     * @param
+     *
+     */
+    // 定义jackson对象
+    private static final ObjectMapper MAPPER = new ObjectMapper();
+
+    /***
+     * 将List对象序列化为JSON文本
+     */
+    public static <T> String toJSONString(List<T> list)
+    {
+        JSONArray jsonArray = JSONArray.fromObject(list);
+
+        return jsonArray.toString();
+    }
+
+    /***
+     * 将对象序列化为JSON文本
+     * @param object
+     * @return
+     */
+    public static String toJSONString(Object object)
+    {
+        JSONArray jsonArray = JSONArray.fromObject(object);
+
+        return jsonArray.toString();
+    }
+
+    /***
+     * 将JSON对象数组序列化为JSON文本
+     * @param jsonArray
+     * @return
+     */
+    public static String toJSONString(JSONArray jsonArray)
+    {
+        return jsonArray.toString();
+    }
+
+    /***
+     * 将JSON对象序列化为JSON文本
+     * @param jsonObject
+     * @return
+     */
+    public static String toJSONString(JSONObject jsonObject)
+    {
+        return jsonObject.toString();
+    }
+
+    /***
+     * 将对象转换为List对象
+     * @param object
+     * @return
+     */
+    public static List toArrayList(Object object)
+    {
+        List arrayList = new ArrayList();
+
+        JSONArray jsonArray = JSONArray.fromObject(object);
+
+        Iterator it = jsonArray.iterator();
+        while (it.hasNext())
+        {
+            JSONObject jsonObject = (JSONObject) it.next();
+
+            Iterator keys = jsonObject.keys();
+            while (keys.hasNext())
+            {
+                Object key = keys.next();
+                Object value = jsonObject.get(key);
+                arrayList.add(value);
+            }
+        }
+
+        return arrayList;
+    }
+
+    /***
+     * 将对象转换为Collection对象
+     * @param object
+     * @return
+     */
+    public static Collection toCollection(Object object)
+    {
+        JSONArray jsonArray = JSONArray.fromObject(object);
+
+        return JSONArray.toCollection(jsonArray);
+    }
+
+    /***
+     * 将对象转换为JSON对象数组
+     * @param object
+     * @return
+     */
+    public static JSONArray toJSONArray(Object object)
+    {
+        return JSONArray.fromObject(object);
+    }
+
+    /***
+     * 将对象转换为JSON对象
+     * @param object
+     * @return
+     */
+    public static JSONObject toJSONObject(Object object)
+    {
+        return JSONObject.fromObject(object);
+    }
+
+    /***
+     * 将对象转换为HashMap
+     * @param object
+     * @return
+     */
+    public static HashMap toHashMap(Object object)
+    {
+        HashMap<String, Object> data = new HashMap<String, Object>();
+        JSONObject jsonObject = JSONUtils.toJSONObject(object);
+        Iterator it = jsonObject.keys();
+        while (it.hasNext())
+        {
+            String key = String.valueOf(it.next());
+            Object value = jsonObject.get(key);
+            data.put(key, value);
+        }
+
+        return data;
+    }
+
+    /***
+     * 将对象转换为List>
+     * @param object
+     * @return
+     */
+    // 返回非实体类型(Map)的List
+    public static List<Map<String, Object>> toList(Object object)
+    {
+        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
+        JSONArray jsonArray = JSONArray.fromObject(object);
+        for (Object obj : jsonArray)
+        {
+            JSONObject jsonObject = (JSONObject) obj;
+            Map<String, Object> map = new HashMap<String, Object>();
+            Iterator it = jsonObject.keys();
+            while (it.hasNext())
+            {
+                String key = (String) it.next();
+                Object value = jsonObject.get(key);
+                map.put((String) key, value);
+            }
+            list.add(map);
+        }
+        return list;
+    }
+
+    /***
+     * 将JSON对象数组转换为传入类型的List
+     * @param
+     * @param jsonArray
+     * @param objectClass
+     * @return
+     */
+    public static <T> List<T> toList(JSONArray jsonArray, Class<T> objectClass)
+    {
+        return JSONArray.toList(jsonArray, objectClass);
+    }
+
+    /***
+     * 将对象转换为传入类型的List
+     * @param
+     * @param object
+     * @param objectClass
+     * @return
+     */
+    public static <T> List<T> toList(Object object, Class<T> objectClass)
+    {
+        JSONArray jsonArray = JSONArray.fromObject(object);
+
+        return JSONArray.toList(jsonArray, objectClass);
+    }
+
+    /***
+     * 将JSON对象转换为传入类型的对象
+     * @param
+     * @param jsonObject
+     * @param beanClass
+     * @return
+     */
+    public static <T> T toBean(JSONObject jsonObject, Class<T> beanClass)
+    {
+        return (T) JSONObject.toBean(jsonObject, beanClass);
+    }
+
+    /***
+     * 将将对象转换为传入类型的对象
+     * @param
+     * @param object
+     * @param beanClass
+     * @return
+     */
+    public static <T> T toBean(Object object, Class<T> beanClass)
+    {
+        JSONObject jsonObject = JSONObject.fromObject(object);
+
+        return (T) JSONObject.toBean(jsonObject, beanClass);
+    }
+
+    /***
+     * 将JSON文本反序列化为主从关系的实体
+     * @param jsonString JSON文本
+     * @param mainClass 主实体类型
+     * @param detailName 从实体类在主实体类中的属性名称
+     * @param detailClass 从实体类型
+     * @return
+     */
+    public static <T, D> T toBean(String jsonString, Class<T> mainClass,
+                                  String detailName, Class<D> detailClass)
+    {
+        JSONObject jsonObject = JSONObject.fromObject(jsonString);
+        JSONArray jsonArray = (JSONArray) jsonObject.get(detailName);
+
+        T mainEntity = JSONUtils.toBean(jsonObject, mainClass);
+        List<D> detailList = JSONUtils.toList(jsonArray, detailClass);
+
+        try
+        {
+            BeanUtils.setProperty(mainEntity, detailName, detailList);
+        }
+        catch (Exception ex)
+        {
+            throw new RuntimeException("主从关系JSON反序列化实体失败!");
+        }
+
+        return mainEntity;
+    }
+
+    /***
+     * 将JSON文本反序列化为主从关系的实体
+     * @param jsonString JSON文本
+     * @param mainClass 主实体类型
+     * @param detailName1 从实体类在主实体类中的属性
+     * @param detailClass1 从实体类型
+     * @param detailName2 从实体类在主实体类中的属性
+     * @param detailClass2 从实体类型
+     * @return
+     */
+    public static <T, D1, D2> T toBean(String jsonString, Class<T> mainClass,
+                                       String detailName1, Class<D1> detailClass1, String detailName2,
+                                       Class<D2> detailClass2)
+    {
+        JSONObject jsonObject = JSONObject.fromObject(jsonString);
+        JSONArray jsonArray1 = (JSONArray) jsonObject.get(detailName1);
+        JSONArray jsonArray2 = (JSONArray) jsonObject.get(detailName2);
+
+        T mainEntity = JSONUtils.toBean(jsonObject, mainClass);
+        List<D1> detailList1 = JSONUtils.toList(jsonArray1, detailClass1);
+        List<D2> detailList2 = JSONUtils.toList(jsonArray2, detailClass2);
+
+        try
+        {
+            BeanUtils.setProperty(mainEntity, detailName1, detailList1);
+            BeanUtils.setProperty(mainEntity, detailName2, detailList2);
+        }
+        catch (Exception ex)
+        {
+            throw new RuntimeException("主从关系JSON反序列化实体失败!");
+        }
+
+        return mainEntity;
+    }
+
+    /***
+     * 将JSON文本反序列化为主从关系的实体
+     * @param jsonString JSON文本
+     * @param mainClass 主实体类型
+     * @param detailName1 从实体类在主实体类中的属性
+     * @param detailClass1 从实体类型
+     * @param detailName2 从实体类在主实体类中的属性
+     * @param detailClass2 从实体类型
+     * @param detailName3 从实体类在主实体类中的属性
+     * @param detailClass3 从实体类型
+     * @return
+     */
+    public static <T, D1, D2, D3> T toBean(String jsonString,
+                                           Class<T> mainClass, String detailName1, Class<D1> detailClass1,
+                                           String detailName2, Class<D2> detailClass2, String detailName3,
+                                           Class<D3> detailClass3)
+    {
+        JSONObject jsonObject = JSONObject.fromObject(jsonString);
+        JSONArray jsonArray1 = (JSONArray) jsonObject.get(detailName1);
+        JSONArray jsonArray2 = (JSONArray) jsonObject.get(detailName2);
+        JSONArray jsonArray3 = (JSONArray) jsonObject.get(detailName3);
+
+        T mainEntity = JSONUtils.toBean(jsonObject, mainClass);
+        List<D1> detailList1 = JSONUtils.toList(jsonArray1, detailClass1);
+        List<D2> detailList2 = JSONUtils.toList(jsonArray2, detailClass2);
+        List<D3> detailList3 = JSONUtils.toList(jsonArray3, detailClass3);
+
+        try
+        {
+            BeanUtils.setProperty(mainEntity, detailName1, detailList1);
+            BeanUtils.setProperty(mainEntity, detailName2, detailList2);
+            BeanUtils.setProperty(mainEntity, detailName3, detailList3);
+        }
+        catch (Exception ex)
+        {
+            throw new RuntimeException("主从关系JSON反序列化实体失败!");
+        }
+
+        return mainEntity;
+    }
+
+    /***
+     * 将JSON文本反序列化为主从关系的实体
+     * @param jsonString JSON文本
+     * @param mainClass 主实体类型
+     * @param detailClass 存放了多个从实体在主实体中属性名称和类型
+     * @return
+     */
+    public static <T> T toBean(String jsonString, Class<T> mainClass,
+                               HashMap<String, Class> detailClass)
+    {
+        JSONObject jsonObject = JSONObject.fromObject(jsonString);
+        T mainEntity = JSONUtils.toBean(jsonObject, mainClass);
+        for (Object key : detailClass.keySet())
+        {
+            try
+            {
+                Class value = (Class) detailClass.get(key);
+                BeanUtils.setProperty(mainEntity, key.toString(), value);
+            }
+            catch (Exception ex)
+            {
+                throw new RuntimeException("主从关系JSON反序列化实体失败!");
+            }
+        }
+        return mainEntity;
+    }
+
+}

+ 87 - 0
log/WebLogAspect.java

@@ -0,0 +1,87 @@
+package com.zkh360.core.config;
+
+import lombok.extern.slf4j.Slf4j;
+import org.aspectj.lang.JoinPoint;
+import org.aspectj.lang.ProceedingJoinPoint;
+import org.aspectj.lang.annotation.*;
+import org.springframework.stereotype.Component;
+import org.springframework.web.context.request.RequestContextHolder;
+import org.springframework.web.context.request.ServletRequestAttributes;
+
+import javax.servlet.http.HttpServletRequest;
+import java.util.Arrays;
+
+@Aspect
+@Component
+@Slf4j
+public class WebLogAspect {
+
+
+    @Pointcut("execution(public * com.zkh360.api..controller.*.*(..))")//两个..代表所有子目录,最后括号里的两个..代表所有参数
+    public void logPointCut() {
+    }
+
+    @Before("logPointCut()")
+    public void doBefore(JoinPoint joinPoint) throws Throwable {
+        // 接收到请求,记录请求内容
+        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
+        HttpServletRequest request = attributes.getRequest();
+
+        // 记录下请求内容
+        log.info("请求地址 : " + request.getRequestURL().toString());
+        String requestAuthorization = request.getHeader("Authorization");
+        log.info("请求的Authorization:"+requestAuthorization);
+        log.info("请求的终端:"+request.getHeader("user-agent"));
+        log.info("HTTP METHOD : " + request.getMethod());
+        log.info("IP : " + request.getRemoteAddr());
+        log.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "."
+                + joinPoint.getSignature().getName());
+
+        //登陆接口用户密码加密
+        String url = request.getRequestURL().toString().substring(request.getRequestURL().toString().length()-10);
+        if(url != null && url.equals("user/login")){
+            String s = Arrays.toString(joinPoint.getArgs());
+            String params = "";
+            String invoiceId = "";
+            String username = "";
+            String[] split = s.split(",");
+            String[] rightStr = new String[split.length];
+            String str = "";
+            for (int i = 0; i < split.length; i++) {
+                str = split[2];
+                String[] temp = split[i].split("=");
+                rightStr[i] = temp[1];
+            }
+            String str2 = "";
+            String[] split1 = str.split("=");
+            for (int i = 0; i < split1.length; i++) {
+                str2 = split1[1];
+            }
+            for (int i = 0; i < rightStr.length; i++) {
+                invoiceId = rightStr[0];
+                username = rightStr[1];
+            }
+            final String passWord = MD5Util.md5(str2);
+//            params = "invoiceId="+invoiceId+",username="+username+",password="+passWord;
+            params = "invoiceId="+invoiceId+",username="+username;
+            log.info("参数 : " + params);
+        }else{
+            log.info("参数 : " + Arrays.toString(joinPoint.getArgs()));
+        }
+
+    }
+
+    @AfterReturning(returning = "ret", pointcut = "logPointCut()")// returning的值和doAfterReturning的参数名一致
+    public void doAfterReturning(Object ret) throws Throwable {
+        // 处理完请求,返回内容
+        log.info("接口返回值 : " + ret);
+    }
+
+    @Around("logPointCut()")
+    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
+        long startTime = System.currentTimeMillis();
+        Object ob = pjp.proceed();// ob 为方法的返回值
+        log.info("接口总耗时 : " + (System.currentTimeMillis() - startTime));
+        return ob;
+    }
+}

+ 262 - 0
redis/RedisService.java

@@ -0,0 +1,262 @@
+package com.zkh360.core.util.redis;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.data.redis.core.*;
+import org.springframework.stereotype.Service;
+
+import java.io.Serializable;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+
+@Service
+public class RedisService {
+    @Autowired
+    private RedisTemplate redisTemplate;
+
+    @Autowired
+    private StringRedisTemplate stringRedisTemplate;
+    /**
+     * 写入缓存
+     * @param key
+     * @param value
+     * @return
+     */
+    public boolean set(final String key, Object value) {
+        boolean result = false;
+        try {
+            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
+            operations.set(key, value);
+            result = true;
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return result;
+    }
+    /**
+     * 写入缓存设置时效时间
+     * @param key
+     * @param value
+     * @return
+     */
+    public boolean set(final String key, Object value, Long expireTime) {
+        boolean result = false;
+        try {
+            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
+            operations.set(key, value);
+            redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
+            result = true;
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return result;
+    }
+    /**
+     * 批量删除对应的value
+     * @param keys
+     */
+    public void remove(final String... keys) {
+        for (String key : keys) {
+            remove(key);
+        }
+    }
+
+    /**
+     * 批量删除key
+     * @param pattern
+     */
+    public void removePattern(final String pattern) {
+        Set<Serializable> keys = redisTemplate.keys(pattern);
+        if (keys.size() > 0) {
+            redisTemplate.delete(keys);
+        }
+    }
+    /**
+     * 删除对应的value
+     * @param key
+     */
+    public void remove(final String key) {
+        if (exists(key)) {
+            redisTemplate.delete(key);
+        }
+    }
+    /**
+     * 判断缓存中是否有对应的value
+     * @param key
+     * @return
+     */
+    public boolean exists(final String key) {
+        return redisTemplate.hasKey(key);
+    }
+    /**
+     * 读取缓存
+     * @param key
+     * @return
+     */
+    public Object get(final String key) {
+        Object result = null;
+        ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
+        result = operations.get(key);
+        return result;
+    }
+    /**
+     * 哈希 添加
+     * @param key
+     * @param hashKey
+     * @param value
+     */
+    public void hmSet(String key, Object hashKey, Object value){
+        HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
+        hash.put(key,hashKey,value);
+    }
+
+    /**
+     * 哈希获取数据
+     * @param key
+     * @param hashKey
+     * @return
+     */
+    public Object hmGet(String key, Object hashKey){
+        HashOperations<String, Object, Object>  hash = redisTemplate.opsForHash();
+        return hash.get(key,hashKey);
+    }
+
+    /**
+     * 列表添加
+     * @param k
+     * @param v
+     */
+    public void lPush(String k,Object v){
+        ListOperations<String, Object> list = redisTemplate.opsForList();
+        list.rightPush(k,v);
+    }
+
+    /**
+     * 列表删除指定元素
+     * @param k
+     * @param l
+     * @param l1
+     * @return
+     */
+    public void trim(String k, long l, long l1){
+        ListOperations<String, Object> list = redisTemplate.opsForList();
+        list.trim(k,l,l1);
+    }
+    
+    /**
+     * 列表获取
+     * @param k
+     */
+    @SuppressWarnings("unchecked")
+	public List<String> rightPop(String k){
+        ListOperations<String, Object> list = redisTemplate.opsForList();
+        return (List<String>) list.rightPop(k);
+    }
+    
+    /**
+     * 列表获取
+     * @param k
+     * @param l
+     * @param l1
+     * @return
+     */
+    public List<Object> lRange(String k, long l, long l1){
+        ListOperations<String, Object> list = redisTemplate.opsForList();
+        return list.range(k,l,l1);
+    }
+    
+    /**
+     * 列表长度
+     * @param k
+     * @return
+     */
+    public Long size(String k){
+        ListOperations<String, Object> list = redisTemplate.opsForList();
+        return list.size(k);
+    }
+
+    /**
+     * 集合添加
+     * @param key
+     * @param value
+     */
+    public void add(String key,Object value){
+        SetOperations<String, Object> set = redisTemplate.opsForSet();
+        set.add(key,value);
+    }
+
+    /**
+     * 集合获取
+     * @param key
+     * @return
+     */
+    public Set<Object> getMembers(String key){
+        SetOperations<String, Object> set = redisTemplate.opsForSet();
+        return set.members(key);
+    }
+
+    /**
+     * 有序集合添加
+     * @param key
+     * @param value
+     * @param scoure
+     */
+    public void zAdd(String key,Object value,double scoure){
+        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
+        zset.add(key,value,scoure);
+    }
+
+    /**
+     * 有序集合获取
+     * @param key
+     * @param scoure
+     * @param scoure1
+     * @return
+     */
+    public Set<Object> rangeByScore(String key,double scoure,double scoure1){
+        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
+        return zset.rangeByScore(key, scoure, scoure1);
+    }
+
+    public Long findSetSize(String key){
+        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
+        return zset.size(key);
+    }
+
+    public Double findItemScore(String key, Object obj){
+        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
+        return zset.score(key, obj);
+    }
+    /**
+     * 有序集合添加
+     * @param key
+     */
+    public Long zRemove(String key,Object... removeObj){
+        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
+        return zset.remove(key,removeObj);
+    }
+
+    public Long zRemoveRange(String key,long start, long end){
+        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
+        return zset.removeRange(key,start,end);
+    }
+
+
+    public Set<Object> keys(String pattern){
+        return redisTemplate.keys( pattern + "*");
+    }
+
+
+    public Set<Object> findSetAll(String key){
+        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
+        long max = zset.size(key);
+        return zset.rangeByScore(key, 0, max);
+    }
+
+    public Long getExpire(String key){
+       return redisTemplate.getExpire(key,TimeUnit.SECONDS);
+
+    }
+
+
+}