0


【云原生】一篇打通微服务架构,nacos + gateway + Redis + MySQL + docker

目录

一、前期准备

本项目暂定项目名GooReeyProject,SpringBoot + Vue构建,具体项目内容未定。

基本架构nacos、gateway、Linux、Redis、rabbitMQ、MySQL、docker、Vue。

1、安装MySQL5.7

2、安装nacos

我安装的是window版的nacos和MySQL,安装nacos时需要注意,要讲配置文件中的集群版改为单机版,才能启动!

3、安装Redis

二、创建父工程

我觉得主要是pom文件

<?xml version="1.0" encoding="UTF-8"?><projectxmlns="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"><modelVersion>4.0.0</modelVersion><groupId>com.guor</groupId><artifactId>GooReeyProject</artifactId><version>1.0-SNAPSHOT</version><modules><module>01common</module><module>02gateway</module></modules><properties><system.version>1.0.0</system.version><system.ip>127.0.0.1</system.ip><system.sport>808</system.sport><system.mode>http</system.mode><java.version>1.8</java.version><spring-cloud.version>Greenwich.SR1</spring-cloud.version><skipTests>true</skipTests><nacos.version>0.2.2.RELEASE</nacos.version></properties><packaging>pom</packaging><name>GooReeyProject</name><description>This is parent project</description><!-- 本项目的父模块使用spring-boot框架 --><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.1.4.RELEASE</version></parent><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><scope>provided</scope></dependency><dependency><groupId>commons-lang</groupId><artifactId>commons-lang</artifactId><version>2.6</version></dependency><dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper-spring-boot-starter</artifactId><version>1.2.5</version></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.23</version></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId><version>0.2.1.RELEASE</version></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><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-alibaba-dependencies</artifactId><version>${nacos.version}</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement><build><resources><resource><directory>src/main/resources</directory><includes><include>**/*.*</include></includes></resource><resource><directory>src/main/resources</directory><includes><include>**/*.yml</include></includes><filtering>true</filtering></resource><resource><directory>src/main/java</directory><includes><include>**/*.xml</include></includes></resource></resources></build></project>

三、创建gateway子工程

1、pom文件

<?xml version="1.0" encoding="UTF-8"?><projectxmlns="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>GooReeyProject</artifactId><groupId>com.guor</groupId><version>1.0-SNAPSHOT</version></parent><modelVersion>4.0.0</modelVersion><artifactId>02gateway</artifactId><dependencies><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.0.1</version></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-gateway</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-hystrix</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId></dependency></dependencies><dependencyManagement><dependencies><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId><exclusions><exclusion><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-ribbon</artifactId></exclusion></exclusions></dependency></dependencies></dependencyManagement><build><finalName>gateway-${system.version}</finalName></build></project>

2、配置文件

spring:application:name: gateway
  cloud:nacos:discovery:server-addr: 127.0.0.1:8848config:server-addr: 127.0.0.1:8848file-extension: yml
        ext-config:-data-id: datasource-share-config.yml
            group: SHARE_GROUP
            refresh:true-data-id: log-share-config.yml
            group: SHARE_GROUP
            refresh:true

(1)gateway.yml

server:port:8080spring:application:name: gateway
    version: 1.0.0
  cloud:gateway:discovery:locator:enabled:truelowerCaseServiceId:truefilters:- StripPrefix=1     
      routes:-id: management
          uri: lb:management   # 服务端 service_idpredicates:- Path=/management/**filters:-name: Hystrix 
              args:name: fallbackcmd
                fallbackUri: forward:/defaultFallback
        -id: demo
          uri: lb://demo
          predicates:- Path=/demo/**hystrix:command:default:execution:isolation:strategy: SEMAPHORE
          thread:timeoutInMilliseconds:1500

(2)datasource-share-config.yml

spring:datasource:url: jdbc:mysql://localhost:3306/blue?serverTimezone=UTC
    driverClassName: com.mysql.cj.jdbc.Driver
    username: root
    password: root
mybatis:typeAliasesPackage: com.guor.*.bean.**mapperLocations: classpath*:**/com/guor/**/dao/mapping/*Mapper.xmlconfiguration:map-underscore-to-camel-case:true

(3)log-share-config.yml

logging:path: logs
  level:root: info
    com.alibaba.nacos.client.naming: warn 
  file:max-size: 20MB
    max-history:30pattern:file:"%d{${LOG_DATEFORMAT_PATTERN:yyyy-MM-dd HH:mm:ss.SSS}} ${LOG_LEVEL_PATTERN:%5p} ${PID:- } --- [%15.15t] %-40.40logger{39} [%5.5line] : %m%n${LOG_EXCEPTION_CONVERSION_WORD:%wEx}"console:"%d{${LOG_DATEFORMAT_PATTERN:yyyy-MM-dd HH:mm:ss.SSS}} %clr(${LOG_LEVEL_PATTERN:%5p}) %clr(${PID:- }){magenta} --- %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr([%5.5line]){cyan} : %m%n${LOG_EXCEPTION_CONVERSION_WORD:%wEx}"

3、启动类

packagecom.guor;importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;importorg.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;importorg.springframework.cloud.client.discovery.EnableDiscoveryClient;importorg.springframework.cloud.context.config.annotation.RefreshScope;importorg.springframework.scheduling.annotation.EnableScheduling;@SpringBootApplication(exclude =DataSourceAutoConfiguration.class)@[email protected]@RefreshScopepublicclassGatewayApplication{publicstaticvoidmain(String[] args){SpringApplication.run(GatewayApplication.class, args);System.out.println("hello world");}}

四、创建management管理模块

1、pom文件

<?xml version="1.0" encoding="UTF-8"?><projectxmlns="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>GooReeyProject</artifactId><groupId>com.guor</groupId><version>1.0-SNAPSHOT</version></parent><modelVersion>4.0.0</modelVersion><artifactId>03management</artifactId><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.0.1</version></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId></dependency><!--MySQL依赖 --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency></dependencies><build><finalName>management-${system.version}</finalName></build></project>

2、配置文件

spring:application:name: management
  cloud:nacos:discovery:server-addr: 127.0.0.1:8848config:server-addr: 127.0.0.1:8848file-extension: yml
        ext-config:-data-id: datasource-share-config.yml
            group: SHARE_GROUP
            refresh:true-data-id: log-share-config.yml
            group: SHARE_GROUP
            refresh:true
server:port:8081spring:application:name: management
    version: 1.0.0
  mvc:static-path-pattern: /management/**resources:static-locations:- file:../../web/management
    - file:../../web/common

3、启动类

packagecom.guor;importorg.mybatis.spring.annotation.MapperScan;importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;importorg.springframework.cloud.client.discovery.EnableDiscoveryClient;importorg.springframework.cloud.context.config.annotation.RefreshScope;@[email protected](scanBasePackages ="com.guor")@MapperScan("com.guor.management.dao")@RefreshScopepublicclassManagementApplication{publicstaticvoidmain(String[] args){SpringApplication.run(ManagementApplication.class, args);}}

五、整合mybatis

1、user表设计

数据库选择的是最常用的MySQL

CREATETABLE`user`(`user_id`int(10)unsignedNOTNULLAUTO_INCREMENT,`username`varchar(100)NOTNULL,`password`varchar(40)NOTNULL,`age`int(11)DEFAULTNULL,`sex`int(11)DEFAULTNULL,`telephone`varchar(100)DEFAULTNULL,`address`varchar(100)DEFAULTNULL,`create_date`dateDEFAULTNULL,`update_date`dateDEFAULTNULL,`deleted`int(11)DEFAULTNULL,`version`int(11)DEFAULTNULL,PRIMARYKEY(`user_id`))ENGINE=InnoDBAUTO_INCREMENT=3DEFAULTCHARSET=utf8;

2、UserController

packagecom.guor.management.controller;importcom.guor.management.bean.User;importcom.guor.management.service.UserService;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.PutMapping;importorg.springframework.web.bind.annotation.RequestBody;importorg.springframework.web.bind.annotation.RestController;importjava.util.List;@RestControllerpublicclassUserController{@AutowiredprivateUserService userService;@GetMapping("/getUserList")publicList<User>getUserList(){return userService.getUserList();}@PutMapping("/insertUser")publicvoidinsertUser(@RequestBodyUser user){
        userService.insertUser(user);}}

3、UserService

packagecom.guor.management.service;importcom.guor.management.bean.User;importjava.util.List;publicinterfaceUserService{List<User>getUserList();voidinsertUser(User user);}
packagecom.guor.management.service.impl;importcom.guor.management.bean.User;importcom.guor.management.dao.UserMapper;importcom.guor.management.service.UserService;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Service;importjava.util.List;@ServicepublicclassUserServiceImplimplementsUserService{@AutowiredprivateUserMapper userMapper;@OverridepublicList<User>getUserList(){return userMapper.getUserList();}@OverridepublicvoidinsertUser(User user){
        userMapper.insertUser(user);}}

4、UserMapper

packagecom.guor.management.dao;importcom.guor.management.bean.User;importjava.util.List;publicinterfaceUserMapper{publicList<User>getUserList();publicvoidinsertUser(User user);}
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPEmapperPUBLIC"-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mappernamespace="com.guor.management.dao.UserMapper"><selectid="getUserList"resultType="java.util.LinkedHashMap">
        select * from user;
    </select><insertid="insertUser"parameterType="com.guor.management.bean.User">
        INSERT INTO gooreey.`user` (username, password) VALUES (#{username}, #{password});
    </insert></mapper>

5、User

packagecom.guor.management.bean;importcom.guor.base.bean.BaseBean;importlombok.Data;@DatapublicclassUserextendsBaseBean{privateInteger userId;privateString username;privateString password;privateInteger age;privateInteger sex;privateString telephone;privateString address;}
packagecom.guor.base.bean;importlombok.Data;importjava.util.Date;@DatapublicclassBaseBean{privateDate createDate;privateDate updateDate;privateInteger deleted;privateInteger version;}

6、postman接口测试

更多精彩内容:

哪吒精华文章汇总

Java热门专栏

SpringBoot进阶实战


本文转载自: https://blog.csdn.net/guorui_java/article/details/126293923
版权归原作者 哪 吒 所有, 如有侵权,请联系我们删除。

“【云原生】一篇打通微服务架构,nacos + gateway + Redis + MySQL + docker”的评论:

还没有评论