基础篇小结

开发工具版本

virtualbox:6.1.32
vagrant:2.2.19
docker:20.0.12
sqlyog:13.1.1
mysql 8
idea: 2021.3.2
vscode: 1.65.1.0
git:2.35.1.2
nacos:1.4.1

在这里插入图片描述

微服务使用

nacos注册中心

1.导入依赖

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>

2.写配置

spring:
  datasource:
    password: root
    username: root
    url: jdbc:mysql://xxx:3306/xxx?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
    driver-class-name: com.mysql.jdbc.Driver

  application:
    name: achangmall-coupon #对应微服务名
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 #nacos地址

3.在每个服务的主入口上标注注解@EnableDiscoveryClient(现在默认不需要标注)

feign

引入feign依赖

		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-openfeign</artifactId>
			<version>3.1.0</version>
		</dependency>

优惠券服务被调用接口
在这里插入图片描述
创建一个接口feign
在这里插入图片描述
标注开启feign客户端并扫描创建的feign接口
在这里插入图片描述
测试

@RequestMapping("member/member")
public class MemberController {
    @Autowired
    private CouponFeignService couponFeignService;

    @GetMapping("/test")
    public R test(){
        MemberEntity memberEntity = new MemberEntity();
        memberEntity.setNickname("还还");

        //远程调用
        R r = couponFeignService.memberCoupon();
        return R.ok().put("member",memberEntity).put("coupon",r.get("list"));
    }
    
    //省略别的接口.........
}

注意这里调用的是新创建的feign接口

nacos配置中心
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-bootstrap</artifactId>
    <version>3.0.3</version>
</dependency>

在coupons项目中创建/src/main/resources/bootstrap.properties ,这个文件是 springboot里规定的,他优先级别application.properties高

coupon.name=huanhuan
coupon.age=18
# 改名字,对应nacos里的配置文件名
spring.application.name=achangmall-coupon
spring.cloud.nacos.config.server-addr=localhost:8848

在这里插入图片描述

nocos里的配置文件
在这里插入图片描述
测试

@Value("${coupon.name}")
private String name;

@Value("${coupon.age}")
private Integer age;

@GetMapping("/test")
public R test(){
    return R.ok().put("name",name).put("age",age);
}

在这里插入图片描述
他似乎还自己开启了热部署

在Controller加上@RefreshScope来动态获取配置数据

spring.cloud.nacos.config.namespace=ed042b3b-b7f3-4734-bdcb-0c516cb357d7 
 # 可以选择对应的命名空间 ,即写上对应环境的命名空间ID
spring.cloud.nacos.config.group=DEFAULT_GROUP  
# 更改配置分组
#加载多配置集
#数据源配置
spring.cloud.nacos.config.ext-config[0].data-id=datasource.yml
spring.cloud.nacos.config.ext-config[0].group=dev
spring.cloud.nacos.config.ext-config[0].refresh=true

#mybaits配置
spring.cloud.nacos.config.ext-config[1].data-id=mybatis.yml
spring.cloud.nacos.config.ext-config[1].group=dev
spring.cloud.nacos.config.ext-config[1].refresh=true

#其他配置
spring.cloud.nacos.config.ext-config[2].data-id=other.yml
spring.cloud.nacos.config.ext-config[2].group=dev
spring.cloud.nacos.config.ext-config[2].refresh=true

测试多配置集
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

gateway

在这里插入图片描述

数据库结构

商品数据库
pms_attr;属性表,其中有一个分类id和category关联
在这里插入图片描述
pms_category:分类表
在这里插入图片描述
pms_group:分组表,也有分类id关联分类
在这里插入图片描述
pms_attr_attrgroup_relation:属性分组关联表
在这里插入图片描述
pms_category
在这里插入图片描述
pms_category_brand_relation分类与品牌关联表
在这里插入图片描述
sku大致有三个表,分别为图片保存地址表,主键为skuid,
sku信息info表,保存了一些基本信息,如价格,标题副标题,还有spuid,categoryid,brandid,这样才能唯一定位到一个具体的产品;
还有个销售属性表,有颜色和内存两个不同的属性,保存着attrid和value,主键为skuid。

pms_product_attr_value为基本属性表,以spuid为主键;
pms_spu_info为spu表,有spu的spuid以及品牌分类id以及基本的名字描述时间等信息
然后就剩一些spu的图片描述等表了,以spuid为主键

crud

