三级分类 递归 存入Redis

文章描述了一种使用SpringBoot和MyBatis实现的商品三级分类同步逻辑,利用Java8StreamAPI的peek()和sorted()方法对数据进行预处理,并将结果存储到Redis缓存中。
摘要由CSDN通过智能技术生成

 

实体类 由于用到递归所以请看标红

/**
* 商品三级分类
* @TableName mall_product_type_info
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class MallProductTypeInfo implements Serializable {

    /**
    * 分类id
    */
    @NotNull(message="[分类id]不能为空")
    @ApiModelProperty("分类id")
    private Long catId;
    /**
    * 分类名称
    */
    @ApiModelProperty("分类名称")
    private String name;
    /**
    * 父分类id
    */
    @ApiModelProperty("父分类id")
    private Long parentCid;
    /**
    * 层级
    */
    @ApiModelProperty("层级")
    private Integer catLevel;
    /**
    * 是否显示[0-不显示,1显示]
    */
    @ApiModelProperty("是否显示[0-不显示,1显示]")
    private Integer showStatus;
    /**
    * 排序
    */
    @ApiModelProperty("排序")
    private Integer sort;
    /**
    * 图标地址
    */
    @ApiModelProperty("图标地址")
    private String icon;
    /**
    * 计量单位
    */
    @ApiModelProperty("计量单位")
    private String productUnit;
    /**
    * 商品数量
    */
    @ApiModelProperty("商品数量")
    private Integer productCount;
    /**
    * 乐观锁
    */
    @ApiModelProperty("乐观锁")
    private Integer revision;

    /**
     * 子分类
     */
    @TableField(exist = false)
    private List<MallProductTypeInfo> children;
}
package com.spider.sync;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spider.mapper.ClassificationMapper;
import com.spider.pojo.MallProductTypeInfo;
import com.spider.util.JsonUtil;
import com.spider.util.RedisCacheUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Configuration;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

import static java.awt.SystemColor.menu;

/**
 * 📝 TODO 三级分类启动同步
 * 🕟 2024/2/22 8:54
 * 👦 Lxj
 */
@Configuration
public class RunnerSync implements ApplicationRunner {
    @Autowired
    private ClassificationMapper classificationMapper;

    @Autowired
    private RedisCacheUtil redisCacheUtil;

    private static String MALL_PRODUCT_TYPE_INFO_REDIS = "mallProductTypeInfoList";


    @Override
    public void run(ApplicationArguments args) throws Exception {

        //获取数据
        List<MallProductTypeInfo> mallProductTypeInfoList = classificationMapper.selectList(new LambdaQueryWrapper<>());


        List<MallProductTypeInfo> typeInfoList = mallProductTypeInfoList.stream().filter(mallProductTypeInfo -> {
            //一级分类
            return mallProductTypeInfo.getParentCid().equals(0L);
        }).peek(menu ->
                //子分类
                menu.setChildren(getChildren(menu, mallProductTypeInfoList))
        ).sorted(
                //catId排序
                Comparator.comparing(MallProductTypeInfo::getCatId)
        ).collect(Collectors.toList());

        //json存入redis
        String jsonString = JsonUtil.toJSONString(typeInfoList);

        redisCacheUtil.setCacheObject(MALL_PRODUCT_TYPE_INFO_REDIS,jsonString);
    }

    /**
     * 获取子分类
     * @param root 当前对象
     * @param mallProductTypeInfoList 集合
     * @return
     */
    public List<MallProductTypeInfo> getChildren(MallProductTypeInfo root,
                                                 List<MallProductTypeInfo> mallProductTypeInfoList) {
        List<MallProductTypeInfo> children = mallProductTypeInfoList.stream().filter(mallProductTypeInfo -> {
            //子分类
            return mallProductTypeInfo.getParentCid().equals(root.getCatId());
        }).peek(menu ->
                //递归 获取子分类
                menu.setChildren(getChildren(menu, mallProductTypeInfoList))
        ).sorted(
                //catId排序
                Comparator.comparing(MallProductTypeInfo::getCatId)
        ).collect(Collectors.toList());

        //最后一级结束递归
        if(children == null || children.size()==0){
            return null;
        }

        return children;
    }


}

peek()sorted() 都是 Java 8 中 Stream API 提供的中间操作(intermediate operation)方法,它们可以对一个 Stream 对象进行一些处理并返回一个新的 Stream 对象。

  • peek(Consumer<? super T> action) 方法允许你在流的每个元素上执行一些操作,而不会改变流的内容。它会将流的每个元素传递给参数 action 执行,并返回原始的流对象。比如在你提供的代码中,peek() 方法将每个 MallProductTypeInfo 对象设置了子元素后返回了原始的流对象。需要注意的是 peek() 方法不应该用来修改流中的元素,它的主要作用是允许你在流的每个元素上执行一些额外的操作,比如打印调试信息等。

  • sorted(Comparator<? super T> comparator) 方法可以按照指定的排序规则对流进行排序,并返回一个新的排序后的流对象。排序规则由参数 comparator 指定,它是一个函数接口,用于比较流中的元素。在你提供的代码中,sorted() 方法使用了 Comparator.comparing() 方法创建了一个按照 catId 属性排序的比较器,并将其传递给 sorted() 方法进行排序。

需要注意的是,这两个方法都是中间操作(intermediate operation),它们不会对流的元素进行实际的操作,只是返回一个新的流对象。只有当你调用流的终端操作(terminal operation)方法时,整个流才会被处理并产生结果。在你提供的代码中,collect(Collectors.toList()) 方法是一个终端操作,它将排序后的流转换为一个 List 对象并返回。

 json在线解析网址

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java中实现无限分类递归可以使用递归函数来实现。下面是一个简单的示例代码: ```java public class RecursiveCategory { // 定义一个分类类 static class Category { String name; List<Category> subCategories; public Category(String name, List<Category> subCategories) { this.name = name; this.subCategories = subCategories; } } // 递归打印分类及其所有子分类 public static void printCategories(Category category, int level) { for (int i = 0; i < level; i++) { System.out.print("--"); } System.out.println(category.name); if (category.subCategories != null) { for (Category subCategory : category.subCategories) { printCategories(subCategory, level + 1); } } } public static void main(String[] args) { // 创建分类对象 Category laptop = new Category("Laptop", null); Category windows = new Category("Windows", null); Category mac = new Category("Mac", null); Category linux = new Category("Linux", null); Category os = new Category("Operating System", Arrays.asList(windows, mac, linux)); Category programming = new Category("Programming", null); Category java = new Category("Java", null); Category python = new Category("Python", null); Category languages = new Category("Programming Languages", Arrays.asList(java, python)); // 构建分类层次结构 laptop.subCategories = Arrays.asList(os); programming.subCategories = Arrays.asList(languages); // 打印分类层次结构 printCategories(laptop, 0); printCategories(programming, 0); } } ``` 以上代码实现了一个简单的无限分类递归示例。它定义了一个`Category`类,每个类别可以有多个子类别。通过递归函数`printCategories`可以打印出分类及其所有子分类。在`main`方法中创建了一些分类对象,并构建了分类的层次结构,最后通过调用`printCategories`方法打印出分类层次结构。你可以根据自己的需求进行修改和扩展。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值