【业务功能篇76】微服务网关路由predicates断言条件-filters路由转换地址-跨域问题-多级目录树化层级设计-mybatisPlus逻辑删除

news2024/9/30 15:21:45

业务开发-基础业务-分类管理

启动renren-fast如果出现如下错误

image.png

-Djps.track.ap.dependencies=false

添加相关配置即可

image.png

分类管理

1.后端分类接口

JDK8特性:https://blog.csdn.net/qq_38526573/category_11113126.html

在后端服务中我们需要查询出所有的三级分类信息,并将这些信息组合为有父子关系的数据,所以首先我们需要在对应的entity中添加关联字段 childrens

	/**
	 * 当前类别所拥有的所有的子类
	 */
	@TableField(exist = false)
	private List<CategoryEntity> childrens;

然后我们在service中完成对应的数据处理的逻辑,具体实现逻辑参考注释

    /**
     * 查询所有的类别数据,然后将数据封装为树形结构,便于前端使用
     *
     * @param params
     * @return
     */
    @Override
    public List<CategoryEntity> queryPageWithTree(Map<String, Object> params) {
        // 1.查询所有的商品分类信息
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        // 2.将商品分类信息拆解为树形结构【父子关系】
        // 第一步遍历出所有的大类  parent_cid = 0
        List<CategoryEntity> list = categoryEntities.stream().filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                .map(categoryEntity -> {
                    // 根据大类找到多有的小类  递归的方式实现
                    categoryEntity.setChildrens(getCategoryChildrens(categoryEntity,categoryEntities));
                    return categoryEntity;
                }).sorted((entity1, entity2) -> {
                    return (entity1.getSort() == null ? 0 : entity1.getSort()) - (entity2.getSort() == null ? 0 : entity2.getSort());
                }).collect(Collectors.toList());
        // 第二步根据大类找到对应的所有的小类
        return list;
    }

    /**
     *  查找该大类下的所有的小类  递归查找
     * @param categoryEntity 某个大类
     * @param categoryEntities 所有的类别数据
     * @return
     */
    private List<CategoryEntity> getCategoryChildrens(CategoryEntity categoryEntity
            , List<CategoryEntity> categoryEntities) {
        List<CategoryEntity> collect = categoryEntities.stream().filter(entity -> {
            // 根据大类找到他的直属的小类
            return entity.getParentCid().equals(categoryEntity.getCatId());
        }).map(entity -> {
            // 根据这个小类递归找到对应的小小类
            entity.setChildrens(getCategoryChildrens(entity, categoryEntities));
            return entity;
        }).sorted((entity1, entity2) -> {
            return (entity1.getSort() == null ? 0 : entity1.getSort()) - (entity2.getSort() == null ? 0 : entity2.getSort());
        }).collect(Collectors.toList());
        return collect;
    }

CategoryService中同步定义对应的接口方法

public interface CategoryService extends IService<CategoryEntity> {

    PageUtils queryPage(Map<String, Object> params);

    List<CategoryEntity> queryPageWithTree(Map<String, Object> params);
}

然后在CategoryController中新增对应处理的方法

    @GetMapping("/listTree")
    public R listTree(@RequestParam Map<String, Object> params){
        List<CategoryEntity> list = categoryService.queryPageWithTree(params);
        return R.ok().put("data", list);
    }

启动服务访问测试

image.png

2. 前端服务串联

2.1 新增菜单

首先我们新增一个 商品系统的目录

image.png

按照上图的操作完成即可

image.png

然后在商品系统下添加 类别管理的菜单

image.png

对应的三级分类的页面 product/catagory–> src/views/modules/product/category.vue

image.png

2.2 类别数据

ElementUI官网:https://element.eleme.cn/#/zh-CN

第一步:展示静态的数据,直接从ElementUI官网拷贝Tree相关案例代码


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

