当前位置:网站首页>Grain Mall (I)

Grain Mall (I)

2022-07-04 18:16:00 Brother Lei's little fan sister

Environment building

This project redis、MySQL They are all used in docker containerized , So we need to Linux Environmental Science

install docker

Docker Installation document

1、 Before uninstalling the system docker

 yum remove docker \
			docker-client \
			docker-client-latest \
			docker-common \
			docker-latest \
			docker-latest-logrotate \
			docker-logrotate \
			docker-engine

2、 install Docker-CE

#  Installation must depend on 
yum install -y yum-utils

# yum install gcc relevant 
yum -y install gcc
yum -y install gcc-c++

#  to update yum Package index 
yum makecache fast
#  Set up stable Mirror warehouse 
 Alibaba cloud is used here 
yum-config-manager --add-repo 
	http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
 Here is the official website , It's the Internet , Not recommended 
yum-config-manager --add-repo 
	https://download.docker.com/linux/centos/docker-ce.repo
#  install  docker, as well as  docker-cli
 yum install docker-ce docker-ce-cli containerd.io

3、 start-up docker

systemctl start docker

4、 Set up docker Boot from boot

systemctl enable docker

5、 test docker Common commands , Notice the switch to root Under the user
docker version

docker Common commands

6、 To configure docker Mirror to accelerate

#  Log in to Alibaba cloud developer platform  ->  Click on the console  ->  Select container image service  ->  The following operation documents configure image acceleration 

mkdir -p /etc/docker
vim /etc/docker/daemon.json