1.查找所有分类以树形结构返回
@Override
public List<CategoryEntity> listTree() {
    List<CategoryEntity> allList = baseMapper.selectList(null);
    List<CategoryEntity> parentList = allList.stream()
    //过滤得到一级菜单,即所有的父菜单
        .filter(item -> item.getParentCid() == 0)
        .map(item -> {
            item.setChildren(getChildren(item, allList));
            return item;
        }).sorted((item1, item2) -> {
        return item1.getSort() - item2.getSort();
    })
        .collect(Collectors.toList());
    return parentList ;
}

//递归查找所有菜单的子菜单
private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> allList) {
    List<CategoryEntity> lastList = allList.stream()
        .filter(item -> {return root.getCatId().equals(item.getParentCid());})
        .map(item -> {
            item.setChildren(getChildren(item, allList));
            return item;
        })
        .sorted(
        (item1, item2) -> {
            return (item1.getSort()==null?0:item1.getSort()) - (item2.getSort()==null?0:item2.getSort());
        })
        .collect(Collectors.toList());

    return lastList;
}

这里是在网关里配置跨域
在这里插入图片描述
以及进行一些路由配置。
前端展示树形组件,采用el-tree

.<template>
    <el-tree
             :data="data"
             :props="defaultProps"
             @node-click="handleNodeClick"
             ></el-tree>
</template>

<script>
    export default {
        data() {
            return {
                data: [],//获取到后端来的数据,并赋值
                defaultProps: {
                    children: "children",
                    label: "name",
                },
            };
        },
        methods: {
            //获取所有菜单
            getMenus() {
                this.$http({
                    url: this.$http.adornUrl(`/product/category/list/tree`),
                    method: "get",
                }).then((resp) => {
                    this.data = resp.data.list;
                });
            },
            handleNodeClick(data) {
                console.log(data);
            },
        },
        created() {
            this.getMenus();
        },
    };
</script>
2.删除分类接口

后台

/**
* 删除
*/
@RequestMapping("/delete")
public R delete(@RequestBody Long[] catIds){
    categoryService.removeCategory(catIds);
    return R.ok();
}

@Override
public void removeCategory(Long[] catIds) {
    baseMapper.deleteBatchIds(Arrays.asList(catIds));
}

配置逻辑删除
在这里插入图片描述在这里插入图片描述

3.新增分类
@RequestMapping("/save")
public R save(@RequestBody CategoryEntity category){
    categoryService.save(category);

    return R.ok();
}
4.修改分类
//数据回显
@RequestMapping("/info/{catId}")
public R info(@PathVariable("catId") Long catId){
    CategoryEntity category = categoryService.getById(catId);
    return R.ok().put("category", category);
}

回显之后前端改完发送表单数据再修改保存即可

5.拖拽效果
@RestController
@RequestMapping("product/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;
    /**
     * 修改分类
     */
    @RequestMapping("/update/sort")
    // @RequiresPermissions("product:category:update")
    public R update(@RequestBody CategoryEntity[] category){

        categoryService.updateBatchById(Arrays.asList(category));
        return R.ok();
    }

}
6.批量删除
@RequestMapping("/delete")
public R delete(@RequestBody Long[] catIds){
    categoryService.removeCategory(catIds);
    return R.ok();
}

前面部分的 前端代码

