百度云
链接: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
OpenFeign(微服务远程调用)
GateWay(API网关)
人人开源 / renren-generator
人人开源项目的代码生成器,可在线生成entity、xml、dao、service、vue、sql代码,减少70%以上的开发任务
https://www.renren.io
数据库技术
包管理工具
IntelliJ IDEA
链接:https://pan.baidu.com/s/1_3cewjaPwz5yEkRtwEpJfQ
提取码:81fd
File | Settings | Editor | File Encodings
设置为UTF-8,勾选Transparent native-to-ascii conversion
Visual Studio Code
安装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
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
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
配置setting.xml文件
<mirrors>
<mirror>
<id>alimavenid>
<name>aliyun mavenname>
<url>http://maven.aliyun.com/nexus/content/groups/public/url>
<mirrorOf>centralmirrorOf>
mirror>
mirrors>
<profiles>
<id>jdk-1.8id>
<activation>
<activeByDefault>trueactiveByDefault>
<jdk>1.8jdk>
activation>
<properties>
<maven.compiler.source>1.8maven.compiler.source>
<maven.compiler.target>1.8maven.compiler.target> <maven.compiler.compilerVersion>1.8maven.compiler.compilerVersion>
properties>
profiles>
IDEA配置Maven
File | Settings | Build, Execution, Deployment | Build Tools | Maven
配置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安装失败的问题
- vscode 下在项目根目录打开终端,npm install [email protected],项目默认的 sass地址一直404的话可以考虑这样做
- 安装完成后打开 package-lock.json ctrl+f 查找 sass,当version="4.13.1"时证明安装成功(当然前提是上一步没报错)
- npm run dev
- 补充一点 我事先将 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创建模块
创建以下几个微服务模块
创建主pom.xml文件管理这些微服务
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>com.atguigu.gulimallgroupId>
<artifactId>gulimallartifactId>
<version>0.0.1-SNAPSHOTversion>
<name>gulimallname>
<description>聚合服务description>
<packaging>pompackaging>
<modules>
<module>gulimall-couponmodule>
<module>gulimall-membermodule>
<module>gulimall-ordermodule>
<module>gulimall-productmodule>
<module>gulimall-waremodule>
<module>renren-fastmodule>
<module>renren-generatormodule>
<module>gulimall-commonmodule>
modules>
project>
通过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文件管理
<modules>
<module>renren-fastmodule>
modules>
使用数据库文件创建数据库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
启动运行为前端项目提供数据
git clone [email protected]:renrenio/renren-generator.git
添加主pom.xml文件管理
<modules>
<module>renren-generatormodule>
modules>
修改配置文件数据库连接
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
修改pom.xml文件添加依赖
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>gulimallartifactId>
<groupId>com.atguigu.gulimallgroupId>
<version>0.0.1-SNAPSHOTversion>
parent>
<modelVersion>4.0.0modelVersion>
<artifactId>gulimall-commonartifactId>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.pluginsgroupId>
<artifactId>maven-compiler-pluginartifactId>
<configuration>
<source>7source>
<target>7target>
configuration>
plugin>
plugins>
build>
<dependencies>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-boot-starterartifactId>
<version>3.3.1version>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>1.18.4version>
dependency>
<dependency>
<groupId>org.apache.httpcomponentsgroupId>
<artifactId>httpcoreartifactId>
<version>4.4.12version>
dependency>
<dependency>
<groupId>commons-langgroupId>
<artifactId>commons-langartifactId>
<version>2.6version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.17version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>servlet-apiartifactId>
<version>2.5version>
<scope>providedscope>
dependency>
<dependency>
<groupId>com.alibaba.cloudgroupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
dependency>
<dependency>
<groupId>com.alibaba.cloudgroupId>
<artifactId>spring-cloud-starter-alibaba-nacos-configartifactId>
dependency>
dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.alibaba.cloudgroupId>
<artifactId>spring-cloud-alibaba-dependenciesartifactId>
<version>2.1.0.RELEASEversion>
<type>pomtype>
<scope>importscope>
dependency>
dependencies>
dependencyManagement>
project>
创建com.atguigu.common.utils,从renren-fast的io.renren.common.utils拷贝
创建com.atguigu.common.xss,从renren-fast的io.renren.common.xss拷贝
修改报错引用
修改renren-generator\src\main\resources\template\Controller.java.vm的模板,注释RequiresPermissions
相关内容
整合Mybasitc-plus
修改gulimall-common的pom.xml
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-boot-starterartifactId>
<version>3.3.1version>
dependency>
修改gulimall-product的pom.xml
<dependency>
<groupId>com.atguigu.gulimallgroupId>
<artifactId>gulimall-commonartifactId>
<version>0.0.1-SNAPSHOTversion>
dependency>
配置
配置数据源
导入数据库驱动,修改gulimall-common的pom.xml
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.17version>
dependency>
创建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<BrandEntity> list = brandService.list(new QueryWrapper<BrandEntity>().eq("brand_id",5L));
list.forEach((item)-> {
System.out.println(item);
});
}
}
使用同样的方法分别创建其他微服务模块
修改gulimall-common的pom.xml文件
<dependency>
<groupId>com.alibaba.cloudgroupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
dependency>
下载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);
}
}
修改pom.xml文件添加OpenFeign依赖
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-openfeignartifactId>
dependency>
修改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
}
}
在gulimall-common
的pom.xml
文件中添加nacos配置
<dependency>
<groupId>com.alibaba.cloudgroupId>
<artifactId>spring-cloud-starter-alibaba-nacos-configartifactId>
dependency>
在对应优惠券微服务创建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
}
添加刷新注解
@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
}
创建命名空间测试环境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":[
]
}
}
使用Spring Intitializr创建模块
修改gulimall-gateway\pom.xml
添加依赖
<dependency>
<groupId>com.atguigu.gulimallgroupId>
<artifactId>gulimall-commonartifactId>
<version>0.0.1-SNAPSHOTversion>
dependency>
启用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.properties
spring.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
,跳转至腾讯
向mysql数据库gulimall_pms-pms-category
导入商品分类数据pms_catelog.sql
在com.atguigu.gulimall.product.controller.CategoryController
创建树形分类接口
/**
* 查询所有分类以及子分类,以树形结构组装起来
*/
@RequestMapping("/list/tree")
public R list(){
List<CategoryEntity> entityList = categoryService.listWithTree();
return R.ok().put("data",entityList);
}
在com.atguigu.gulimall.product.service.CategoryService
创建方法
public interface CategoryService extends IService<CategoryEntity> {
PageUtils queryPage(Map<String, Object> params);
List<CategoryEntity> listWithTree();
}
在com.atguigu.gulimall.product.entity.CategoryEntity
添加属性
@TableField(exist = false)
private List<CategoryEntity> children;
在com.atguigu.gulimall.product.service.impl.CategoryServiceImpl
@Override
public List<CategoryEntity> listWithTree() {
//1. 查出所有分类
List<CategoryEntity> entities = baseMapper.selectList(null);
//2. 组装成父子的树形结构
List<CategoryEntity> 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<CategoryEntity> getChildren(CategoryEntity root,List<CategoryEntity> all){
List<CategoryEntity> 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
启动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文件
<dependency>
<groupId>com.atguigu.gulimallgroupId>
<artifactId>gulimall-commonartifactId>
<version>0.0.1-SNAPSHOTversion>
dependency>
修改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.
创建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);
//// }
}
修改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