3月技术点01

  
序号
标题
内容
1

多线程新方式应用

 CompletableFuture<List<CbWareSkuRespDTO>> queryWareSkuFuture = CompletableFuture.supplyAsync(() -> 

                mallClient.post2List(CbApiPathConstant.WARE_SKU_PATH, cbWareSkuReqDTO, CbWareSkuRespDTO.class), executor); 

        queryWareSkuFuture.handle((BiFunction<List<CbWareSkuRespDTO>, Throwable, Object>) (cbWareSkuRespDTOS, throwable) -> { 

            cbWareSkuRespDTOs.addAll(cbWareSkuRespDTOS); 

            return cbWareSkuRespDTOS; 

        }); 

        CompletableFuture<List<CbWareServiceContentRespDTO>> queryServiceContentFuture = CompletableFuture.supplyAsync(() -> 

                mallClient.post2List(CbApiPathConstant.WARE_SERVICE_CONTENT_PATH, null, CbWareServiceContentRespDTO.class), executor); 

        queryServiceContentFuture.handle((BiFunction<List<CbWareServiceContentRespDTO>, Throwable, Object>) (cbWareServiceContentRespDTOS, throwable) -> { 

            cbWareServiceContentRespDTOs.addAll(cbWareServiceContentRespDTOS); 

            return cbWareServiceContentRespDTOS; 

        }); 

        CompletableFuture.allOf(queryWareSkuFuture, queryServiceContentFuture).whenComplete((v, th) -> { 

            CbWareSkuRespDTO cbWareSkuRespDTO = cbWareSkuRespDTOs.stream().filter(wareSku -> wareSku.getSkuNo().equals(reqDTO.getSkuId())).findFirst().orElse(null); 

            atomicReference.set(this.convertOsWareRespDTO(cbWareSkuRespDTO, cbWareServiceContentRespDTOs)); 

        }).join(); 

2

创建 hashMap 方式,设置容量时已考虑加载因子

CollectionUtils.newHashMap(10);  org.srping.framework.util 5.3 以后版本

3

原子性设置 引用对象

AtomicReference<OsWareSkuRespDTO> atomicReference = new AtomicReference<>(new OsWareSkuRespDTO());

4

枚举中可加,可以省去写构造方法

类加注解 @AllArgsConstructor

5

枚举中根据 value  找 desc

public static OsWareDeliveryTypeEnum getEnumByCode(Integer code) {

        return Stream.of(values()).filter(element -> element.getCode().equals(code)).findFirst().orElse(null);

    }

6、

Hutool 组件使用说明

hashMap to bean  字段名不一致情况

 

pblic static void main(String[] args) {

    HashMap<String, Object> map = CollUtil.newHashMap();

    map.put("a_id", 1);

    map.put("b_name", "张三");

    // 设置别名,用于对应bean的字段名

    HashMap<String, String> mapping = CollUtil.newHashMap();

    mapping.put("a_id", "id");

    mapping.put("b_name", "name");

    TestBean bean = BeanUtil.toBean(map, TestBean.class, CopyOptions.create().setFieldMapping(mapping));

    System.out.println(bean);

}

7、  字符串处理--Hutool  // 填充字符串模板

String format = StrUtil.format("a的值为{a}, b的值为{b}", Map.of("a", "aValue", "b", "bValue"));

8  集合框架使用--Hutool  

// 新建一个HashSet

Set<Integer> hashSet = CollUtil.newHashSet(1, 2, 3);

Set<Integer> linkedHashSet = CollUtil.newLinkedHashSet(4, 2, 3); 

// 两个集合取交集

Collection<Integer> intersection = CollUtil.intersection(hashSet, linkedHashSet); 

// 两个集合取并集

Collection<Integer> union = CollUtil.union(hashSet, linkedHashSet); 

// 两个集合取差集

Collection<Integer> disjunction = CollUtil.disjunction(hashSet, linkedHashSet); 

// 判断一个集合是否为null或空集

boolean empty = CollUtil.isEmpty(hashSet); 

// 创建一个ArrayList

List<Integer> arrayList = ListUtil.toList(1, 2, 3); 

// 创建一个LinkedList

List<Integer> linkedList = ListUtil.toLinkedList(1, 2, 3);