.<template>
    <div>
        <el-switch
                   v-model="draggable"
                   active-text="开启拖拽"
                   inactive-text="关闭拖拽"
                   >
        </el-switch>
        <el-button @click="batchSave" v-if="draggable">批量保存</el-button>
        <el-button type="danger" @click="batchDelete">批量删除</el-button>
        <el-tree
                 :data="data"
                 :props="defaultProps"
                 show-checkbox
                 @node-click="handleNodeClick"
                 :expand-on-click-node="false"
                 node-key="catId"
                 :default-expanded-keys="expandedKey"
                 :draggable="draggable"
                 :allow-drop="allowDrop"
                 ref="menuTree"
                 >
            <span class="custom-tree-node" slot-scope="{ node, data }">
                <span>{{ node.label }}</span>
                <span>
                    <el-button
                               v-if="node.level != 3"
                               type="text"
                               size="mini"
                               @click="() => append(data)"
                               >
                        Append
                    </el-button>
                    <el-button
                               v-if="node.childNodes <= 0"
                               type="text"
                               size="mini"
                               @click="() => remove(node, data)"
                               >
                        Delete
                    </el-button>
                    <el-button type="text" size="mini" @click="() => edit(data)">
                        Edit
                    </el-button>
                </span>
            </span></el-tree
            >

        <el-dialog title="提示" :visible.sync="dialogVisible" width="30%">
            <el-form :model="category">
                <el-form-item label="分类名称">
                    <el-input v-model="category.name" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="图标">
                    <el-input v-model="category.icon" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="计量单位">
                    <el-input
                              v-model="category.productUnit"
                              autocomplete="off"
                              ></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitData">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                pCid: [],
                draggable: false,
                updateNodes: [],
                maxLevel: 0,
                dialogType: "", //edit,add
                title: "",
                dialogVisible: false,
                expandedKey: [],
                category: {
                    name: "",
                    parentCid: 0,
                    catLevel: 0,
                    showStatus: 1,
                    sort: 0,
                    icon: "",
                    productUnit: "",
                    catId: null,
                },
                data: [],
                defaultProps: {
                    children: "children",
                    label: "name",
                },
            };
        },
        methods: {
            // 批量删除
            batchDelete() {
                let catIds = [];
                let checkedNodes = this.$refs.menuTree.getCheckedNodes();
                console.log("被选中的元素", checkedNodes);
                for (let i = 0; i < checkedNodes.length; i++) {
                    catIds.push(checkedNodes[i].catId);
                }
                this.$confirm(`是否批量删除【${catIds}】菜单?`, "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                })
                    .then(() => {
                    this.$http({
                        url: this.$http.adornUrl("/product/category/delete"),
                        method: "post",
                        data: this.$http.adornData(catIds, false),
                    })
                        .then(({ data }) => {
                        this.$message({
                            type: "success",
                            message: "菜单批量删除成功!",
                        });
                        // 刷新出新的菜单
                        this.getMenus();
                    })
                        .catch(() => {});
                })
                    .catch(() => {});
            },
            batchSave() {
                this.$http({
                    url: this.$http.adornUrl("/product/category/update/sort"),
                    method: "post",
                    data: this.$http.adornData(this.updateNodes, false),
                })
                    .then(({ data }) => {
                    this.$message({
                        type: "success",
                        message: "菜单顺序修改成功!",
                    });
                    // 刷新出新的菜单
                    this.getMenus();
                    // 设置需要默认展开的菜单
                    this.expandedKey = this.pCid;
                    this.updateNodes = [];
                    this.maxLevel = 0;
                    // this.pCid = 0;
                })
                    .catch(() => {});
            },
            handleDrop(draggingNode, dropNode, dropType, ev) {
                console.log("handleDrop: ", draggingNode, dropNode, dropType);

                //1 当前节点最新的父节点
                let pCid = 0;
                let siblings = null;
                if (dropType == "before" || dropType == "after") {
                    pCid =
                        dropNode.parent.data.catId == undefined
                        ? 0
                    : dropNode.parent.data.catId;
                    siblings = dropNode.parent.childNodes;
                } else {
                    pCid = dropNode.data.catId;
                    siblings = dropNode.childNodes;
                }
                this.pCid.push(pCid);
                //2 当前拖拽节点的最新顺序
                for (let i = 0; i < siblings.length; i++) {
                    if (siblings[i].data.catId == draggingNode.data.catId) {
                        // 如果遍历的是当前正在拖拽的节点
                        let catLevel = draggingNode.level;
                        if (siblings[i].level != draggingNode.level) {
                            // 当前节点的层级发生变化
                            catLevel = siblings[i].level;
                            // 修改他子节点的层级
                            this.updateChildNodeLevlel(siblings[i]);
                        }
                        this.updateNodes.push({
                            catId: siblings[i].data.catId,
                            sort: i,
                            parentCid: pCid,
                            catLevel: catLevel,
                        });
                    } else {
                        this.updateNodes.push({ catId: siblings[i].data.catId, sort: i });
                    }
                }
                //3 当前拖拽节点的最新层级
                console.log("updateNodes", this.updateNodes);
            },
            updateChildNodeLevlel(node) {
                if (node.childNodes.length > 0) {
                    for (let i = 0; i < node.childNodes.length; i++) {
                        var cNode = node.childNodes[i].data;
                        this.updateNodes.push({
                            catId: cNode.catId,
                            catLevel: node.childNodes[i].level,
                        });
                        this.updateChildNodeLevlel(node.childNodes[i]);
                    }
                }
            },
            allowDrop(draggingNode, dropNode, type) {
                //1 被拖动的当前节点以及所在的父节点总层数不能大于3

                //1 被拖动的当前节点总层数
                console.log("allowDrop:", draggingNode, dropNode, type);

                var level = this.countNodeLevel(draggingNode);

                // 当前正在拖动的节点+父节点所在的深度不大于3即可
                let deep = Math.abs(this.maxLevel - draggingNode.level) + 1;
                console.log("深度:", deep);

                // this.maxLevel
                if (type == "innner") {
                    // console.log(
                    //   `this.maxLevel: ${this.maxLevel}; draggingNode.data.catLevel:${draggingNode.data.catLevel};dropNode.level: ${dropNode.level}`
                    // );
                    return deep + dropNode.level <= 3;
                } else {
                    return deep + dropNode.parent.level <= 3;
                }
            },
            countNodeLevel(node) {
                // 找到所有子节点,求出最大深度
                if (node.childNodes != null && node.childNodes.length > 0) {
                    for (let i = 0; i < node.childNodes.length; i++) {
                        if (node.childNodes[i].level > this.maxLevel) {
                            this.maxLevel = node.childNodes[i].level;
                        }
                        this.countNodeLevel(node.childNodes);
                    }
                }
            },
            //添加节点
            append(data) {
                console.log("append----", data);
                this.dialogType = "add";
                this.title = "添加分类";
                this.category.parentCid = data.catId;
                this.category.catLevel = data.catLevel * 1 + 1;
                this.category.catId = null;
                this.category.name = null;
                this.category.icon = "";
                this.category.productUnit = "";
                this.category.sort = 0;
                this.category.showStatus = 1;
                this.dialogVisible = true;
            },
            // 修改三级分类数据
            editCategory() {
                var { catId, name, icon, productUnit } = this.category;
                this.$http({
                    url: this.$http.adornUrl("/product/category/update"),
                    method: "post",
                    data: this.$http.adornData({ catId, name, icon, productUnit }, false),
                })
                    .then(({ data }) => {
                    this.$message({
                        type: "success",
                        message: "菜单修改成功!",
                    });
                    // 关闭对话框
                    this.dialogVisible = false;
                    // 刷新出新的菜单
                    this.getMenus();
                    // 设置需要默认展开的菜单
                    this.expandedKey = [this.category.parentCid];
                })
                    .catch(() => {});
            },
            edit(data) {
                console.log("要修改的数据", data);
                this.dialogType = "edit";
                this.title = "修改分类";
                // 发送请求获取节点最新的数据,数据回显
                this.$http({
                    url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
                    method: "get",
                }).then((data) => {
                    // 请求成功
                    console.log("要回显得数据", data);
                    console.log(data);
                    this.category = data.data.category;
                    // console.log(this.category);
                    this.dialogVisible = true;
                });
            },
            //上交
            submitData() {
                if (this.dialogType == "add") {
                    this.addCategory();
                }
                if (this.dialogType == "edit") {
                    this.editCategory();
                }
            },

            // 添加三级分类
            addCategory() {
                console.log("提交的三级分类数据", this.category);
                this.$http({
                    url: this.$http.adornUrl("/product/category/save"),
                    method: "post",
                    data: this.$http.adornData(this.category, false),
                })
                    .then(({ data }) => {
                    this.$message({
                        type: "success",
                        message: "菜单保存成功!",
                    });
                    this.dialogVisible = false;
                    // 刷新出新的菜单
                    this.getMenus();
                    this.expandedKey = [this.category.parentCid];
                })
                    .catch(() => {});
            },
            //删除节点
            remove(node, data) {
                var ids = [data.catId]; //删除节点的id
                this.$confirm(`是否删除【${data.name}】当前菜单?`, "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                })
                    .then(() => {
                    this.$http({
                        url: this.$http.adornUrl("/product/category/delete"),
                        method: "post",
                        data: this.$http.adornData(ids, false),
                    })
                        .then(({ data }) => {
                        this.$message({
                            type: "success",
                            message: "菜单删除成功!",
                        });
                        // 刷新出新的菜单
                        this.getMenus();
                        this.expandedKey = [node.parent.data.catId];
                    })
                        .catch(() => {});
                })
                    .catch(() => {
                    this.$message({
                        type: "info",
                        message: "已取消删除",
                    });
                });
            },
            //获取所有菜单
            getMenus() {
                this.$http({
                    url: this.$http.adornUrl(`/product/category/list/tree`),
                    method: "get",
                }).then((resp) => {
                    this.data = resp.data.list;
                });
            },
            handleNodeClick(data) {
                console.log(data);
            },
        },
        created() {
            this.getMenus();
        },
    };
</script>

<style>
</style>

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值