SpringCloud Alibaba微服务实战一 基础环境准备

目录

介绍

版本组件介绍

Docker Compose安装

Nacos 服务注册与发现

简介

安装 Nacos

容器化 MySQL

导入nacos的数据表

开启端口

测试nacos配置

微服务框架搭建

创建父工程

创建子模块

配置XML

创建启动项 配置yaml

Mysql创建数据库

CodeGenerator 模板生成器

测试


介绍

Spring Cloud Alibaba 致力于提供微服务开发的一站式解决方案。此项目包含开发分布式应用微服务的必需组件,方便开发者通过 Spring Cloud 编程模型轻松使用这些组件来开发分布式应用服务。

依托 Spring Cloud Alibaba,您只需要添加一些注解和少量配置,就可以将 Spring Cloud 应用接入阿里微服务解决方案,通过阿里中间件来迅速搭建分布式应用系统。

版本组件介绍

官方版本说明:版本说明 · alibaba/spring-cloud-alibaba Wiki · GitHub

本次 Spring Cloud Alibaba 版本

SpringCloud Alibaba微服务实战一 基础环境准备_第1张图片

本次 Spring Cloud Alibaba 版本及其自身所适配的各组件对应版本

SpringCloud Alibaba微服务实战一 基础环境准备_第2张图片

内容主要基于三个微服务:账户服务AccountService,账单服务RecordService,用户服务UserService

用到的组件有:

  • 注册中心、配置中心 Nacos
  • 限流 Sentinel
  • 分布式事务 Seata
  • 网关 SpringCloud Gateway
  • 认证授权 Spring Cloud Oauth2
  • docker、docker-compose

由于用到的组件相对较多,部署会很繁琐,最关键的是没有资源服务器,所以在开发过程中我会逐渐将一些组件使用docker-compose部署

本篇内容就是使用Dokcer-compose部署Nacos,Sentinel,MySQL,作为后面的文章的基础环境

Docker Compose安装

// 下载1.25.0 docker compose
sudo curl -L "https://github.com/docker/compose/releases/download/1.25.0/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose

// 添加可执行权限
sudo chmod +x /usr/local/bin/docker-compose

// 测试安装
docker-compose --version

Nacos 服务注册与发现

简介

        Nacos 致力于帮助您发现、配置和管理微服务。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据及流量管理。

        Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。 Nacos 是构建以“服务”为中心的现代应用架构 (例如微服务范式、云原生范式) 的服务基础设施。

安装 Nacos

docker pull nacos/nacos-server:1.4.1

nacos中的数据是存放在内存中的,一旦重启nacos数据就会丢失,所以说nacos一定要配置持久化

由于nacos需要依赖于MySQL作为资源存储,所以在编写完整docker-compose之前我会先用docker启动临时的mysql容器,然后准备好nacos需要的数据库

容器化 MySQL

先关闭本机mysql

docker rm -f $(docker ps -qa)

启动临时容器

docker run --rm --name mysql -e MYSQL_ROOT_PASSWORD=123456 -v /app/cloud/mysql/data:/var/lib/mysql -p 3306:3306 -d mysql:5.7

导入nacos的数据表

mysql客户端连接你的容器

新建数据库:cacos_config

