Java面试进阶(http协议、list集合操作、多线程、时间处理、excel导出图片)

Java面试进阶

http协议的使用

http请求get
HttpClient client = new HttpClient();
            URI url = new URIBuilder(APP_URL)
                    .setPath("/")
                    .addParameter("app_key", "")
                    .addParameter("f_gantry", )
                    .addParameter("t_gantry", )
                    .addParameter("time", )
                    .addParameter("group", "")
                    .build();
            GetMethod get = new GetMethod(url.toString());
            client.executeMethod(get);
            InputStream in = get.getResponseBodyAsStream();
            String res = IOUtils.toString(in, "utf-8");
            JSONObject obj = JSONObject.parseObject(res);
http请求Post
public static Object doPost(String url, String reqbody) throws Exception {
        HttpClient client = new HttpClient();
        PostMethod post = new PostMethod(url);
        RequestEntity entity = new StringRequestEntity(reqbody, "text/plain", "UTF-8");
        post.setRequestEntity(entity);
        post.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
        post.setRequestHeader("", "");
        client.executeMethod(post);
        StringWriter writer = new StringWriter();
        IOUtils.copy(post.getResponseBodyAsStream(), writer, StandardCharsets.UTF_8.name());
        String temps = writer.toString();
        if (temps.indexOf("{") == 0) {
            return JSONObject.parseObject(temps);
        } else if (temps.indexOf("[") == 0) {
            return JSONArray.parseObject(temps);
        } else {
            return temps;
        }
    }

JAVA8对list集合的使用

获得集合中某个字段的集合

List<String> names= users.stream().map(User::getName).collect(Collectors.toList())

List<String> nameList4 = sections4.stream().map(Section -> Section.getYd()).collect(Collectors.toList());

根据某一字段的条件过滤集合

flows.stream().filter(item -> item.getReadFlag() == 0).count();

List<ServiceAreaInfoBean> collect =serviceAreaInfoList.stream().filter(item -> item.getCode().equals(serviceAreaId)).collect(Collectors.toList());

根据某一字段分组成map集合

Map<String, List<UnitInfoPo>> codeMap =
   units.stream().collect(Collectors.groupingBy(UnitInfoPo::getUnitCode));
   
Map<String,List<Product>> map= prodList.stream().collect(Collectors.groupingBy(item -> {
             if(item.getNum() > 2&&item.getNum()<5) {
                 return "小于3";
             }else {
                 return "other";
             }
         }));

根据某一字段求和

Integer timeRate = radarData.stream().mapToInt(RadarTodayInfo::getTimeRate).sum()

#分组求和
Map<String, Integer> prodMap5 = prodList.stream().collect(Collectors.groupingBy(Product::getCategory, Collectors.summingInt(Product::getNum)));
{啤酒=13, 零食=6}

Map<String, Long> prodMap4 = prodList.stream().collect(Collectors.groupingBy(Product::getCategory, Collectors.counting()));
{啤酒=2, 零食=3}

根据某一字段排序

 gantrysByRoadNum.sort((x,y)->Integer.compare(x.getKm(), y.getKm()));

数组求和

Arrays.stream(radarLaneVo.getLane1()).sum();

根据某一字段去重

 List<RadarBean> lists = list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(()
                -> new TreeSet<>(Comparator.comparing(RadarBean::getRoadCode))), ArrayList::new));

根据某一字段去重

List<OdDdtaBean> distinctClass = odDdtaBeans.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(()
                -> new TreeSet<>(Comparator.comparing(o -> o.getOriginCityName() + ";" + o.getDestnCityName()))), ArrayList::new));

按照几个属性拼接分组

        Map<String, List<Product>> prodMap1 = prodList.stream().collect(Collectors.groupingBy(item -> item.getCategory() + "_" + item.getName()));

联合其他收集器

     Map<String, Set<String>> prodMap7 = prodList.stream().collect(Collectors.groupingBy(Product::getCategory, Collectors.mapping(Product::getName, Collectors.toSet())));

collect

将流转化为其他形式,常用的List,Set、Map、Collection

// 转为list
List<String> nameList = prodList.stream().map(item -> item.getName()).collect(Collectors.toList());

// 转为Set
Set<String> nameSet = prodList.stream().map(item -> item.getName()).collect(Collectors.toSet());