<script>
/* eslint-disable */
export default {
    data() {
      return {
        data: [{
          label: '一级 1',
          children: [{
            label: '二级 1-1',
            children: [{
              label: '三级 1-1-1'
            }]
          }]
        }, {
          label: '一级 2',
          children: [{
            label: '二级 2-1',
            children: [{
              label: '三级 2-1-1'
            }]
          }, {
            label: '二级 2-2',
            children: [{
              label: '三级 2-2-1'
            }]
          }]
        }, {
          label: '一级 3',
          children: [{
            label: '二级 3-1',
            children: [{
              label: '三级 3-1-1'
            }]
          }, {
            label: '二级 3-2',
            children: [{
              label: '三级 3-2-1'
            }]
          }]
        }],
        defaultProps: {
          children: 'children',
          label: 'label'
        }
      };
    },
    methods: {
      handleNodeClick(data) {
        console.log(data);
      }
    }
  };
</script>

<style>

</style>

页面效果

image.png

第二步:动态获取后台服务的数据


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

<script>
/* eslint-disable */
export default {
    data() {
      return {
        data: [],
        defaultProps: {
          children: 'children',
          label: 'label'
        }
      };
    },
    methods: {
      getCategory(){
        this.$http({
          url: this.$http.adornUrl('/product/category/listTree'),
          method: 'get'
        }).then(({data}) => {
          console.log("成功获取的类别数据:",data.data)
          this.data = data.data
        })
      },
      handleNodeClick(data) {
        console.log(data);
      }
    },created(){
      this.getCategory();
    }
  };
</script>

<style>

</style>

访问三级分类数据并没有得到我们期望的结果。出现了404错误:http://localhost:8080/renren-fast/product/category/listTree

image.png

针对这个错误提示我们需要通过网关服务来实现统一的路由处理

image.png

修改了前端统一的后端服务地址为路由服务后

image.png

访问后这个验证码出不来了

image.png

验证码出不来的原因是请求的地址:http://localhost:8070/captcha.jpg?uuid=a496be9e-d916-4f3e-813d-d396c13a8b87 跑到网关服务获取验证码了,这里网关服务就应该要将这个请求路由到renren-fast服务中。

首先renren-fast服务没有在注册中心中注册,网关发现不了,先注册renren-fast服务

在renren-fast中依赖commons

		<dependency>
			<groupId>com.msb.mall</groupId>
			<artifactId>mall-commons</artifactId>
			<version>0.0.1-SNAPSHOT</version>
		</dependency>

添加注册中心和配置中心相关的信息

image.png

image.png

然后放开注册中心

image.png

最后启动服务提示如下错误

image.png

原因是因为SpringBoot我们把版本升级到了2.4.12那么validation默认被移除了,我们需要收到的添加依赖

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-validation</artifactId>
			<version>2.4.12</version>
		</dependency>

启动服务,注册成功

image.png

解决验证码图片不显示的问题,我们需要在网关服务中添加对renren-fast服务访问的路由