SpringCloud Alibaba微服务实战一 基础环境准备_第3张图片

 导入sql

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for config_info
-- ----------------------------
DROP TABLE IF EXISTS `config_info`;
CREATE TABLE `config_info`  (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `data_id` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'data_id',
  `group_id` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL,
  `content` longtext CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'content',
  `md5` varchar(32) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL COMMENT 'md5',
  `gmt_create` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `gmt_modified` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间',
  `src_user` text CHARACTER SET utf8 COLLATE utf8_bin NULL COMMENT 'source user',
  `src_ip` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL COMMENT 'source ip',
  `app_name` varchar(128) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL,
  `tenant_id` varchar(128) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT '' COMMENT '租户字段',
  `c_desc` varchar(256) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL,
  `c_use` varchar(64) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL,
  `effect` varchar(64) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL,
  `type` varchar(64) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL,
  `c_schema` text CHARACTER SET utf8 COLLATE utf8_bin NULL,
  PRIMARY KEY (`id`) USING BTREE,
  UNIQUE INDEX `uk_configinfo_datagrouptenant`(`data_id`, `group_id`, `tenant_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 19 CHARACTER SET = utf8 COLLATE = utf8_bin COMMENT = 'config_info' ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of config_info
-- ----------------------------
INSERT INTO `config_info` VALUES (18, 'config_info.yaml', 'DEFAULT_GROUP', 'name: kuang', '46d09e283c2c06777cb9b27f6ab9a629', '2022-06-17 07:54:45', '2022-06-17 07:54:45', NULL, '43.250.200.118', '', '', '测试', NULL, NULL, 'yaml', NULL);

-- ----------------------------
-- Table structure for config_info_aggr
-- ----------------------------
DROP TABLE IF EXISTS `config_info_aggr`;
CREATE TABLE `config_info_aggr`  (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `data_id` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'data_id',
  `group_id` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'group_id',
  `datum_id` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'datum_id',
  `content` longtext CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT '内容',
  `gmt_modified` datetime(0) NOT NULL COMMENT '修改时间',
  `app_name` varchar(128) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL,
  `tenant_id` varchar(128) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT '' COMMENT '租户字段',
  PRIMARY KEY (`id`) USING BTREE,
  UNIQUE INDEX `uk_configinfoaggr_datagrouptenantdatum`(`data_id`, `group_id`, `tenant_id`, `datum_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_bin COMMENT = '增加租户字段' ROW_FORMAT = Dynamic;

-- ----------------------------
-- Table structure for config_info_beta
-- ----------------------------
DROP TABLE IF EXISTS `config_info_beta`;
CREATE TABLE `config_info_beta`  (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `data_id` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'data_id',
  `group_id` varchar(128) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'group_id',
  `app_name` varchar(128) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL COMMENT 'app_name',
  `content` longtext CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'content',
  `beta_ips` varchar(1024) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL COMMENT 'betaIps',
  `md5` varchar(32) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL COMMENT 'md5',
  `gmt_create` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `gmt_modified` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间',
  `src_user` text CHARACTER SET utf8 COLLATE utf8_bin NULL COMMENT 'source user',
  `src_ip` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL COMMENT 'source ip',
  `tenant_id` varchar(128) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT '' COMMENT '租户字段',
  PRIMARY KEY (`id`) USING BTREE,
  UNIQUE INDEX `uk_configinfobeta_datagrouptenant`(`data_id`, `group_id`, `tenant_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_bin COMMENT = 'config_info_beta' ROW_FORMAT = Dynamic;

-- ----------------------------
-- Table structure for config_info_tag
-- ----------------------------
DROP TABLE IF EXISTS `config_info_tag`;
CREATE TABLE `config_info_tag`  (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `data_id` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'data_id',
  `group_id` varchar(128) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'group_id',
  `tenant_id` varchar(128) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT '' COMMENT 'tenant_id',
  `tag_id` varchar(128) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'tag_id',
  `app_name` varchar(128) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL COMMENT 'app_name',
  `content` longtext CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'content',
  `md5` varchar(32) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL COMMENT 'md5',
  `gmt_create` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `gmt_modified` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间',
  `src_user` text CHARACTER SET utf8 COLLATE utf8_bin NULL COMMENT 'source user',
  `src_ip` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL COMMENT 'source ip',
  PRIMARY KEY (`id`) USING BTREE,
  UNIQUE INDEX `uk_configinfotag_datagrouptenanttag`(`data_id`, `group_id`, `tenant_id`, `tag_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_bin COMMENT = 'config_info_tag' ROW_FORMAT = Dynamic;

-- ----------------------------
-- Table structure for config_tags_relation
-- ----------------------------
DROP TABLE IF EXISTS `config_tags_relation`;
CREATE TABLE `config_tags_relation`  (
  `id` bigint(20) NOT NULL COMMENT 'id',
  `tag_name` varchar(128) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'tag_name',
  `tag_type` varchar(64) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL COMMENT 'tag_type',
  `data_id` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'data_id',
  `group_id` varchar(128) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'group_id',
  `tenant_id` varchar(128) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT '' COMMENT 'tenant_id',
  `nid` bigint(20) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`nid`) USING BTREE,
  UNIQUE INDEX `uk_configtagrelation_configidtag`(`id`, `tag_name`, `tag_type`) USING BTREE,
  INDEX `idx_tenant_id`(`tenant_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_bin COMMENT = 'config_tag_relation' ROW_FORMAT = Dynamic;

-- ----------------------------
-- Table structure for group_capacity
-- ----------------------------
DROP TABLE IF EXISTS `group_capacity`;
CREATE TABLE `group_capacity`  (
  `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `group_id` varchar(128) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT '' COMMENT 'Group ID,空字符表示整个集群',
  `quota` int(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT '配额,0表示使用默认值',
  `usage` int(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT '使用量',
  `max_size` int(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT '单个配置大小上限,单位为字节,0表示使用默认值',
  `max_aggr_count` int(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT '聚合子配置最大个数,,0表示使用默认值',
  `max_aggr_size` int(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT '单个聚合数据的子配置大小上限,单位为字节,0表示使用默认值',
  `max_history_count` int(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT '最大变更历史数量',
  `gmt_create` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `gmt_modified` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间',
  PRIMARY KEY (`id`) USING BTREE,
  UNIQUE INDEX `uk_group_id`(`group_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_bin COMMENT = '集群、各Group容量信息表' ROW_FORMAT = Dynamic;

-- ----------------------------
-- Table structure for his_config_info
-- ----------------------------
DROP TABLE IF EXISTS `his_config_info`;
CREATE TABLE `his_config_info`  (
  `id` bigint(64) UNSIGNED NOT NULL,
  `nid` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
  `data_id` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
  `group_id` varchar(128) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
  `app_name` varchar(128) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL COMMENT 'app_name',
  `content` longtext CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
  `md5` varchar(32) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL,
  `gmt_create` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `gmt_modified` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `src_user` text CHARACTER SET utf8 COLLATE utf8_bin NULL,
  `src_ip` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL,
  `op_type` char(10) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL,
  `tenant_id` varchar(128) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT '' COMMENT '租户字段',
  PRIMARY KEY (`nid`) USING BTREE,
  INDEX `idx_gmt_create`(`gmt_create`) USING BTREE,
  INDEX `idx_gmt_modified`(`gmt_modified`) USING BTREE,
  INDEX `idx_did`(`data_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 26 CHARACTER SET = utf8 COLLATE = utf8_bin COMMENT = '多租户改造' ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of his_config_info
-- ----------------------------
INSERT INTO `his_config_info` VALUES (0, 23, 'config_info.yaml', 'DEFAULT_GROUP', '', 'name: kaung', 'c99be43b88caa40fb2663ad3b9a59684', '2022-06-17 07:36:19', '2022-06-17 07:36:20', NULL, '43.250.200.118', 'I', '');
INSERT INTO `his_config_info` VALUES (17, 24, 'config_info.yaml', 'DEFAULT_GROUP', '', 'name: kaung', 'c99be43b88caa40fb2663ad3b9a59684', '2022-06-17 07:37:05', '2022-06-17 07:37:05', NULL, '43.250.200.118', 'D', '');
INSERT INTO `his_config_info` VALUES (0, 25, 'config_info.yaml', 'DEFAULT_GROUP', '', 'name: kuang', '46d09e283c2c06777cb9b27f6ab9a629', '2022-06-17 07:54:45', '2022-06-17 07:54:45', NULL, '43.250.200.118', 'I', '');

-- ----------------------------
-- Table structure for permissions
-- ----------------------------
DROP TABLE IF EXISTS `permissions`;
CREATE TABLE `permissions`  (
  `role` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `resource` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `action` varchar(8) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  UNIQUE INDEX `uk_role_permission`(`role`, `resource`, `action`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Table structure for roles
-- ----------------------------
DROP TABLE IF EXISTS `roles`;
CREATE TABLE `roles`  (
  `username` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `role` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  UNIQUE INDEX `idx_user_role`(`username`, `role`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of roles
-- ----------------------------
INSERT INTO `roles` VALUES ('nacos', 'ROLE_ADMIN');

-- ----------------------------
-- Table structure for tenant_capacity
-- ----------------------------
DROP TABLE IF EXISTS `tenant_capacity`;
CREATE TABLE `tenant_capacity`  (
  `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `tenant_id` varchar(128) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT '' COMMENT 'Tenant ID',
  `quota` int(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT '配额,0表示使用默认值',
  `usage` int(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT '使用量',
  `max_size` int(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT '单个配置大小上限,单位为字节,0表示使用默认值',
  `max_aggr_count` int(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT '聚合子配置最大个数',
  `max_aggr_size` int(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT '单个聚合数据的子配置大小上限,单位为字节,0表示使用默认值',
  `max_history_count` int(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT '最大变更历史数量',
  `gmt_create` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `gmt_modified` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间',
  PRIMARY KEY (`id`) USING BTREE,
  UNIQUE INDEX `uk_tenant_id`(`tenant_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_bin COMMENT = '租户容量信息表' ROW_FORMAT = Dynamic;

-- ----------------------------
-- Table structure for tenant_info
-- ----------------------------
DROP TABLE IF EXISTS `tenant_info`;
CREATE TABLE `tenant_info`  (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `kp` varchar(128) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'kp',
  `tenant_id` varchar(128) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT '' COMMENT 'tenant_id',
  `tenant_name` varchar(128) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT '' COMMENT 'tenant_name',
  `tenant_desc` varchar(256) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL COMMENT 'tenant_desc',
  `create_source` varchar(32) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL COMMENT 'create_source',
  `gmt_create` bigint(20) NOT NULL COMMENT '创建时间',
  `gmt_modified` bigint(20) NOT NULL COMMENT '修改时间',
  PRIMARY KEY (`id`) USING BTREE,
  UNIQUE INDEX `uk_tenant_info_kptenantid`(`kp`, `tenant_id`) USING BTREE,
  INDEX `idx_tenant_id`(`tenant_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8 COLLATE = utf8_bin COMMENT = 'tenant_info' ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of tenant_info
-- ----------------------------
INSERT INTO `tenant_info` VALUES (1, '1', 'cdc378f4-114b-471b-8732-b7d38bcb02ea', 'orders', '订单的命名空间', 'nacos', 1648718577421, 1648718577421);
INSERT INTO `tenant_info` VALUES (2, '1', 'faf33017-b8c2-48fa-9b29-09d644006946', 'users', '用户的命名空间', 'nacos', 1648718588816, 1648718588816);
INSERT INTO `tenant_info` VALUES (3, '1', '0cbe8b45-e878-4c59-9ab8-5b8616ac4d57', 'gateway', '网关', 'nacos', 1648881242577, 1648881242577);

-- ----------------------------
-- Table structure for users
-- ----------------------------
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users`  (
  `username` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `password` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `enabled` tinyint(1) NOT NULL,
  PRIMARY KEY (`username`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of users
-- ----------------------------
INSERT INTO `users` VALUES ('nacos', '$2a$10$EuWPZHzz32dJN7jexM34MOeYirDdFAZm2kuWj7VEOJhhZkDrxfvUu', 1);

SET FOREIGN_KEY_CHECKS = 1;

配置docker-compse文件

//进入指定目录
cd /usr/local/

//创建文件
mkdir docker

//进入创建好的docker文件
cd docker/

//创建编辑
vi docker-compose.yaml

docker-compse内容,大家可以自行修改

version: "3"
services:
  mysql:
    container_name: mysql
    image: mysql:5.7
    environment:
      - MYSQL_ROOT_PASSWORD=123456
    volumes:
      - /app/cloud/mysql/data:/var/lib/mysql
    ports:
      - "3306:3306"
    restart: always

  nacos:
    image: nacos/nacos-server:1.4.1
    container_name: nacos
    hostname: nacos
    restart: always
    environment:
      - MODE=standalone
      - TZ=Asia/Shanghai
      - NACOS_SERVER_PORT=8848
      - SPRING_DATASOURCE_PLATFORM=mysql
      - MYSQL_SERVICE_HOST=192.78.224.108
      - MYSQL_SERVICE_PORT=3306
      - MYSQL_SERVICE_DB_NAME=nacos_config
      - MYSQL_SERVICE_USER=root
      - MYSQL_SERVICE_PASSWORD=123456
      - PREFER_HOST_MODE=hostname
    volumes:
      - /app/cloud/nacos/logs:/home/nacos/logs
    ports:
      - "8848:8848"

192.78.224.108 需改成你的IP地址

开启端口

使用云服务器的:配置规则 8848

未使用云服务器的

// 查看防火墙状态
systemctl status firewalld
systemctl stop firewalld
systemctl start firewalld

// 开启端口
firewall-cmd --zone=public --add-port=8848/tcp --permanent

// 查询端口号8848是否开启
firewall-cmd --query-port=8848/tcp

// 重启防火墙
firewall-cmd --reload

// 查询有哪些端口是开启的
firewall-cmd --list-port

 启动nacos

docker-compose up -d nacos

测试nacos配置

 账户密码:nacos

添加配置 SpringCloud Alibaba微服务实战一 基础环境准备_第4张图片

 创建:Properties 或 yaml 配置

SpringCloud Alibaba微服务实战一 基础环境准备_第5张图片

配置完成查看数据库是否存在该数据

SpringCloud Alibaba微服务实战一 基础环境准备_第6张图片

微服务框架搭建

创建父工程

        项目昵称:spring-cloud-alibaba

        pom.xml配置


        1.8
        
        2021.1
        
        2020.0.1
        
        3.5.1
        
        8.0.13
        
        3.5.2
        
        2.3
        
        2.0.7
        
        1.18.24



    org.springframework.boot
    spring-boot-starter-parent
    2.4.2



    
            
            
                com.alibaba.cloud
                spring-cloud-alibaba-dependencies
                ${springcloud-alibaba-version}
                pom
                import
            

            
            
                org.springframework.cloud
                spring-cloud-dependencies
                ${springcloud-version}
                pom
                import
            

            
            
                com.baomidou
                mybatis-plus-boot-starter
                ${mp-version}
            

            
            
                mysql
                mysql-connector-java
                ${mysql-version}
            

            
            
                com.baomidou
                mybatis-plus-generator
                ${mp-generator}
            

            
            
                org.apache.velocity
                velocity-engine-core
                ${mp-velocity}
            

            
            
                com.github.xiaoymin
                knife4j-spring-boot-starter
                ${knife4j-version}
            

            
            
                org.projectlombok
                lombok
                ${lk-version}
            
    

        删除  .dea 与 src 文件

创建子模块

在你的父工程中建立多个模块的Maven项目

公共CommonService

账户服务AccountService

账单服务RecordService

用户服务UserService

SpringCloud Alibaba微服务实战一 基础环境准备_第7张图片

 配置XML

 common-service

 pom.xml如下


        
        
            org.springframework.boot
            spring-boot-starter-web
        

        
        
            com.baomidou
            mybatis-plus-boot-starter
        

        
        
            mysql
            mysql-connector-java
        

        
        
            com.baomidou
            mybatis-plus-generator
        

        
        
            org.apache.velocity
            velocity-engine-core
        

        
        
            com.github.xiaoymin
            knife4j-spring-boot-starter
        

        
        
            org.projectlombok
            lombok
        

user-service,record-service,account-service 都引入 common


    
    
        org.example
        common-service
        1.0-SNAPSHOT
    
    
    
    
        com.alibaba.cloud
        spring-cloud-starter-alibaba-nacos-discovery
    

创建启动项 配置yaml

user-service

src/main/java下创建 com/kuang/user/ 目录 并创建 启动类 UserApplication

UserApplication.java

package com.kuang.user;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
//开启服务注册与发现
@EnableDiscoveryClient
public class UserApplication {

    public static void main(String[] args) {
        SpringApplication.run(UserApplication.class,args);
    }
}

application.yaml

server:
  port: 8081

spring:
  application:
    name: user-service
  cloud:
    nacos:    #将这个服务注册到Nacos中
      discovery:
       server-addr: 192.74.102.54:8848  #换成你的 IP:8848

测试运行

SpringCloud Alibaba微服务实战一 基础环境准备_第8张图片

 nacos查看

SpringCloud Alibaba微服务实战一 基础环境准备_第9张图片

分别为 account-service,record-service 配置不同的yaml

server:
  port: 8082 #需要更改 account-service 8082 ,record-service 8083

spring:
  application:
    name: account-service #需要更改为服务名字
  cloud:
    nacos:    #将这个服务注册到Nacos中
      discovery:
       server-addr: 192.74.102.54:8848  #换成你的 IP:8848

分别为 account-service,record-service 创建如 user-service 的启动类 测试能否正常运行

Mysql创建数据库

库名:onlinebank

导入数据

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for account
-- ----------------------------
DROP TABLE IF EXISTS `account`;
CREATE TABLE `account`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `card_no` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `password` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `balance` int(6) NULL DEFAULT NULL,
  `status` int(11) NULL DEFAULT NULL,
  `user_id` int(11) NULL DEFAULT NULL COMMENT '关联用户的id',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 5 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of account
-- ----------------------------
INSERT INTO `account` VALUES (1, '1', '110', 300, 1, 1);
INSERT INTO `account` VALUES (2, '2', '123456', 300, 1, 1);
INSERT INTO `account` VALUES (3, '3', '123123', 300, 0, 1);
INSERT INTO `account` VALUES (4, '4', '456456', 200, 0, 1);

-- ----------------------------
-- Table structure for transaction_record
-- ----------------------------
DROP TABLE IF EXISTS `transaction_record`;
CREATE TABLE `transaction_record`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `card_no` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `transaction_date` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `amout` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `balance` int(19) NULL DEFAULT NULL,
  `transaction_type` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `remark` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 27 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of transaction_record
-- ----------------------------
INSERT INTO `transaction_record` VALUES (22, '1', '2022-6-17', '100', 500, '取款', '备注1');
INSERT INTO `transaction_record` VALUES (23, '2', '2022-6-17', '100', 200, '存款', '备注1');
INSERT INTO `transaction_record` VALUES (24, '1', '2022-6-17', '100', 400, '取款', '备注1');
INSERT INTO `transaction_record` VALUES (25, '3', '2022-6-17', '100', 300, '存款', '备注1');
INSERT INTO `transaction_record` VALUES (26, '1', '2022-6-17', '100', 300, '取款', '转账给2账户100');
INSERT INTO `transaction_record` VALUES (27, '2', '2022-6-17', '100', 300, '存款', '收到1账户转账100');

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`  (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '编号',
  `username` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '用户名',
  `phone` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '手机号',
  `create_time` datetime(0) NOT NULL COMMENT '创建时间',
  `update_time` datetime(0) NOT NULL COMMENT '修改时间',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, 'kuang', '17925768888', '2022-06-17 15:43:57', '2022-06-17 15:43:59');

SET FOREIGN_KEY_CHECKS = 1;

common-service

        创建如下包与类

SpringCloud Alibaba微服务实战一 基础环境准备_第10张图片

CodeGenerator 模板生成器

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.querys.MySqlQuery;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.fill.Column;
import com.baomidou.mybatisplus.generator.fill.Property;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

/**
 * @program: spring-cloud-alibaba
 * @description: 代码生成器
 * @author: Mr.Kuang
 * @create: 2022-05-18 10:14
 **/
public class CodeGenerator {

    public static void main(String[] args) {
        /*数据库配置*/
        DataSourceConfig dataSourceConfig =
                new DataSourceConfig
                        .Builder("jdbc:mysql://112.74.102.54:3306/onlinebank?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true","root","")
                        .dbQuery(new MySqlQuery())
                        .build();


        /*创建一共代码生成器对象*/
        AutoGenerator generator = new AutoGenerator(dataSourceConfig);



        //String property = System.getProperty(scanner("请输入项目路径"));


        /*全局配置*/
        GlobalConfig globalConfig = new GlobalConfig.Builder()
                .fileOverride()
                .outputDir(scanner("请输入你的项目路径") + "/src/main/java")
                .author("HaiGee").disableOpenDir()
                //.enableKotlin()
                //.enableSwagger()
                .dateType(DateType.TIME_PACK)
                .commentDate("yyyy-MM-dd")
                .build();



        generator.global(globalConfig);


        /*包配置(PackageConfig)*/
        PackageConfig packageConfig = new PackageConfig.Builder()
                .parent("com.kuang.common")
                //.moduleName("blog")
                .entity("entity")
                .service("service")
                .serviceImpl("service.impl")
                .mapper("mapper")
                .xml("mapper")
                .controller("controller")
                //.other("other")
                //.pathInfo(Collections.singletonMap(OutputFile.mapper, "D://"))
                //.pathInfo(Collections.singletonMap(OutputFile.xml, "D://"))
                .build();

        generator.packageInfo(packageConfig);


        TemplateConfig templateConfig = new TemplateConfig.Builder()
                .disable(TemplateType.ENTITY)
                .entity("/templates/entity.java")
                .service("/templates/service.java")
                .serviceImpl("/templates/serviceImpl.java")
                .mapper("/templates/mapper.java")
                .xml("/templates/mapper.xml")
                .controller("/templates/controller.java")
                .build();

        generator.template(templateConfig);

        /*策略配置*/
        StrategyConfig strategyConfig = new StrategyConfig.Builder()
                .enableCapitalMode()
                .enableSkipView()
                .disableSqlFilter()
                //.likeTable(new LikeTable("USER"))
                .addInclude(getTables(scanner("请输入表名,多个英文逗号分隔?所有输入 all")))
                .addTablePrefix("transaction_")
                //.addFieldSuffix("_flag")
                /*   .entityBuilder()
                   .controllerBuilder()
                   .mapperBuilder()
                   .serviceBuilder()*/
                .build();

        strategyConfig.entityBuilder()
                //.superClass(BaseEntity.class)
                .disableSerialVersionUID()
                .enableChainModel()
                .enableLombok()
                .enableRemoveIsPrefix()
                .enableTableFieldAnnotation()
                .enableActiveRecord()
                .versionColumnName("version")
                .versionPropertyName("version")
                .logicDeleteColumnName("deleted")
                .logicDeletePropertyName("deleted")
                .naming(NamingStrategy.underline_to_camel)
                .columnNaming(NamingStrategy.underline_to_camel)
                //.addSuperEntityColumns("id", "created_by", "created_time", "updated_by", "updated_time")
                //.addIgnoreColumns("age")
                .addTableFills(new Column("create_time", FieldFill.INSERT))
                .addTableFills(new Property("update_time", FieldFill.INSERT_UPDATE))
                .idType(IdType.AUTO)
                .formatFileName("%s")
                .build();

        strategyConfig.controllerBuilder()
                //.superClass(BaseController.class)
                //.enableHyphenStyle()
                .enableRestStyle()
                .formatFileName("%sController")
                .build();

        strategyConfig.serviceBuilder()
                //.superServiceClass(BaseService.class)
                // .superServiceImplClass(BaseServiceImpl.class)
                .formatServiceFileName("%sService")
                .formatServiceImplFileName("%sServiceImp")
                .build();

        strategyConfig
                .mapperBuilder()
                .superClass(BaseMapper.class)
                //.enableMapperAnnotation()
                //.enableBaseResultMap()
                //.enableBaseColumnList()
                //.cache(MyMapperCache.class)
                .formatMapperFileName("%sMapper")
                .formatXmlFileName("%sMapper")
                .build();


        generator.strategy(strategyConfig);

        /*执行代码生成器*/
        generator.execute();
    }

    // 处理 all 情况
    protected static List getTables(String tables) {
        return "all".equals(tables) ? Collections.emptyList() : Arrays.asList(tables.split(","));
    }

    /**
     * 

* 读取控制台内容 *

*/ public static String scanner(String tip) { Scanner scanner = new Scanner(System.in); StringBuilder help = new StringBuilder(); help.append("请输入" + tip + ":"); System.out.println(help.toString()); if (scanner.hasNext()) { String ipt = scanner.next(); if (StringUtils.isNotBlank(ipt)) { return ipt; } } throw new MybatisPlusException("请输入正确的" + tip + "!"); } }

按照你的路径自行更改

运行

SpringCloud Alibaba微服务实战一 基础环境准备_第11张图片

执行成功后我们会获得这4个包

 除entity实体类包不动,其他3个分别放置于对应的服务内 外加一个feign包

 这里以user-service为例

SpringCloud Alibaba微服务实战一 基础环境准备_第12张图片

 mapper层添加@Mapper注解

 SpringCloud Alibaba微服务实战一 基础环境准备_第13张图片

 为每个服务的 yaml 新增配置

server:
  port: 8081

spring:
  application:
    name: user-service
  cloud:
    nacos:
      discovery:
       server-addr: 192.74.102.54:8848
#下面为本次新增的配置
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://192.74.102.54:3306/onlinebank?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true
    username: root
    password: 123456


mybatis-plus:
  mapper-locations: classpath*:/mapper/*.xml
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    map-underscore-to-camel-case: true
  type-aliases-package: com.kuang.common.entity

 测试

为user-service controller 添加一个测试接口

package com.kuang.user.controller;

import com.kuang.common.entity.User;
import com.kuang.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 

* 前端控制器 *

* * @author HaiGee * @since 2022-06-17 */ @RestController @RequestMapping("/user") public class UserController { @Autowired UserService userService; @GetMapping("/getUserList") public List getUserList(){ List users = userService.list(); return users; } }

 运行测试能否获得数据

访问地址 需要查看nacos的服务详情

SpringCloud Alibaba微服务实战一 基础环境准备_第14张图片

SpringCloud Alibaba微服务实战一 基础环境准备_第15张图片

 测试

SpringCloud Alibaba微服务实战一 基础环境准备_第16张图片

你可能感兴趣的:(spring,cloud,微服务,java,linux)