9 请求HttpClient,请求失败时,多次发起请求

HttpClient client = new HttpClient();
PostMethod myPost = new PostMethod(url);
if (StringUtils.isNotBlank(sessionKey)) {
Header header = new Header();
header.setName("Session-Key");
header.setValue(sessionKey);
myPost.setRequestHeader(header);
}
client.getParams().setSoTimeout(300 * 1000);
String responseString = null;

//重试策略;如果http请求出错,默认三次重试
myPost.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
myPost.setRequestEntity(new StringRequestEntity(jsonStr, "application/json", "utf-8"));
int statusCode = client.executeMethod(myPost);

if (statusCode == HttpStatus.SC_OK) {
BufferedInputStream bis = new BufferedInputStream(myPost.getResponseBodyAsStream());
byte[] bytes = new byte[1024];
 ByteArrayOutputStream bos = new ByteArrayOutputStream();
int count = 0;
while ((count = bis.read(bytes)) != -1) {
bos.write(bytes, 0, count);
 }
byte[] strByte = bos.toByteArray();
 responseString = new String(strByte, 0, strByte.length, "utf-8");
 bos.close();
 bis.close();
}
  将数组转换成 数据流 可执行filter,map 等
Stream.of(new Integer[]{1,2,4,5})
  AtomicReference 的应用

// 订单商品总数
AtomicReference<Integer> totalCount = null;
totalCount.updateAndGet(v -> v + detail.getCount());

:重点使用特性应用在lamda表达式 可以修改特性, 正常非final 变量不可变在lamda表达式 foreach中。

  字符串拼接
StrUtil.format("{}{}", NumberUtil.decimalFormat("#.##", distance), "m");
  stream聚合使用
BigDecimal discountAmountTotal = cbCanUseCouponList.stream().filter(e -> e.getDiscountAmount() != null && e.getSelected())
.map(e -> BigDecimal.valueOf(e.getDiscountAmount())).reduce(BigDecimal.ZERO, BigDecimal::add);
  字符串通配符匹配

PatternMatchUtils.simpleMatch((/api/mall/**).split(StrUtil.COMMA), uri);
可以匹配 /api/mall/categoryList ,/api/mall/list 等

  与当前时间比较
LocalDateTime.parse(notice.getBeginDate()
, DateTimeFormatter.ofPattern(DatePattern.UTC_MS_WITH_ZONE_OFFSET_PATTERN)).isBefore(LocalDateTime.now())
 
list根据列 取最小
UserInfo user=   listUser.stream().min((o1,o2)->o1.getId().compareTo(o2.getId())).orElse(null);
UserInfo user2=listUser.stream().min(new Comparator<UserInfo>() {
@Override
 public int compare(UserInfo o1, UserInfo o2) {
if(o1==null || o2==null){
return 0;
 }
return o1.getId().compareTo(o2.getId());
 }
}).orElse(null);
System.out.println("user.toString() = " + user.toString());
  do/dto/vo 说明
  • 数据对象:xxxDO,xxx即为数据表名

  • 数据传输对象:xxxDTO,xxx为业务领域相关的名称。

  • 展示对象:xxxVO,xxx一般为网页名称。

  • POJO是DO/DTO/BO/VO的统称,禁止命名成xxxPOJO。

   restTemplate.getForObject 返回实体 中泛型属性 原ArrayList 变成 LinkedHashMap
  • BaseResult result = restTemplate.getForObject(url, BaseResult.class);响应数据中属性 变成为Linkedhashmap,
  • 解决方式
  •  1、对result 中linkedHashMap 再次转换 如用 Beanutil.copypropites(source,target)
  •  2、 转换调用方法和参数:   
  • ParameterizedTypeReference<List<MyModelClass>> typeRef = new ParameterizedTypeReference<List<MyModelClass>>() {
    };
    ResponseEntity<List<MyModelClass>> responseEntity = restTemplate.exchange(url, HttpMethod.POST, new HttpEntity<>(mvm), typeRef);
    List<MyModelClass> myModelClasses = responseEntity.getBody();

posted @ 2023-12-07 15:07  xiaoBai1001  阅读(9)  评论(0编辑  收藏  举报