// 转为Map
Map<Long, Product> idMap = prodList.stream().collect(Collectors.toMap(Product::getId,Functions.identity()));

// 转为LinkedList
prodList.stream().map(item -> item.getName()).collect(Collectors.toCollection(LinkedList::new));

//统计总数
Long count = prodList.stream().collect(Collectors.counting());

// 分组
Map<Long, List<Product>> listMap = prodList.stream().collect(Collectors.groupingBy(Product::getId));

// 拼接
String nameJoin = prodList.stream().map(Product::getName).collect(Collectors.joining());

Java处理百分比

import java.text.NumberFormat;
public class test2 {
	public static void main(String[] args) {
		int num=20;
		int nummber=100;
		int s=(num*100/nummber);
		//System.out.println(s);
		
		int diliverNum=3;//举例子的变量
		int queryMailNum=8;//举例子的变量
		// 创建一个数值格式化对象   
		NumberFormat numberFormat = NumberFormat.getInstance();   
		// 设置精确到小数点后2位   
		numberFormat.setMaximumFractionDigits(0);   
		String result = numberFormat.format((float)diliverNum/(float)queryMailNum*100);
		System.out.println(result);
	}
}
Map集合遍历、排序
package com.company;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class map {
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("1", "value1");
        map.put("2", "value2");
        map.put("3", "value3");

        //第一种:普遍使用,二次取值
        System.out.println("通过Map.keySet遍历key和value:");
        for (String key : map.keySet()) {
            System.out.println("key= "+ key + " and value= " + map.get(key));
        }

        System.out.println("通过Map.entrySet使用iterator遍历key和value:");
        Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, String> entry = it.next();
            System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
        }

        //第三种:推荐,尤其是容量大时
        System.out.println("通过Map.entrySet遍历key和value");
        for (Map.Entry<String, String> entry : map.entrySet()) {
            System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
        }

        //第四种
        System.out.println("通过Map.values()遍历所有的value,但不能遍历key");
        for (String v : map.values()) {
            System.out.println("value= " + v);
        }
    }
}
    /**map集合排序--车道
     * @param map*/
    public static Map<String, List<RadarLaneInfo>> sortMapFromKeyLane(Map<String, List<RadarLaneInfo>> map){
        Map<String, List<RadarLaneInfo>> map2 = new TreeMap<>(
                new Comparator<String>() {
                    public int compare(String obj1, String obj2) {
                        //升序排序(反过来就是降序排序)
                        return obj1.compareTo(obj2);
                    }
                });
        for (Map.Entry<String,  List<RadarLaneInfo>> entry : map.entrySet()) {
            String key = entry.getKey();
            List<RadarLaneInfo> value = entry.getValue();
            map2.put(key, value);
        }
        return map2;
    }
}

