尚硅谷2020微服务分布式电商项目《谷粒商城》
项目简介
资料
-
百度云
链接:https://pan.baidu.com/s/1eGCTi6pLtKbDCwBs-zCOzQ 提取码:1pma
涉及技术
-
前端技术
-
Vue
-
人人开源 / renren-fast-vue
renren-fast-vue基于vue、element-ui构建开发,实现renren-fast后台管理前端功能,提供一套更优的前端解决方案。
http://demo.open.renren.io/renren-fast
-
ES6
-
-
后端技术
-
spring boot
-
人人开源 / renren-fast
renren-fast是一个轻量级的Spring Boot2.1快速开发平台,其设计目标是开发迅速、学习简单、轻量级、易扩展;使用Spring Boot、Shiro、MyBatis、Redis、Bootstrap、Vue2.x等框架,包含:管理员列表、角色管理、菜单管理、定时任务、参数管理、代码生成器、日志管理、云存储、API模块(APP接口开发利器)、前后端分离等。
https://www.renren.io
-
-
spring cloud
-
spring alibaba
- nacos(注册配置中心)
OpenFeign(微服务远程调用)
GateWay(API网关)
-
-
人人开源 / renren-generator
人人开源项目的代码生成器,可在线生成entity、xml、dao、service、vue、sql代码,减少70%以上的开发任务
https://www.renren.io
-
-
数据库技术
- MySQL
- redis
-
包管理工具
- npm
- maven
环境搭建
编辑器
-
IntelliJ IDEA
链接:https://pan.baidu.com/s/1_3cewjaPwz5yEkRtwEpJfQ 提取码:81fd
- Plugins
- Gitee
- Lombok
- MyBatisX
-
File | Settings | Editor | File Encodings
设置为UTF-8,勾选Transparent native-to-ascii conversion
- Plugins
-
Visual Studio Code
- extensions
- Auto Close Tag
- Auto Rename Tag
- Chinese(Simplified) Language Pack
- ESLint
- HTML CSS Support
- HTML Snippets
- JavaScript(ES6) code snippets
- Live Server
- open in browser
- Vetur
- extensions
Linux虚拟机chenhao02
- 安装Centos7
- 配置静态IP
安装docker
-
安装docker
$ sudo yum remove docker \ docker-client \ docker-client-latest \ docker-common \ docker-latest \ docker-latest-logrotate \ docker-logrotate \ docker-engine $ sudo yum install -y yum-utils # 官网yum源 $ sudo yum-config-manager \ --add-repo \ https://download.docker.com/linux/centos/docker-ce.repo # 阿里云yum源 $ sudo yum-config-manager \ --add-repo \ http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo # 将软件包信息提前在本地缓存一份,用来提高搜索安装软件的速度 yum makecache fast $ sudo yum install docker-ce docker-ce-cli containerd.io $ sudo systemctl start docker
-
查看docker信息
docker -v docker images # 开机启动 systemctl enable docker
-
修改docker源为阿里云
sudo mkdir -p /etc/docker sudo tee /etc/docker/daemon.json <<-'EOF' { "registry-mirrors": ["https://aeb49y3h.mirror.aliyuncs.com"] } EOF sudo systemctl daemon-reload sudo systemctl restart docker
-
docker镜像自动启动
docker update redis --restart=always docker update mysql --restart=always
安装mysql
-
安装mysql
docker pull mysql:5.7
-
配置mysql
docker run -p 3306:3306 --name mysql \ -v /mydata/mysql/log:/var/log/mysql \ -v /mydata/mysql/data:/var/lib/mysql \ -v /mydata/mysql/conf:/etc/mysql \ -e MYSQL_ROOT_PASSWORD=root \ -d mysql:5.7
-
查看状态
docker images docker ps docker exec -it mysql /bin/bash
-
配置config文件
/mydata/mysql/conf/my.conf
[client] default-character-set=utf8 [mysql] default-character-set=utf8 [mysqld] init_connect='SET collation_connection = utf8_unicode_ci' init_connect='SET NAMES utf8' character-set-server=utf8 collection-server=utf8_unicode_ci skip-character-set-client-handshake skip-name-resolve
使用资料中的sql文件(gulimall_*.sql)创建微服务数据库基字符集使用utf8mb4
安装redis
-
安装redis
docker pull redis
-
配置redis
mkdir -p /mydata/redis/conf touch /mydata/redis/conf/redis.conf docker run -p 6379:6379 --name redis \ -v /mydata/redis/data:/data \ -v /mydata/redis/conf/redis.conf:/etc/redis/redis.conf \ -d redis redis-server /etc/redis/redis.conf
-
查看信息
docker ps docker images
-
redis配置
# 配置持久化 appendonly yes
Maven配置
-
配置setting.xml文件
alimaven aliyun maven http://maven.aliyun.com/nexus/content/groups/public/ central jdk-1.8 true 1.8 1.8 1.8 1.8 -
IDEA配置Maven
-
File | Settings | Build, Execution, Deployment | Build Tools | Maven
配置
-
码云git配置
- 初次运行 Git 前的配置
node配置淘宝镜像
npm config set registry http://registry.npm.taobao.org/
前端项目搭建
-
开源项目源码下载人人开源 / renren-fast-vue
git clone [email protected]:renrenio/renren-fast-vue.git
-
依赖包下载
git install
sass安装报错解决方法
> 完美解决 sass安装失败的问题
> 1. vscode 下在项目根目录打开终端,npm install [email protected],项目默认的 sass地址一直404的话可以考虑这样做
> 2. 安装完成后打开 package-lock.json ctrl+f 查找 sass,当version="4.13.1"时证明安装成功(当然前提是上一步没报错)
> 3. npm run dev
> 4. 补充一点 我事先将 npm版本切换到 6.9.0了 sudo npm -g install [email protected](这条命令是在根目录下运行,不是项目根)
> 关于新谷粒P16的前段项目使用npm install报错的问题,首先确保安装了python3.0以上版本,并配置全局变量
> 其次大部分错误是报node-sass4.9.0安装失败。
> 执行以下步骤可以完美解决
> 首先把项目文件夹下的package.json里面的node-sass4.9.0改成4.9.2(不改可能也没关系,不过我改了,防止踩坑)
> 然后项目文件夹下打开cmd命令窗口(和Visual Studio Code的终端命令是一样的)
> 执行:
> npm i node-sass --sass_binary_site=https://npm.taobao.org/mirrors/node-sass/
> 执行成功看看有没有报错,如果没报错执行下面命令
> npm install ,
> 没报错就是安装成功,然后使用npm run dev 就ok了
> 注:这么做得原理就是先单独从淘宝镜像吧nod-sass下载下来,然后再进行编译,因为这句命令好像是不成功后的,(npm config set registry http://registry.npm.taobao.org/),默认从github下载,导致报错的
-
依赖安装后运行
npm run serve
后端搭建
项目结构创建
-
使用Spring Intitializr创建模块
- Project Metadata
- Group: com.atguigu.gulimall
- Artifact: gulimall-product
- Package: com.atguigu.gulimall.product
- Dependencies添加依赖
- Web-Spring Web
- Spring Cloud Routing-OpenFeign
- Project Metadata
-
创建以下几个微服务模块
- gulimall-coupon
- gulimall-member
- gulimall-order
- gulimall-product
- gulimall-ware
-
创建主pom.xml文件管理这些微服务
4.0.0 com.atguigu.gulimall gulimall 0.0.1-SNAPSHOT gulimall 聚合服务 pom gulimall-coupon gulimall-member gulimall-order gulimall-product gulimall-ware renren-fast renren-generator gulimall-common 通过IDEA的Maven可管理所有微服务
-
修改.gitignore文件
target/ pom.xml.tag pom.xml.releaseBackup pom.xml.versionsBackup pom.xml.next release.properties dependency-reduced-pom.xml buildNumber.properties .mvn/timing.properties .mvn/wrapper/maven-wrapper.jar **/mvnw **/mvnw.cmd .mvn .idea **/.gitignore
后台项目搭建
-
人人开源 / renren-fast
git clone [email protected]:renrenio/renren-fast.git
-
添加主pom.xml文件管理
renren-fast 使用数据库文件创建数据库gulimall_admin
-
修改参数配置文件
spring: datasource: type: com.alibaba.druid.pool.DruidDataSource druid: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://chenhao02:3306/gulimall_admin?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai username: root password: root initial-size: 10 max-active: 100 min-idle: 10 max-wait: 60000 pool-prepared-statements: true max-pool-prepared-statement-per-connection-size: 20 time-between-eviction-runs-millis: 60000 min-evictable-idle-time-millis: 300000 #Oracle需要打开注释 #validation-query: SELECT 1 FROM DUAL test-while-idle: true test-on-borrow: false test-on-return: false stat-view-servlet: enabled: true url-pattern: /druid/* #login-username: admin #login-password: admin filter: stat: log-slow-sql: true slow-sql-millis: 1000 merge-sql: false wall: config: multi-statement-allow: true
启动运行为前端项目提供数据
逆向工程代码生成器
- 人人开源 / renren-generator
git clone [email protected]:renrenio/renren-generator.git
-
添加主pom.xml文件管理
renren-generator -
修改配置文件数据库连接
server: port: 80 # mysql spring: datasource: type: com.alibaba.druid.pool.DruidDataSource #MySQL配置 driverClassName: com.mysql.jdbc.Driver url: jdbc:mysql://chenhao02:3306/gulimall_pms?useUnicode=true&characterEncoding=UTF-8&useSSL=false username: root password: root jackson: time-zone: GMT+8 date-format: yyyy-MM-dd HH:mm:ss resources: static-locations: classpath:/static/,classpath:/views/ mybatis: mapperLocations: classpath:mapper/**/*.xml pagehelper: reasonable: true supportMethodsArguments: true params: count=countSql #指定数据库,可选值有【mysql、oracle、sqlserver、postgresql】 renren: database: mysql
-
修改生成文件属性配置
#代码生成器,配置信息 mainPath=com.atguigu #包名 package=com.atguigu.gulimall moduleName=ware #作者 author=chenshun #Email [email protected] #表前缀(类名不会包含表前缀) tablePrefix=pms_ #类型转换,配置信息 tinyint=Integer smallint=Integer mediumint=Integer int=Integer integer=Integer bigint=Long float=Float double=Double decimal=BigDecimal bit=Boolean char=String varchar=String tinytext=String text=String mediumtext=String longtext=String date=Date datetime=Date timestamp=Date NUMBER=Integer INT=Integer INTEGER=Integer BINARY_INTEGER=Integer LONG=String FLOAT=Float BINARY_FLOAT=Float DOUBLE=Double BINARY_DOUBLE=Double DECIMAL=BigDecimal CHAR=String VARCHAR=String VARCHAR2=String NVARCHAR=String NVARCHAR2=String CLOB=String BLOB=String DATE=Date DATETIME=Date TIMESTAMP=Date TIMESTAMP(6)=Date int8=Long int4=Integer int2=Integer numeric=BigDecimal
-
运行选中所有表-点击生成代码
将压缩包解压后将main文件夹拷贝粘贴至对应微服务main文件夹
-
使用Maven创建模块gulimall-common
-
Project Metadata
- GroupId: com.atguigu.gulimall
- ArtifactId: gulimall-common
-
修改pom.xml文件添加依赖
gulimall com.atguigu.gulimall 0.0.1-SNAPSHOT 4.0.0 gulimall-common org.apache.maven.plugins maven-compiler-plugin 7 com.baomidou mybatis-plus-boot-starter 3.3.1 org.projectlombok lombok 1.18.4 org.apache.httpcomponents httpcore 4.4.12 commons-lang commons-lang 2.6 mysql mysql-connector-java 8.0.17 javax.servlet servlet-api 2.5 provided com.alibaba.cloud spring-cloud-starter-alibaba-nacos-discovery com.alibaba.cloud spring-cloud-starter-alibaba-nacos-config com.alibaba.cloud spring-cloud-alibaba-dependencies 2.1.0.RELEASE pom import -
创建com.atguigu.common.utils,从renren-fast的io.renren.common.utils拷贝
- com.atguigu.common.utils.Constant
- com.atguigu.common.utils.PageUtils
- com.atguigu.common.utils.Query
- com.atguigu.common.utils.R
- com.atguigu.common.utils.RRException
-
创建com.atguigu.common.xss,从renren-fast的io.renren.common.xss拷贝
- com.atguigu.common.xss.HTMLFilter
- com.atguigu.common.xss.SQLFilter
修改报错引用
修改renren-generator\src\main\resources\template\Controller.java.vm的模板,注释
RequiresPermissions
相关内容
-
配置测试商品微服务
-
整合Mybasitc-plus
-
修改gulimall-common的pom.xml
com.baomidou mybatis-plus-boot-starter 3.3.1 -
修改gulimall-product的pom.xml
com.atguigu.gulimall gulimall-common 0.0.1-SNAPSHOT
-
-
配置
-
配置数据源
-
导入数据库驱动,修改gulimall-common的pom.xml
mysql mysql-connector-java 8.0.17 -
创建gulimall-product\src\main\resources\application.yml文件
spring:
datasource:
username: root
password: root
url: jdbc:mysql://192.168.174.130:3306/gulimall_pms?useUnicode=true&characterEncoding=UTF-8&useSSL=false
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis-plus:
mapper-location: classpath:/mapper/*/.xml
global-config:
db-config:
id-type: auto
server:
port: 10000 -
-
-
测试com.atguigu.gulimall.product.GulimallProductApplicationTests
package com.atguigu.gulimall.product; import com.atguigu.gulimall.product.entity.BrandEntity; import com.atguigu.gulimall.product.service.BrandService; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.util.List; @SpringBootTest class GulimallProductApplicationTests { @Autowired BrandService brandService; @Test void contextLoads() { BrandEntity brandEntity = new BrandEntity(); // 更新 // brandEntity.setBrandId(5L); // brandEntity.setDescript("华为牛逼"); // brandService.updateById(brandEntity); // 插入 // brandEntity.setName("华为"); // brandService.save(brandEntity); // System.out.println("保存成功..."); List
list = brandService.list(new QueryWrapper ().eq("brand_id",5L)); list.forEach((item)-> { System.out.println(item); }); } } 使用同样的方法分别创建其他微服务模块
使用nacos作为注册中心
-
修改gulimall-common的pom.xml文件
com.alibaba.cloud spring-cloud-starter-alibaba-nacos-discovery 下载nacos运行启动
-
修改对应微服务模块的application.yml
spring: datasource: username: root password: root url: jdbc:mysql://chenhao02:3306/gulimall_pms?useUnicode=true&characterEncoding=UTF-8&useSSL=false driver-class-name: com.mysql.cj.jdbc.Driver # 配置nacos注册中心 cloud: nacos: discovery: server-addr: 127.0.0.1:8848 application: name: gulimall-product mybatis-plus: mapper-location: classpath:/mapper/**/*.xml global-config: db-config: id-type: auto server: port: 10000
-
为com.atguigu.gulimall.product.GulimallProductApplication添加注册发现功能
package com.atguigu.gulimall.product; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; // 添加注册发现功能 @EnableDiscoveryClient @SpringBootApplication public class GulimallProductApplication { public static void main(String[] args) { SpringApplication.run(GulimallProductApplication.class, args); } }
OpenFeign进行远程调用
-
修改pom.xml文件添加OpenFeign依赖
org.springframework.cloud spring-cloud-starter-openfeign -
修改com.atguigu.gulimall.coupon.controller.CouponController作为调用测试
@RequestMapping("/member/list") public R membercoupons(){ CouponEntity couponEntity = new CouponEntity(); couponEntity.setCouponName("100减50"); return R.ok().put("coupons",Arrays.asList(couponEntity)); }
-
新建com.atguigu.gulimall.member.feign.CouponFeignService实现调用接口
package com.atguigu.gulimall.member.feign; import com.atguigu.common.utils.R; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.RequestMapping; @FeignClient("gulimall-coupon") public interface CouponFeignService { @RequestMapping("/coupon/coupon/member/list") public R membercoupons(); }
-
启用Feign调用功能com.atguigu.gulimall.member.GulimallMemberApplication
@EnableFeignClients(basePackages = "com.atguigu.gulimall.member.feign")
-
创建接口com.atguigu.gulimall.member.controller.MemberController
@Autowired CouponFeignService couponFeignService; @RequestMapping("/coupons") public R Test(){ MemberEntity memberEntity = new MemberEntity(); memberEntity.setNickname("张三"); R membercoupons = couponFeignService.membercoupons(); return R.ok().put("member",memberEntity) .put("coupons",membercoupons.get("coupons")); }
-
启动微服务gulimall-coupon、gulimall-member,访问
localhost:8000/member/member/coupons
{ "msg":"success", "code":0, "coupons":[ { "id":null, "couponType":null, "couponImg":null, "couponName":"100减50", "num":null, "amount":null, "perLimit":null, "minPoint":null, "startTime":null, "endTime":null, "useType":null, "note":null, "publishCount":null, "useCount":null, "receiveCount":null, "enableStartTime":null, "enableEndTime":null, "code":null, "memberLevel":null, "publish":null } ], "member":{ "id":null, "levelId":null, "username":null, "password":null, "nickname":"张三", "mobile":null, "email":null, "header":null, "gender":null, "birth":null, "city":null, "job":null, "sign":null, "sourceType":null, "integration":null, "growth":null, "status":null, "createTime":null } }
使用nacos作为配置中心
读取本地配置文件
-
在
gulimall-common
的pom.xml
文件中添加nacos配置com.alibaba.cloud spring-cloud-starter-alibaba-nacos-config -
在对应优惠券微服务创建
gulimall-coupon\src\main\resources\bootstrap.properties
spring.application.name=gulimall-coupon spring.cloud.nacos.config.server-addr=127.0.0.1:8848
-
创建
gulimall-coupon\src\main\resources\application.properties
coupon.user.name=zhangsan coupon.user.age=18
-
在
gulimall-coupon\src\main\java\com\atguigu\gulimall\coupon\controller\CouponController.java
创建测试函数@Value("${coupon.user.name}") private String name; @Value("${coupon.user.age}") private Integer age; @RequestMapping("/test") public R test(){ return R.ok().put("name",name).put("age",age); }
-
启动微服务gulimall-coupon,访问
http://localhost:7000/coupon/coupon/test
{ "msg":"success", "code":0, "name":"zhangsan", "age":18 }
读取nacos的配置文件
-
在nacos配置管理 | 配置列表 创建
gulimall-coupon.properties
-
添加刷新注解
@RefreshScope public class CouponController { }
-
启动微服务gulimall-coupon,访问
http://localhost:7000/coupon/coupon/test
{ "msg":"success", "code":0, "name":"zhangsan11", "age":11 }
-
修改nacos中的配置
coupon.user.name=nacos-default coupon.user.age=22
-
重启服务刷新访问
http://localhost:7000/coupon/coupon/test
{ "msg":"success", "code":0, "name":"nacos-default", "age":22 }
nacos命名空间
概念
- 命名空间
- 配置集
- 配置集ID
- 配置分组
命名空间
创建命名空间测试环境test、开发环境dev、生产环境prod
-
在prod命名空间下创建配置gulimall-coupon.properties
coupon.user.name=nacos-prod-default coupon.user.age=30
-
修改
gulimall-coupon\src\main\resources\bootstrap.properties
spring.application.name=gulimall-coupon spring.cloud.nacos.config.server-addr=127.0.0.1:8848 # 命名空间prod的ID spring.cloud.nacos.config.namespace=c8753605-71cd-4bb8-a7df-fec2af431835
-
重启服务刷新访问
http://localhost:7000/coupon/coupon/test
{ "msg":"success", "code":0, "name":"nacos-prod-default", "age":30 }
-
为微服务gulimall-coupon创建命名空间并创建配置gulimall-coupon.properties
coupon.user.name=nacos-gulimall~coupon-default coupon.user.age=40
-
修改
gulimall-coupon\src\main\resources\bootstrap.properties
spring.application.name=gulimall-coupon spring.cloud.nacos.config.server-addr=127.0.0.1:8848 # 命名空间gulimall-coupon的ID spring.cloud.nacos.config.namespace=ae7d7658-8c8a-4fc8-8365-e3b5df3d1776
-
重启服务刷新访问
http://localhost:7000/coupon/coupon/test
{ "msg":"success", "code":0, "name":"nacos-gulimall~coupon-default", "age":40 }
配置分组
-
创建配置文件gulimall-coupon.properties,分组Group设置为1111
coupon.user.name=nacos-gulimall~coupon-1111 coupon.user.age=44
-
修改
gulimall-coupon\src\main\resources\bootstrap.properties
spring.application.name=gulimall-coupon spring.cloud.nacos.config.server-addr=127.0.0.1:8848 # 命名空间gulimall-coupon的ID spring.cloud.nacos.config.namespace=ae7d7658-8c8a-4fc8-8365-e3b5df3d1776 spring.cloud.nacos.config.group=1111
-
重启服务刷新访问
http://localhost:7000/coupon/coupon/test
{ "msg":"success", "code":0, "name":"nacos-gulimall~coupon-1111", "age":44 }
-
创建配置文件gulimall-coupon.properties,分组Group设置为prod
coupon.user.name=nacos-gulimall~coupon-prod coupon.user.age=44
-
修改
gulimall-coupon\src\main\resources\bootstrap.properties
spring.application.name=gulimall-coupon spring.cloud.nacos.config.server-addr=127.0.0.1:8848 # 命名空间gulimall-coupon的ID spring.cloud.nacos.config.namespace=ae7d7658-8c8a-4fc8-8365-e3b5df3d1776 spring.cloud.nacos.config.group=prod
-
重启服务刷新访问
http://localhost:7000/coupon/coupon/test
{ "msg":"success", "code":0, "name":"nacos-gulimall~coupon-prod", "age":44 }
多配置集加载
-
创建datasource.yml,分组设置为dev
spring: datasource: username: root password: root url: jdbc:mysql://chenhao02:3306/gulimall_sms?useUnicode=true&characterEncoding=UTF-8&useSSL=false driver-class-name: com.mysql.cj.jdbc.Driver
-
创建mybatis.yml,分组设置为dev
mybatis-plus: mapper-location: classpath:/mapper/**/*.xml global-config: db-config: id-type: auto
-
创建other.yml,分组设置为dev
spring: cloud: nacos: discovery: server-addr: 127.0.0.1:8848 application: name: gulimall-coupon server: port: 7000
注释
gulimall-coupon\src\main\resources\application.yml
-
修改
gulimall-coupon\src\main\resources\bootstrap.properties
spring.application.name=gulimall-coupon spring.cloud.nacos.config.server-addr=127.0.0.1:8848 spring.cloud.nacos.config.namespace=ae7d7658-8c8a-4fc8-8365-e3b5df3d1776 spring.cloud.nacos.config.group=prod 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 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
-
重启服务刷新访问
http://localhost:7000/coupon/coupon/test
{ "msg":"success", "code":0, "name":"nacos-gulimall~coupon-prod", "age":44 }
-
访问
http://localhost:7000/coupon/coupon/list
{ "msg":"success", "code":0, "page":{ "totalCount":0, "pageSize":10, "totalPage":0, "currPage":1, "list":[ ] } }
使用Gateway作为API网关
-
使用Spring Intitializr创建模块
- Project Metadata
- Group: com.atguigu.gulimall
- Artifact: gulimall-gateway
- Package: com.atguigu.gulimall.gateway
- Dependencies添加依赖
- Spring Cloud Routing-Gateway
- Project Metadata
-
修改
gulimall-gateway\pom.xml
添加依赖com.atguigu.gulimall gulimall-common 0.0.1-SNAPSHOT -
启用
gulimall-gateway\src\main\java\com\atguigu\gulimall\gateway\GulimallGatewayApplication.java
@EnableDiscoveryClient // 排除数据源自动配置 @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}) public class GulimallGatewayApplication { public static void main(String[] args) { SpringApplication.run(GulimallGatewayApplication.class, args); } }
-
创建gulimall-gateway\src\main\resources\bootstrap.properties
spring.application.name=gulimall-gateway spring.cloud.nacos.config.server-addr=127.0.0.1:8848 spring.cloud.nacos.config.namespace=f3a73a90-6225-448d-bd72-d4eb8e5f0e0e
-
在nacos创建命名空间
gulimall-gateway
,创建gulimall-gateway.propertiesspring.application.name=gulimall-gateway spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848 server.port=88
-
创建配置文件gulimall-gateway\src\main\resources\application.yml
spring: cloud: gateway: routes: - id: test_route uri: https://www.baidu.com predicates: - Query=url,baidu - id: qq_route uri: https://www.qq.com predicates: - Query=url,qq
启动gulimall-gateway访问
http://localhost:88/hello?url=baidu
,跳转至百度启动gulimall-gateway访问
http://localhost:88/hello?url=qq
,跳转至腾讯
项目开发
商品服务
三级分类
三级分类数据查询P45
向mysql数据库
gulimall_pms-pms-category
导入商品分类数据pms_catelog.sql
-
在
com.atguigu.gulimall.product.controller.CategoryController
创建树形分类接口/** * 查询所有分类以及子分类,以树形结构组装起来 */ @RequestMapping("/list/tree") public R list(){ List
entityList = categoryService.listWithTree(); return R.ok().put("data",entityList); } -
在
com.atguigu.gulimall.product.service.CategoryService
创建方法public interface CategoryService extends IService
{ PageUtils queryPage(Map params); List listWithTree(); } -
在
com.atguigu.gulimall.product.entity.CategoryEntity
添加属性@TableField(exist = false) private List
children; -
在
com.atguigu.gulimall.product.service.impl.CategoryServiceImpl
@Override public List
listWithTree() { //1. 查出所有分类 List entities = baseMapper.selectList(null); //2. 组装成父子的树形结构 List level1Menus = entities.stream().filter(categoryEntity -> categoryEntity.getParentCid() == 0 ).map(menu->{ menu.setChildren(getChildren(menu,entities)); return menu; }).sorted((menu1,menu2)->{ return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort()); }).collect(Collectors.toList()); return level1Menus; } //递归查找所有菜单的子菜单 private List getChildren(CategoryEntity root,List all){ List children = all.stream().filter(categoryEntity -> categoryEntity.getParentCid() == root.getCatId() ).map(categoryEntity -> { categoryEntity.setChildren(getChildren(categoryEntity,all)); return categoryEntity; }).sorted((menu1,menu2)->{ return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort()); }).collect(Collectors.toList()); return children; } 启动
gulimall-product
访问http://localhost:10000/product/category/list/tree
配置网关路径P46
启动renren-fast、renren-fast-vue
登录
http://localhost:8001/#/login
- 系统管理-菜单管理-新增 目录 “商品系统”
- 系统管理-菜单管理-新增 菜单“分类维护”
创建前端vue文件
renren-fast-vue\src\views\modules\product\category.vue
-
修改static\config\index.js的api接口请求地址为网关地址
// api接口请求地址 window.SITE_CONFIG['baseUrl'] = 'http://localhost:88/api';
-
修改renren-fast的pom.xml文件
com.atguigu.gulimall gulimall-common 0.0.1-SNAPSHOT -
修改renren-fast的renren-fast\src\main\resources\application.yml
spring: application: name: renren-fast cloud: nacos: discovery: server-addr: 127.0.0.1:8848
-
启用注册发现功能renren-fast\src\main\java\io\renren\RenrenApplication.java
@EnableDiscoveryClient @SpringBootApplication public class RenrenApplication { public static void main(String[] args) { SpringApplication.run(RenrenApplication.class, args); } }
-
修改gulimall-gateway\src\main\resources\application.yml将路由转发至renren-fast微服务
spring: cloud: gateway: routes: - id: admin_route uri: lb://renren-fast predicates: - Path=/api/** filters: - RewritePath=/api/(?
.*),/renren-fast/$\{segment} -
访问http://localhost:8001/#/login,能转发请求查看验证码图片,但有跨域问题
Access to XMLHttpRequest at 'http://localhost:88/api/sys/login' from origin 'http://localhost:8001' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
网关统一配置跨域P47
-
创建gulimall-gateway\src\main\java\com\atguigu\gulimall\gateway\config\GulimallCorsConfiguration.java
package com.atguigu.gulimall.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.UrlBasedCorsConfigurationSource; import org.springframework.web.cors.reactive.CorsWebFilter; @Configuration public class GulimallCorsConfiguration { @Bean public CorsWebFilter corsWebFilter(){ UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.addAllowedHeader("*"); corsConfiguration.addAllowedMethod("*"); corsConfiguration.addAllowedOrigin("*"); corsConfiguration.setAllowCredentials(true); source.registerCorsConfiguration("/**",corsConfiguration); return new CorsWebFilter(source); } }
-
禁用默认跨域renren-fast\src\main\java\io\renren\config\CorsConfig.java
package io.renren.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class CorsConfig implements WebMvcConfigurer { // @Override //// public void addCorsMappings(CorsRegistry registry) { //// registry.addMapping("/**") //// .allowedOrigins("*") //// .allowCredentials(true) //// .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") //// .maxAge(3600); //// } }
三级分类树型展示P48
-
修改gulimall-gateway\src\main\resources\application.yml将路由转发至gulimall-product微服务
spring: cloud: gateway: routes: - id: product_route uri: lb://gulimall-product predicates: - Path=/api/product/** filters: - RewritePath=/api/(?
.*),/$\{segment} 为微服务gulimall-product创建命名空间gulimall-product
-
添加配置中心gulimall-product\src\main\resources\bootstrap.properties
spring.application.name=gulimall-product spring.cloud.nacos.config.server-addr=127.0.0.1:8848 spring.cloud.nacos.config.namespace=32ab9335-9125-4669-9954-eb3947090106
-
添加注册发现功能gulimall-product\src\main\resources\application.yml
spring: datasource: username: root password: root url: jdbc:mysql://chenhao02:3306/gulimall_pms?useUnicode=true&characterEncoding=UTF-8&useSSL=false driver-class-name: com.mysql.cj.jdbc.Driver # 配置nacos注册中心 cloud: nacos: discovery: server-addr: 127.0.0.1:8848 application: name: gulimall-product mybatis-plus: mapper-location: classpath:/mapper/**/*.xml global-config: db-config: id-type: auto server: port: 10000
-
启用注册发现功能gulimall-product\src\main\java\com\atguigu\gulimall\product\GulimallProductApplication.java
// 添加注册发现功能 @EnableDiscoveryClient @SpringBootApplication public class GulimallProductApplication { public static void main(String[] args) { SpringApplication.run(GulimallProductApplication.class, args); } }
-
调整路由顺序gulimall-gateway\src\main\resources\application.yml
spring: cloud: gateway: routes: - id: product_route uri: lb://gulimall-product predicates: - Path=/api/product/** filters: - RewritePath=/api/(?
.*),/$\{segment} - id: admin_route uri: lb://renren-fast predicates: - Path=/api/** filters: - RewritePath=/api/(? .*),/renren-fast/$\{segment} -
前端项目添加axios模块src\main.js
import axios from 'axios' Vue.prototype.$axios = axios axios.defaults.baseURL = 'http://localhost:88/api';
-
创建前端vue文件
renren-fast-vue\src\views\modules\product\category.vue