tee /etc/docker/daemon.json <<-'EOF' 
{ 
	"registry-mirrors": `["https://82m9ar63.mirror.aliyuncs.com"]
}
EOF

systemctl daemon-reload
systemctl restart

docker install mysql

1、 Download the image file docker pull mysql:5.7

2、 Create an instance and start

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

Parameter description :
-p 3306:3306: The container of 3306 Port mapping to host's 3306 port
-v /mydata/mysql/conf:/etc/mysql: Mount the configuration folder to the host
-v /mydata/mysql/log:/var/log/mysql: Mount the log folder to the host
-v /mydata/mysql/data:/var/lib/mysql/: Mount the configuration folder to the host
-e MYSQL_ROOT_PASSWORD=root: initialization root User's password

MySQL To configure
vi /mydata/mysql/conf/my.cnf

[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
collation-server=utf8_unicode_ci
skip-character-set-client-handshake
skip-name-resolve

Be careful : solve MySQL The problem of slow connection
Add the following... In the configuration file , And restart mysql
[mysqld]
skip-name-resolve
explain :
skip-name-resolve: Skip domain name resolution

3、 container-passing mysql Command line tool connection
docker exec -it mysql mysql -uroot -proot

4、 Set up root The remote access

grant all privileges on *.* to 'root'@'%' identified by 'root' with grant option;
flush privileges;

5、 Enter the container file system
docker exec -it mysql /bin/bash

docker install redis

1、 Download the image file docker pull redis

2、 Setup profile

mkdir -p /mydata/redis/conf
touch /mydata/redis/conf/redis.conf

redis Self description file

3、 modify /etc/redis/redis.conf file

#  Turn on  redis  verification ( Optional )
requirepass 123456

#  allow  redis  Field connection , Comment out 
 # bind 127.0.0.1

#  Set up  
daemonize no

#  Turn on  redis  Persistence ,appendonly yes ( Optional )

4、 Create an instance and start

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

5、 Use redis Mirrored execution redis-cli Command connection docker exec -it redis redis-cli

Set as docker Self starting

docker update mysql --restart=always

docker update redis --restart=always

Installation configuration git

1、 download git https://git-scm.com

2、 To configure git, Get into git bash

#  Configure username 
git config --global user.name "username" //( name )
#  Configure mailbox 
git config --global user.email "[email protected]" //( The email used when registering an account )

3、IDEA initialization git

 In the user directory (C:\Users\ASUS) Create ignore rule file  git.ignore, Write content 
 stay  .gitconfig  File reference ignored configuration file 
 stay  IDEA  Set in , location  Git  Program 

3、IDEA Integrate Gitee

 install  Gitee  plug-in unit , Sign in  Gitee  account number 

4、 To configure ssh Password free login

Get into git bash; Use :ssh-keygen -t rsa -C "[email protected]" command . Three consecutive returns

And then execute cat ~/.ssh/id_rsa.pub , You will get a string of keys

Log in gitee, Find... In the settings SSH KEY

take secret key Paste in the contents of

Use ssh -T [email protected] Whether the test is successful or not

Git+ Code cloud tutorial

from gitee Initialize project

New warehouse

 Insert picture description here

 Insert picture description here

IDEA Pull items

 Insert picture description here

 Insert picture description here

 Insert picture description here

Create project microservices

Goods and services 、 Warehousing services 、 Order service 、 Coupon service 、 Customer service

common :

  1. Are joined by web、openfeign rely on
  2. Package name of each service
    afei.xxx(product/order/ware/coupon/member)
  3. Module name :gulimall-coupon

 Insert picture description here
 Insert picture description here

 Insert picture description here
 Insert picture description here
 Insert picture description here

 Insert picture description here

modify Parent class Project pom.xml

modify Parent class Project .gitignore file , Let some files of its subclasses not be submitted

**/mvnw
**/mvnw.cmd
**/.mvn

**/.gitignore
**/target/
.idea

You can view the content preview submitted to the code cloud here

 Insert picture description here

Initialize database

Establish the corresponding database

 Insert picture description here

Will provide sql The statements in the file are copied into navicat perform , There is a problem dragging the container directly

Tools IDEA、VsCode

idea install lombok、mybatisx 、gitee plug-in unit

Vscode Install and develop necessary plug-ins :

  • Vetur —— Syntax highlighting 、 intellisense 、Emmet etc. Contains formatting functions , Alt+Shift+F ( Format full text ),Ctrl+K Ctrl+F( Format the selected code , Two Ctrl You need to press at the same time )
  • EsLint —— Grammatical error correction
  • Auto Close Tag —— Auto close HTML/XML label
  • Auto Rename Tag —— Automatically complete the synchronous modification of the other side label
  • JavaScript(ES6) code snippets — — ES6 Grammar intelligent prompt and fast input , except js Support in addition .ts,.jsx,.tsx,.html,.vue, Omit to configure it to support a variety of include js Time of code file
  • HTML CSS Support —— Give Way html Write on labels class Smart tip the styles supported by the current project
  • HTML Snippets —— html Fast automatic completion
  • Open in browser —— The browser opens quickly
  • Live Server —— Open as an embedded server
  • Chinese (Simplified) Language Pack for Visual Studio Code —— Chinese language pack

 Insert picture description here

Everyone open source to build a background management system

 Insert picture description here
After entering the point , clone

 Insert picture description here

Right click on the desktop , open Git Bash , Download the code to the desktop

 Insert picture description here

renren-fast

Copy the back-end code into project Catalog

 Insert picture description here

stay Parent item Join in Everyone is open source module

	<modelVersion>4.0.0</modelVersion>
	<groupId>com.atguigu.gulimall</groupId>
	<artifactId>gulimall</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>gulimall</name>
	<description> Aggregation services </description>
	<packaging>pom</packaging>
	<modules>
		<module>gulimall-coupon</module>
		<module>gulimall-member</module>
		<module>gulimall-order</module>
		<module>gulimall-product</module>
		<module>gulimall-ware</module>
		<module>renren-fast</module>
		<module>renren-generator</module>
		<module>gulimall-common</module>
	</modules>

renren-fast There is a database sql Statement file , Create a new library in the database gulumall_admin , perform sql sentence

 Insert picture description here
 Insert picture description here

modify renren-fast Configuration file for

 Insert picture description here

Start this project

Be careful , if renren-fast Integrated nacos, You still need to start Nacos service

communication link failure Of , Display initialization init datasource error Of , Add &useSSL=false
It is reported that the package cannot be found and is abnormal , Use the right sidebar maven Inside install command
url The suffix should be gulimall_admin?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
springboot The version should be the same 2.1.8.RELEASE

visit localhost:8080/renren-fast

 Insert picture description here

renren-fast-vue

Put the file directory on the desktop Delete .git Catalog , And then use VsCode open
 Insert picture description here

install Node.js

The front-end development , Indispensable Node.js
Node.js It's based on ChromeV8 Engine JavaScript Running environment .
NPM It's with NodeJS Installed together Package management tools ,JavaScript-NPM,Java-Maven;

1)、 Download and install on the official website node.js, And use node-v Check version . Note that version !!
 Insert picture description here
 Insert picture description here

2)、 To configure npm Use taobao mirror
npm config set registry http://registry.npm.taobao.org/

 Insert picture description here

open VsCode , Input... At the terminal npm install

You can also choose to open under the project folder cmd Command window , Just like the terminal ( Note that you need to configure environment variables , Reference article

Input npm install install npm,nodejs Default Integration npm

here npm Students who report errors , You can quit vs, Then the administrator runs vs, Execute it again . If it still doesn't work Just create a new terminal and input it again npm stall Just fine
There are errors , You can try cnpm install Try first
Errors can be referred to :https://blog.csdn.net/weixin_43859732/article/details/107779450
https://blog.csdn.net/wangbeita/article/details/112517509

 Insert picture description here
The following interface shows success

I don't use... Here vs, But use cmd Window for operation
Pay attention to the implementation of npm install Before , To prevent errors , Have already put renren-fast-vue Under the project folder package.json Inside node-sass Change to 4.9.2

 Insert picture description here

After success, you can access the ready to start project ( Be careful renren-fast Of 8080 In operation , The database is also running )

I didn't download it here vs, In the project directory , Open... With administrator privileges cmd , perform npm run dev You can start the front-end project

 Insert picture description here

This is a vs Start successful style
 Insert picture description here

Refresh Login interface Graphic verification code , It is found that there is output in the background , It means success

 Insert picture description here

Everyone runs error :

1、 start-up renren-fast Background error Error creating bean with name ‘scheduleJobService‘

route :src/main/java/io/renren/modules/job/config/ScheduleConfig.java

ScheduleConfig Class //PostgreSQL database , Need to open this comment

2、 After startup , Cross domain problems found during login :
 Insert picture description here
CorsConfig Class addCorsMappings Method , Need to open this comment

@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);
    }
}

3、 When there is such an error , The explanation is due to the introduction of mybatis Dependence , There will be relevant configurations for importing data sources at the bottom . If the database is not used in the module , There is no information about the configuration database , You're going to report a mistake
 Insert picture description here

solve :

Exclude from dependencies Related dependencies of database automatic configuration , You can also exclude
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)

Database reverse engineering

have access to Everyone is open source Automatically generate projects , You can also use MybatisX plug-in unit , Use IDEA Built in database management tools

Open source for everyone Code generation Project clone to local

 Insert picture description here

Delete from directory .git Catalog , And then as part of the project Sub module

 Insert picture description here
 Insert picture description here

Project modification The configuration file application.yml, Change the database configuration , The database is the database that needs to generate code

 Insert picture description here

Modify the information file generator.properties , Change the package name and class name of the generated class

 Insert picture description here

After the project runs , Access page , You can see the console , Select the desired table , Generate code

The generated code will be downloaded in a compressed package

 Insert picture description here

Open the package , You can see the generated code

 Insert picture description here

In the generated controller In class , It uses shiro Permission annotation for , But in this case SpringSecurity , So you need to delete the annotation
 Insert picture description here
But deleting one by one is more troublesome , Before generating code , stay renren-generator Modify the template in the project
 Insert picture description here

Copy the code into the required project , Open class , There will be errors , Because some tool classes are not referenced correctly

about Here's the picture Of common The tool classes in the package , Used before renren-fast Inside the project Of common package Under the util There are ready-made ones in the bag

 Insert picture description here

 Insert picture description here

Then open other classes , Also need to find Lombok、MybatisPlus Such dependence , So you can provide a public project , Used to provide common dependencies as well as Some tools, etc

gulimall-common modular

pom.xml

	<parent>
        <artifactId>gulimall</artifactId>
        <groupId>afei.gulimall</groupId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>gulimall-common</artifactId>
    <description> Every microservice has a common dependency ,bean, Tools, etc. </description>

    <dependencies>
        <!-- mybatis-plus-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.2.0</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.8</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.4.12</version>
        </dependency>


        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>

        <!-- Import mysql drive  -->
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.17</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>

        <!-- Service registration / Find out -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>

        <!-- The configuration center is used for configuration management -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
        </dependency>

        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>2.0.1.Final</version>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>2.1.2.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

Entity class

It will be used in the project that just generated the code common The tool class under the package , from renren-fast Copy it from the project

For the time being, only the contents in the red box , Other contents are created manually later

 Insert picture description here

gulimall-product modular

Port number of each module
 Insert picture description here

Now test CRUD

  1. Integrate MyBatis-Plus
    Import dependence mybatis-plus-boot-starter 3.2.0 ( Put it in common project )
    To configure :

    1. Configure data sources ;

      1. The driver to import the database .mysql-connector-java 8.0( Put it in common project )
      2. stay application.yml Configure data source related information
         Insert picture description here
    2. To configure MyBatis-Plus;

      1. Use @MapperScan
      2. tell MyBatis-Plus,sql Map file location , And set the primary key auto increment
         Insert picture description here
    3. test
       Insert picture description here

  2. Logical deletion
    1)、 Configure global logical deletion rules ( Omit )
    2)、 Configure logically deleted components Bean( Omit )
    3)、 to Bean Add logical deletion comments @TableLogic

  3. JSR303
    1)、 to Bean Add verification note :javax.validation.constraints, And define your own message Tips
    2)、 Turn on the check function @Valid effect : After checking the error, there will be a default response ;
    3)、 For verification bean Followed by one BindingResult, You can get the result of verification
    4)、 Group check ( Complex verification of multiple scenarios )
    1)、 @NotBlank(message = “ Brand name must be submitted ”,groups = {AddGroup.class,UpdateGroup.class}) Mark the verification notes with what needs to be verified
    2)、@Validated({AddGroup.class})
    3)、 By default, there is no verification comment for the specified group @NotBlank, In the case of group verification @Validated({AddGroup.class}) It doesn't work , Only in @Validated take effect ;
    5)、 Custom check
    1)、 Write a custom verification annotation
    2)、 Write a custom checker ConstraintValidator
    3)、 Associated with custom validator and custom validation annotation

Distributed components

nacos Registry Center

stay common Introduce dependencies into the project

	<!-- Service registration / Find out -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>

        <!-- The configuration center is used for configuration management -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
        </dependency>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>2.1.2.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

Then change the configuration file in other projects

 Insert picture description here

Use the annotation found by registration on the startup class @EnableDiscoveryClient

nacos Configuration center

stay common Introduce dependencies into the project
Then change the configuration file in other projects

How to use Nacos As the configuration center, it manages the configuration in a unified way :

  1. Introduce dependencies , spring-cloud-starter-alibaba-nacos-config

  2. Create a bootstrap.properties
     Insert picture description here

  3. You need to add a default configuration center called Data sets (Data Id),Data Id Default naming rules —— Application name .properties

  4. to Data Id Add any configuration

  5. Dynamic refresh configuration
    controller controller Use notes above @RefreshScope, Indicates that the configuration is dynamically obtained and refreshed

  6. Be careful , If the same configuration item is configured in the configuration center and the file , priority of use Configuration center configuration

  7. Load multiple configuration sets
     Insert picture description here  Insert picture description here

openFeign

 Here is the reference

Want to call other services remotely :

  1. introduce open-feign
  2. Write an interface , tell SpringCloud This interface needs to call the remote service
    1. Each method that declares an interface is the request that invokes which remote service
  3. Enable remote call function
    Use annotations on the startup class @EnableFeignClients

In the module that needs to be called remotely pom Introduce dependencies into the file

<properties>
	<java.version>1.8</java.version>
	<spring-cloud.version>Greenwich.SR3</spring-cloud.version>
</properties>
<dependencies>
	<dependency>
		<groupId>com.atguigu.gulimall</groupId>
		<artifactId>gulimall-common</artifactId>
		<version>0.0.1-SNAPSHOT</version>
	</dependency>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
	</dependency>
	<dependency>
		<groupId>org.springframework.cloud</groupId>
		<artifactId>spring-cloud-starter-openfeign</artifactId>
	</dependency>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-test</artifactId>
		<scope>test</scope>
	</dependency>
</dependencies>
<dependencyManagement>
	<dependencies>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-dependencies</artifactId>
			<version>${spring-cloud.version}</version>
			<type>pom</type>
			<scope>import</scope>
		</dependency>
	</dependencies>
</dependencyManagement>

The target method is as follows :
 Insert picture description here

stay member Module writing interface

 Insert picture description here

stay member Annotate the module startup class

 Insert picture description here

Finally stay member modular Implement remote call

 Insert picture description here

gateway

New module , Join in gateway rely on

  1. Open service registration discovery ( To configure nacos The address of the registry )
  2. Write the gateway configuration file

 Insert picture description here

	<properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Greenwich.SR3</spring-cloud.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>afei.gulimall</groupId>
            <artifactId>gulimall-common</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

Start the registration discovery on the startup class @EnableDiscoveryClient

Writing configuration files

spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
spring.application.name=gulimall-gateway
server.port=88
spring.cloud.nacos.config.server-addr=127.0.0.1:8848
spring.cloud.nacos.config.namespace=b5d62415-0dea-4747-a65d-874cc6203bf2
spring:
  cloud:
    gateway:
      routes:
#  Indicates if there are parameters in the request url, And the parameter value is baidu when , It will jump to https://www.baidu.com
#  For example, to access  88/hello?url=baidu  Will jump to  baodu.com/hello
# - id: test_route
# uri: https://www.baidu.com
# predicates:
# - Query=url,baidu 

#  Indicates if there are parameters in the request  url, And the parameter value is  qq when , It will jump to  https://www.qq.com
#  For example, to access  88/hello?url=qq, Will jump to  qq.com/hello
# - id: qq_route
# uri: https://www.qq.com
# predicates:
# - Query=url,qq


  ##  The front-end project ,/api
## http://localhost:88/api/captcha.jpg http://localhost:8080/renren-fast/captcha.jpg
## http://localhost:88/api/product/category/list/tree http://localhost:10000/product/category/list/tree

原网站

版权声明
本文为[Brother Lei's little fan sister]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/185/202207041613582739.html