文件上传

 @PostMapping("/SingleFile/upload")
    public String SingleFileUpLoad(HttpServletRequest request, @RequestParam(value = "file", required = false) MultipartFile[] multipartFile,
                                   String brigadeId, EquipmentRepair equipmentRepair) throws IOException, QSException {
        //判断文件是否为空
        if (multipartFile.length != 0) {
            String imgDir = request.getSession().getServletContext().getRealPath("/").replace("qwpt", "sb_upload");
            File files = new File(imgDir);
            if (!files.exists()) {
                files.mkdirs();
            }
            //获取大队名称
            String brigadeName = equipmentRepairService.queryBrigadeName(brigadeId);
            String[] str = new String[3];
            int num = 0;
            //图片存入青云服务器
            for (MultipartFile multipartFile1 : multipartFile) {
                String picName = "sb_" + Tools.getUUID() + System.currentTimeMillis() + ".jpg";
                String savePath = imgDir + picName;
                File file = new File(savePath);
                multipartFile1.transferTo(file);
                String newObjectName = QingStorUtil.getNewObjectName("qwpt_sb", brigadeName, picName);
                QingStorUtil.uploadInputFile(file, newObjectName);
                str[num] = newObjectName;
                num++;
            }

多线程的使用

自定义线程池

/**
     * @Description 创建线程池
     * @param poolName 线程池名称
     * @param coreSize 核心线程数
     * @param maxSize 最大线程数
     * @param queueSize 阻塞队列大小(线程池无法获取线程执行任务时对应任务会进入队列中等待执行)
     * @return 线程对象
     * @Author XUWZ
     * @Date 2021年1月11日 下午4:36:38
     */
    public static ThreadPoolExecutor createThreadPool(String poolName, int coreSize, int maxSize, int queueSize) {
        return new CustomThreadPoolExecutor(coreSize, maxSize, 0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(queueSize), new NamedThreadFactory(poolName),
                new logedCallerRunsPolicy(poolName));
    }
private static final ThreadPoolExecutor THREADPOOLType = ThreadPoolUtil
            .createThreadPool("DEALSCOPECONGESTION_THREADPOOL", 30, 30, 100);
    private static final ThreadPoolExecutor THREADPOOLLane = ThreadPoolUtil
            .createThreadPool("DEALSCOPECONGESTION_THREADPOOL", 30, 30, 100);

创建线程

 for(RadarBean bean:radar){
            String roadCode = bean.getCode();
            /**车型流量统计*/
            Future<List<VehicleTypeInfo>> submit = THREADPOOLType.submit(new VehicleTypeInfos(unitCode, roadCode, startTime,endTimes));
            /**车道流量统计*/
            Future<VehicleLaneInfo> submitLane = THREADPOOLType.submit(new VehicleLane(unitCode, roadCode, startTime,endTimes));
        }

创建线程的class类,继承callable

/**车型导出统计*/
    public class  VehicleTypeInfos implements Callable<List<VehicleTypeInfo>> {
        private final String unitCode;
        private final String radarCode;
        private final String startTime;
        private final String endTime;
        public VehicleTypeInfos(String unitCode, String radarCode, String startTime, String endTime) {
            this.unitCode = unitCode;
            this.radarCode = radarCode;
            this.startTime = startTime;
            this.endTime = endTime;
        }
        @Override
        public List<VehicleTypeInfo> call() {
            List<RadarInfoAll> modelFlowStatisDay = statisService.getModelFlowStatisDays(unitCode, radarCode, startTime,endTime);
            return list;
        }
    }

JAVA8简单线程

 ExecutorService exc = Executors.newFixedThreadPool(200);

Callable<gantryTotalBean> query = query( startTime, endTime, dateType, json);
            Future<gantryTotalBean> submit = exc.submit(query);
            gantryTotalBean bean = submit.get();

 public Callable<gantryTotalBean> query(String startTime,String endTime,String dateType,JSONObject json){
        //申请单个线程执行类
        Callable<gantryTotalBean> myCallable = new Callable<gantryTotalBean>() {
            @Override
            public gantryTotalBean call() throws Exception {
                gantryTotalBean bean = new gantryTotalBean();
                
                return bean;
            }
        };
        return myCallable;
    }

读取配置文件转换成实体类

@Component
@ConfigurationProperties(prefix = "unitconfig")
@Data
public class UnitConfig {
    private Map<String, Param> configMap;
    @Data
    public static class Param {
        private String dataFilterClass;
        private String tollstationCityId;
        private String cityNameAbbreviate;
        private String roadConditionOrgCode;
        private String roadAccidentOrgCode;
        private String policeCarNumPrefix;
        private String rescueCarNumPrefix;
        private String videoListOrgCode;
        private String vmsListOrgCode;
        private String roadDistrictCode;
        private String todayAccidentCode;
        private String caiyunDataOrgCode;
    }
}

配置文件

unitconfig:
  configMap:
    TZ_VMS:
      dataFilterClass: ""
      tollstationCityId: ""
      cityNameAbbreviate: ""
      roadConditionOrgCode: ""
      roadAccidentOrgCode: ""
      policeCarNumPrefix: "M"
      rescueCarNumPrefix: "苏"
      videoListOrgCode: ""
      vmsListOrgCode: ""
      todayAccidentCode: ""
      roadDistrictCode: ""
      caiyunDataOrgCode: ""
    LX_DLL:
      dataFilterClass: ""
      tollstationCityId: ""
      cityNameAbbreviate: "Z"
      roadConditionOrgCode: ""
      roadAccidentOrgCode: ""
      policeCarNumPrefix: "苏C"
      rescueCarNumPrefix: "苏C"
      videoListOrgCode: ""
      vmsListOrgCode: ""
      todayAccidentCode: ""
      roadDistrictCode: ""
      caiyunDataOrgCode: ""

时间的处理(Hutoll)

package cn.microvideo.flowac.sys.util;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.microvideo.flowac.module.rttraffic.entity.RadarInfoAll;
import cn.microvideo.flowac.module.rttraffic.entity.RadarLaneInfo;

import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class HutoolDateUtil {
    /**
     * 获取当前时间
     */
    public static String nowDateTime() {
        return DateUtil.now();
    }

    /**
     * 获取一天的开始时间和结束时间
     */
    public static String[] beginOfDay(String time) {
        Date date = DateUtil.parse(time);
        Date beginOfDay = DateUtil.beginOfDay(date);
        Date endOfDay = DateUtil.endOfDay(date);
        String[] str = new String[2];
        str[0] = String.valueOf(beginOfDay);
        str[1] = String.valueOf(endOfDay);
        return str;
    }

    /**
     * 字符串转日期
     */
    public static Date tranforDate(String dateStr) {
        return DateUtil.parse(dateStr, "yyyy-MM-dd HH:mm:ss");
    }

    /**
     * 日期时间偏移
     */
    public static String timeOffset(String dateStr, Integer number) {
        Date date = DateUtil.parse(dateStr);
        DateTime newDate2 = DateUtil.offsetDay(date, number);
//        DateTime newDate3 = DateUtil.offsetHour(date, -3);
        return newDate2.toString();
    }

    /**
     * 计算时间差--天
     */
    public static long timeDifference(String startTime, String endTime) {

        Date date1 = DateUtil.parse(startTime);
        Date date2 = DateUtil.parse(endTime);
        long betweenDay = DateUtil.between(date1, date2, DateUnit.DAY);
        return betweenDay;
    }

    /**
     * 计算时间差--小时
     */
    public static int timeDifferenceHour(String startTime, String endTime) {

        Date date1 = DateUtil.parse(startTime);
        Date date2 = DateUtil.parse(endTime);
        int betweenDay = (int) DateUtil.between(date1, date2, DateUnit.HOUR);
        return betweenDay;
    }

    /**
     * 输出按天的数组
     */
    public static String[] monthArray(String time, int num) {
        String[] str = new String[num];
        str[0] = time.substring(0, 8);
        for (int i = 1; i < num; i++) {
            Date date = DateUtil.parse(time);
            DateTime newDate2 = DateUtil.offsetDay(date, i);
            String timeDays = HutoolDateUtil.timeEmpty(newDate2.toString()).substring(0, 8);
            str[i] = timeDays;
        }
        return str;
    }

    /**
     * 输出按天的数组
     */
    public static String[] monthArrays(String time, int num) {
        String[] str = new String[num+1];
        str[0] = time.substring(0, 8);
        for (int i = 1; i <= num; i++) {
            Date date = DateUtil.parse(time);
            DateTime newDate2 = DateUtil.offsetDay(date, i);
            String timeDays = HutoolDateUtil.timeEmpty(newDate2.toString()).substring(0, 8);
            str[i] = timeDays;
        }
        return str;
    }

    /**
     * 输出一天的小时数组
     */
    public static String[] dayArray(String time, int num) {
        String[] str = new String[num];
        str[0] = time;
        for (int i = 1; i < num; i++) {
            Date date = DateUtil.parse(time);
            DateTime newDate3 = DateUtil.offsetHour(date, i);
            String times = HutoolDateUtil.timeEmpty(newDate3.toString());
            str[i] = times;
        }
        return str;
    }
    /**
     * 输出一天的小时数组--导出
     */
    public static String[] dayArrayExport(String time, int num) {
        String[] str = new String[num];
        for (int i = 0; i < num; i++) {
            Date date = DateUtil.parse(time);
            DateTime newDate3 = DateUtil.offsetHour(date, i);
            String format = DateUtil.format(newDate3, "yyyy-MM-dd HH:mm:ss");
            str[i] = format;
        }
        return str;
    }

    /**
     * 时间转时间戳
     */
    public static String timeStamp(String time) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = simpleDateFormat.parse(time);
        long ts = date.getTime();
        String res = String.valueOf(ts);
        return res;
    }

    /**
     * 时间格式转化--输出20211207110000
     */
    public static String timeEmpty(String time) {
        return time.replaceAll("-", "").replaceAll(":", "").replaceAll(" ", "");
    }

    /**
     * 输出一天的小时数组
     */
    public static String[] timeHour(String time) {
        Date date = DateUtil.parse(time + " 00:00:00");
        String[] str = new String[24];
        for (int i = 0; i < 24; i++) {
            DateTime newDate = DateUtil.offsetHour(date, i);
            str[i] = String.valueOf(newDate.toString().substring(11, 16));
        }
        return str;
    }

    /**
     * 输出当前时间的小时数组-- 10:00-11:00
     */
    public static String[] timeHours(String time) {
        Date date = DateUtil.parse(time);
        String[] str = new String[2];
        str[0] = date.toString().substring(11, 13);
        DateTime newDate = DateUtil.offsetHour(date, 1);
        str[1] = newDate.toString().substring(11, 13);
        return str;
    }

    /**
     * 比较两时间大小
     */
    public static Integer compareTime(String startTime, String endTime) {
        Date date1 = DateUtil.parse(startTime);
        Date date2 = DateUtil.parse(endTime);
        if (date1.getTime() < date2.getTime()) {
            return 0;
        } else {
            return 1;
        }
    }

    /**
     * 计算百分比
     */
    public static String numberFormat(int int1, int int2) {
        // 创建一个数值格式化对象
        NumberFormat numberFormat = NumberFormat.getInstance();
        // 设置精确到小数点后2位
        numberFormat.setMaximumFractionDigits(0);
        String result = numberFormat.format((float) int1 / (float) int2 * 100);
        return result;
    }

excel导出图片

    response.setCharacterEncoding("UTF-8");
    response.setContentType("application/x-download");
    String fileName;
    fileName = URLEncoder.encode("车辆统计", "UTF-8");
    response.addHeader("Content-Disposition", "attachment;filename=" + fileName+ ".xls");
   
    XSSFWorkbook wb = new XSSFWorkbook();
    XSSFSheet sheet = wb.createSheet("ss");

   // 插入 PNG 图片至 Excel
    InputStream is = new FileInputStream("C:\\Users\\HP\\Desktop\\vpn连接文档\\下载.jpg");
    byte[] bytes = IOUtils.toByteArray(is);
    int pictureIdx = wb.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);
    CreationHelper helper = wb.getCreationHelper();
    Drawing drawing = sheet.createDrawingPatriarch();
    ClientAnchor anchor = helper.createClientAnchor();

            // 图片插入坐标
    anchor.setCol1(6); //列
    anchor.setRow1(0); //行
   // 插入图片
    Picture pict = drawing.createPicture(anchor, pictureIdx);
    pict.resize();

    OutputStream out = response.getOutputStream();
    wb.write(out);
    out.close();

  // 新建一输出文件流
    FileOutputStream fOut = new FileOutputStream("D:\\test.xlsx");
  // 把相应的Excel 工作簿存盘
    wb.write(fOut);
    fOut.flush();
  // 操作结束,关闭文件
    fOut.close();
    System.out.println("文件生成...");
    @RequestMapping("/exportPic")
    @ResponseBody
    public void exportPic(HttpServletResponse response)  {
        try{
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/x-download");
            String fileName;
            fileName = URLEncoder.encode("车辆统计", "UTF-8");
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName+ ".xls");

            XSSFWorkbook wb = new XSSFWorkbook();
            XSSFSheet sheet = wb.createSheet("ss");

            // 插入 PNG 图片至 Excel
            HttpClient client = new HttpClient();
            GetMethod get = new GetMethod("https://ga2.jchc.cn/qwpt/showPic?objName=qwpt_sb/%E6%B1%9F%E8%8B%8F%E7%9C%81%E4%BA%A4%E8%AD%A6%E6%80%BB%E9%98%9F/2021/11/24sb_d41f567f8c8042f0a0a0e25bcbec821a1637734758557.jpg");
            client.executeMethod(get);
            InputStream is = get.getResponseBodyAsStream();

            byte[] bytes = IOUtils.toByteArray(is);
            int pictureIdx = wb.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);
            CreationHelper helper = wb.getCreationHelper();
            Drawing drawing = sheet.createDrawingPatriarch();
            ClientAnchor anchor = helper.createClientAnchor();

            // 图片插入坐标
            anchor.setCol1(6); //列
            anchor.setRow1(0); //行
            // 插入图片
            Picture pict = drawing.createPicture(anchor, pictureIdx);
            pict.resize();

            OutputStream out = response.getOutputStream();
            wb.write(out);
            out.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

调整图片大小

public static void main(String[] args) {
        FileOutputStream fileOut = null;
                 BufferedImage bufferImg = null;
                 // 先把读进来的图片放到一个ByteArrayOutputStream中,以便产生ByteArray
                 try {
                     ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
                     HttpClient client = new HttpClient();
                     GetMethod get = new GetMethod("https://ga2.jchc.cn/qwpt/showPic?objName=qwpt_sb/%E6%B1%9F%E8%8B%8F%E7%9C%81%E4%BA%A4%E8%AD%A6%E6%80%BB%E9%98%9F/2021/11/24sb_d41f567f8c8042f0a0a0e25bcbec821a1637734758557.jpg");
                     client.executeMethod(get);
                     InputStream is = get.getResponseBodyAsStream();
                     bufferImg = ImageIO.read(is);
//                   bufferImg = ImageIO.read(new File("C:\\Users\\HP\\Desktop\\vpn连接文档\\下载.jpg"));
                     ImageIO.write(bufferImg, "jpg", byteArrayOut);

                      XSSFWorkbook wb = new XSSFWorkbook();
                        XSSFSheet sheet1 = wb.createSheet("test picture");
                        // 画图的顶级管理器,一个sheet只能获取一个(一定要注意这点)
                     XSSFDrawing drawingPatriarch = sheet1.createDrawingPatriarch();
                     for (int i = 0; i < 3; i++) {
                               // anchor主要用于设置图片的属性
                            XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 1023, 250, (short) 1, 1+i*10, (short) 5, 8+i*10);
                             // 插入图片
                         drawingPatriarch.createPicture(anchor, wb.addPicture(byteArrayOut.toByteArray(), XSSFWorkbook.PICTURE_TYPE_JPEG));
                           }
                        fileOut = new FileOutputStream("D:\\Excel.xls");
                       // 写入excel文件
                     wb.write(fileOut);
                        System.out.println("----Excle文件已生成------");
                   } catch (Exception e) {
                       e.printStackTrace();
                 } finally {
                       if (fileOut != null) {
                              try {
                                   fileOut.close();
                               } catch (IOException e) {
                                    e.printStackTrace();
                                }
                         }
                    }
           }