# 注册中心的信息
spring:
  application:
    name: mall-gateway
  cloud:
    nacos:
      discovery:
        server-addr: 192.168.56.100:8848
    gateway:
      routes:
        - id: route1
          uri: http://www.baidu.com
          predicates:
            - Query=url,baidu
        - id: route2
          uri: http://www.jd.com
          predicates:
            - Query=url,jd
        - id: app_route
          uri: lb://renren-fast
          predicates:
            - Path=/app/**
          filters:
            - RewritePath=/app/(?<segment>/?.*), /renren-fast/$\{segment}
# localhost:8070/app/captcha.jpg -->
# localhost:8080/app/captcha.jpg localhost:8080/renren-fast/captcha.jpg
# 指定注册中心的服务端口
server:
  port: 8070



然后测试访问验证码出现了503的错误

image.png

出现503错误的原因是Gateway网关服务中会根据loadbanlance负载均衡路由到renren-fast但是缺少了对应的依赖,在Gateway服务中添加即可

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-loadbalancer</artifactId>
        </dependency>

2.3 跨域问题

同源策略

由于浏览器的同源策略,即属于不同域的页面之间不能相互访问各自的页面内容
:同源策略,单说来就是同协议,同域名,同端口

URL 说明 是否允许通信
http://www.a.com/a.js
http://www.a.com/b.js 同一域名下 允许
http://www.a.com/lab/a.js
http://www.a.com/script/b.js 同一域名下不同文件夹 允许
http://www.a.com:8000/a.js
http://www.a.com/b.js 同一域名,不同端口 不允许
http://www.a.com/a.js
https://www.a.com/b.js 同一域名,不同协议 不允许
http://www.a.com/a.js
http://70.32.92.74/b.js 域名和域名对应ip 不允许
http://www.a.com/a.js
http://script.a.com/b.js 主域相同,子域不同 不允许
http://www.a.com/a.js
http://a.com/b.js 同一域名,不同二级域名(同上) 不允许(cookie这种情况下也不允许访问)
http://www.cnblogs.com/a.js
http://www.a.com/b.js 不同域名 不允许

跨域网站介绍:https://developer.mozilla.org/zh-CN/docs/Web/HTTP/CORSimage.png

image.png

对于跨域问题的解决我们统一在Gateway中设定。注意删除掉在renren-fast中配置的跨域问题

package com.msb.mall.gateway.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsConfigurationSource;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

@Configuration
public class MallCorsConfiguration {

    @Bean
    public CorsWebFilter corsWebFilter(){
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration configuration = new CorsConfiguration();
        // 配置跨域的信息
        configuration.addAllowedHeader("*");
        configuration.addAllowedMethod("*");
        // SpringBoot升级到2.4.0 之后需要使用该配置
        configuration.addAllowedOriginPattern("*");
        configuration.setAllowCredentials(true);
        source.registerCorsConfiguration("/**",configuration);
        return new CorsWebFilter(source);
    }
}

然后登录操作即可

image.png

2.4 查看类别数据

首先需要在Gateway中配置商品服务的路由信息,同时要注意配置规则的先后顺序

image.png

然后服务端响应的数据的字段要在Vue文件中显示的对应,才能正确的显示

image.png

访问测试

image.png

3 删除类别

2> 实现后台服务逻辑删除的操作

在实际开发中针对数据删除这块我们一般都会采用逻辑删除的方法来操作。在本项目中我们可以通过mybatis-Puls中提供的逻辑删除方式来实现

mybatis-plus:https://mp.baomidou.com/guide/

首先配置全局的逻辑删除逻辑

image.png

然后在entity的字段中显示的标明:

image.png

然后我们就可以在service中继续使用delete相关的方法来操作了

    /**
     * 逻辑批量删除操作
     * @param ids
     */
    @Override
    public void removeCategoryByIds(List<Long> ids) {
        // TODO  1.检查类别数据是否在其他业务中使用

        // 2.批量逻辑删除操作
        baseMapper.deleteBatchIds(ids);

    }

然后通过postman测试

image.png

然后在数据库中反应的效果

image.png

3> 串联前后端的逻辑

要实现该效果,首先需要通过ajax异步的来提交请求到后端服务

this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(ids, false),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
              });
              // 重新加载所有的菜单数据
              this.getCategory();
              // 设置默认展开的父节点信息
              this.expandKeys=[node.parent.data.catId]
            } else {
              this.$message.error(data.msg);
            }

然后删除需要必要的提示信息

this.$confirm(`是否确认删除【${data.name}】记录?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 传递的数据
          let ids = [data.catId];
          // 把删除的请求提交到后台服务
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(ids, false),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
              });
              // 重新加载所有的菜单数据
              this.getCategory();
              // 设置默认展开的父节点信息
              this.expandKeys=[node.parent.data.catId]
            } else {
              this.$message.error(data.msg);
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
      console.log("删除", data, node);

image.png

image.png

最后删除成功数据后Tree数据刷新及对应的Tree的默认展示父节点信息

image.png

image.png

image.png

到此,三级分类数据的删除操作搞定

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/920009.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

住宅IP:解锁更快速、稳定的互联网,你准备好了吗?

随着互联网的广泛普及&#xff0c;我们对网络的需求也越来越高。无论是工作、学习还是娱乐&#xff0c;我们都希望能够享受到更快速、稳定的互联网连接。而在实现这一目标的过程中&#xff0c;住宅IP正逐渐崭露头角&#xff0c;成为了一种备受关注的解决方案。那么&#xff0c;…

dig批量域名逆向查询ip

dig批量域名逆向查询ip dig nocmd noall answer -f iplist.txtiplist.txt中内容 效果图&#xff1a; dig其他选项参数&#xff1a; dig www.baidu.com A # 查询A记录&#xff0c;如果域名后面不加任何参数&#xff0c;默认查询A记录 dig www.baidu.com MX # 查询MX记…

利用TinyPng实现自动压图工具并管理

做游戏开发都会有缩减包体的问题&#xff0c;压图就是一个途径&#xff0c;用什么工具压图有很多工具和方法&#xff0c;我喜欢使用TinyPng&#xff0c;我自己久用python写了一个方便压图的工具。 ​​​​​​​​​​​​​​TinyPnghttps://tinypng.com/ 大家应该都用过&am…

Java学习笔记40

Java笔记40 创建运行时类的对象 获取运行时类的完整结构 我们可以通过反射来获取运行时类的完整结构&#xff0c;这包括&#xff1a; 实现的全部接口&#xff08;Interface&#xff09;所继承的父类&#xff08;Superclass&#xff09;全部的构造器&#xff08;Constructor&…

10 Mybatis

文章目录 1 概述1.1 什么是Mybatis?1.2 JDBC介绍(了解)1.2.1 问题分析1.2.2 技术对比 1.3 数据库连接池1.4 lombok 2 Mybatis基础操作2.1 准备2.2 删除2.2.1 日志输入2.2.2 预编译SQL2.2.2.1 介绍2.2.2.2 SQL注入2.2.2.3 参数占位符 2.3 新增2.3.1 主键返回 2.4 更新2.5 查询2…

Java 内置注解

一、内置注解 Java内置注解 也称 Java标准注解&#xff0c;是Java JDK 中自带的注解。Java 中有许多标准注解&#xff0c;以下是一些常见的标准注解&#xff1a; 1. Override&#xff1a;用于表示一个方法是重写父类中的方法。 2. Deprecated&#xff1a;用于标记已经过时的方法…

vue 使用print.js打印小票

官网&#xff1a;https://printjs.crabbly.com/ // 安装 npm install print-js --save// 引入 import printJS from print-js// 使用 printJS({printable: https://hwke.tbbug.com/images/phone/1899ed9346f64020ff4f9bbae6983952.jpg,type: image,imageStyle: width:100%;ma…

linux系统(centos、ubuntu、银河麒麟服务、uos、deepin)判断程序是否已安装,通用判断方法:使用所有应用和命令的判断

前言 项目中需要判断linux服务器中是否已经安装了某个服务 方法有很多种&#xff0c;但是很多都不通用&#xff0c; 脚本代码就不容易做成统一的 解决方案 用下面的脚本代码去进行判断 用jdk测试 脚本意思如下&#xff1a; 输入java -version命令&#xff0c;将返回的字…

react hooks 计数器

180秒倒计时 const [count, setCount] useState(0)setCount(180)useEffect(() > {clearTimeout(timer)timer setTimeout(() > {if (count > 1) {setCount(count - 1)} else {setIsSendEmail(false)}}, 1000)// eslint-disable-next-line}, [count]) import { useSta…

STM32 无法烧录

1. 一直显示芯片没连接上&#xff0c;检查连线也没问题&#xff0c;换了个ST-Link 烧录器还是连不上&#xff0c;然后又拿这个烧录器去其它板子上试下&#xff0c;就可以连接上&#xff0c;说明我连线没问题&#xff0c;烧录器也没问题&#xff0c;驱动什么的更是没问题&#x…

Kubernetes(K8S)简介

Kubernetes (K8S) 是什么 它是一个为 容器化 应用提供集群部署和管理的开源工具&#xff0c;由 Google 开发。Kubernetes 这个名字源于希腊语&#xff0c;意为“舵手”或“飞行员”。k8s 这个缩写是因为 k 和 s 之间有八个字符的关系。 Google 在 2014 年开源了 Kubernetes 项…

openCV实战-系列教程3:形态学操作(腐蚀操作/膨胀操作/开运算/闭运算/梯度计算/礼帽和黑帽)、源码解读

1、腐蚀操作 1.1 腐蚀 首先读进来并打印一张图 img cv2.imread(yzy.jpg) cv2.imshow(img, img) cv2.waitKey(0) cv2.destroyAllWindows() 这个图片出现了一些毛刺&#xff0c;看着挺难受 执行一个腐蚀操作&#xff0c;再将图片打印出来&#xff1a; kernel np.ones((3,3…

工厂方法模式介绍

韩敬海 设计模式&#xff08;Java版&#xff09; &#xff08;一&#xff09;定义 定义一个创建对象的接口&#xff0c;让子类决定实例化哪个类。工厂方法使一个类的实例化延迟到其子类。 工厂方法涉及的角色有&#xff1a; 1 .抽象工厂角色&#xff1a;工厂方法模式的核心&am…

从C语言到C++_34(C++11_下)可变参数+ lambda+function+bind+笔试题

目录 1. 可变参数模板 1.1 展开参数包 1.1.1 递归函数方式展开 1.1.2 逗号表达式展开 1.2 emplace相关接口 2. lambda表达式&#xff08;匿名函数&#xff09; 2.1 C11之前函数的缺陷 2.2 lambda表达式语法 2.3 函数对象与lambda表达式 3. 包装器 3.1 function包装器…

最新AI系统ChatGPT程序源码/微信公众号/H5端+搭建部署教程+完整知识库

一、前言 SparkAi系统是基于国外很火的ChatGPT进行开发的Ai智能问答系统。本期针对源码系统整体测试下来非常完美&#xff0c;可以说SparkAi是目前国内一款的ChatGPT对接OpenAI软件系统。 那么如何搭建部署AI创作ChatGPT&#xff1f;小编这里写一个详细图文教程吧&#xff01…

ARM DIY(三)板载串口和 LCD 调试

前言 今天焊接两大关键输入输出设备&#xff1a;串口和屏幕。 串口 串口部分使用 CP2102N 芯片&#xff08;USB 转 TTL&#xff09;&#xff0c;这样用一根数据线连接板子和 PC 就可以直接调试了。 焊接 CP2102 和 Type C 上电调试&#xff0c;串口可以正常输入输出。 看来…

css实现文字的渐变,适合大屏

1 在全局写一个全局样式&#xff0c;文字渐变 2 在组件中使用 CSS3利用-webkit-background-clip: text;实现文字渐变效果_css如何把盒子底部的文字变成透明渐变_I俩月亮的博客-CSDN博客 CSS 如何实现文字渐变色 &#xff1f;_css字体颜色渐变_一个水瓶座程序猿.的博客-CSDN博客…

ui设计师简历自我评价(合集)

UI设计最新面试题及答案 1、说说你是怎么理解UI的? UI是最直观的把产品展示展现在用户面前的东西&#xff0c;是一个产品的脸面。人开始往往是先会先喜欢上美好的事物后&#xff0c;在去深究内在的东西的。 那么也就意味着一个产品的UI首先要做的好看&#xff0c;无论风格是…

tensordataset 和dataloader取值

测试1 from torch.utils.data import TensorDataset,DataLoader import numpy as np import torch a np.array([[1,2,3],[2,3,3],[1,1,2],[10,10,10],[100,200,200],[-1,-2,-3]]) print(a)X torch.FloatTensor(a) print(X)dataset TensorDataset(X,X)测试2 from torch.uti…

基于PHP的电脑商城系统

有需要请加文章底部Q哦 可远程调试 基于PHP的电脑商城系统 一 介绍 此电脑商城系统基于原生PHP开发&#xff0c;数据库mysql&#xff0c;前端bootstrap。用户可注册登录&#xff0c;购物下单&#xff0c;评论等。管理员登录后台对电脑商品&#xff0c;用户&#xff0c;订单&a…