map函数式接口,代替if_else

用上了Java8的新特性lambda表达式

  • 判断条件放在key中
  • 对应的业务逻辑放在value中
@Service
public class QueryGrantTypeService {
 
    @Autowired
    private GrantTypeSerive grantTypeSerive;
    private Map<String, Function<String,String>> grantTypeMap=new HashMap<>();

    /**
     *  初始化业务分派逻辑,代替了if-else部分
     *  key: 优惠券类型
     *  value: lambda表达式,最终会获得该优惠券的发放方式
     */
    @PostConstruct
    public void dispatcherInit(){
        grantTypeMap.put("红包",resourceId->grantTypeSerive.redPaper(resourceId));
        grantTypeMap.put("购物券",resourceId->grantTypeSerive.shopping(resourceId));
        grantTypeMap.put("qq会员",resourceId->grantTypeSerive.QQVip(resourceId));
    }
 
    public String getResult(String resourceType){
        //Controller根据 优惠券类型resourceType、编码resourceId 去查询 发放方式grantType
        Function<String,String> result=getGrantTypeMap.get(resourceType);
        if(result!=null){
         //传入resourceId 执行这段表达式获得String型的grantType
            return result.apply(resourceId);
        }
        return "查询不到该优惠券的发放方式";
    }
}

如果单个 if 语句块的业务逻辑有很多行的话,我们可以把这些 业务操作抽出来,写成一个单独的Service,即:

//具体的逻辑操作

@Service
public class GrantTypeSerive {

    public String redPaper(String resourceId){
        //红包的发放方式
        return "每周末9点发放";
    }
    public String shopping(String resourceId){
        //购物券的发放方式
        return "每周三9点发放";
    }
    public String QQVip(String resourceId){
        //qq会员的发放方式
        return "每周一0点开始秒杀";
    }
}

入参String resourceId是用来查数据库的,这里简化了,传参之后不做处理。

用http调用的结果:

@RestController
public class GrantTypeController {
    @Autowired
    private QueryGrantTypeService queryGrantTypeService;
    @PostMapping("/grantType")
    public String test(String resourceName){
        return queryGrantTypeService.getResult(resourceName);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值