SpringCloud学习笔记【零基础篇】SpringCloud介绍及微服务架构编码构建

一、SpringCloud介绍

SpringCloud 是微服务一站式服务解决方案,微服务全家桶。它是微服务开发的主流技术栈。它采用了名称,而非数字版本号。
SpringCloud 和 SpringCloud Alibaba 目前是最主流的微服务框架组合。

SpringCloud版本选择

选用 SpringBoot 和 SpringCloud 版本有约束,不按照它的约束会有冲突。
SpringCloud学习笔记【零基础篇】SpringCloud介绍及微服务架构编码构建_第1张图片
查看版本对ces应关系:https://spring.io/projects/spring-cloud#overview

课程所用软件版本

cloud Hoxton.SR1
boot 2.2.2.RELEASE
cloud alibaba 2.1.0.RELEASE
Java Java8
Maven 3.5及以上
Mysql 5.7及以上

题外话:当前boot版已经到2.7.3为最新,为什么选2.2.2?

  1. 如果项目中只用到boot,直接用最新的boot版本,这没问题,但是同时用boot和cloud,需要照顾cloud,由cloud决定boot版本;
    查看cloud和boot最佳适配关系:https://spring.io/projects/spring-cloud#learn
    SpringCloud学习笔记【零基础篇】SpringCloud介绍及微服务架构编码构建_第2张图片

Cloud各种组件的停更/升级/替换

现在(2020年):

  1. Eureka停用,可以使用zk作为服务注册中心
  2. 服务调用,Ribbon准备停更,代替为LoadBalance
  3. Feign改为OpenFeign
  4. Hystrix停更,改为resilence4j,或者阿里巴巴的sentienl
  5. Zuul改为gateway
  6. 服务配置Config改为 Nacos
  7. 服务总线Bus改为Nacos
    SpringCloud学习笔记【零基础篇】SpringCloud介绍及微服务架构编码构建_第3张图片参考资料:

SpringCloud:

https://cloud.spring.io/spring-cloud-static/Hoxton.SR1/reference/htmlsingle/
Spring Cloud中文文档:https://www.bookstack.cn/read/spring-cloud-docs/docs-index.md

二、微服务架构编码构建

约定 > 配置 > 编码

(一)构建父工程

  1. 微服务cloud整体聚合父工程Project
    • File >New >Project,选择Maven
    • 勾选添加archetype,选择版本 org.apache.maven.archetypes:maven-archetype-site (Next下一步)
    填写GroupId:com.atguigu.springcloud 填写ArtifactId:cloud2020
    SpringCloud学习笔记【零基础篇】SpringCloud介绍及微服务架构编码构建_第4张图片
    • 配置字符编码: File | Settings | Editor | File Encodings
    配置 Project Encoding 为 utf-8; 配置Default encoding for properties files 为utf-8
    并勾选Transparent native-to-ascii conversion
    SpringCloud学习笔记【零基础篇】SpringCloud介绍及微服务架构编码构建_第5张图片
    • 注解激活生效:File | Settings | Build, Execution, Deployment | Compiler | Annotation Processors 勾选 Enable annotation processing
    SpringCloud学习笔记【零基础篇】SpringCloud介绍及微服务架构编码构建_第6张图片
    • 调整Java编译版本:File | Settings | Build, Execution, Deployment | Compiler | Java Compiler 列表 Target bytecode version下拉选择8
    • File Type 过滤: File | Settings | Editor | File Types 过滤掉不想看的文件在Ignored Files and Folders填入过滤格式 .gitignore,.idea,*.iml
    SpringCloud学习笔记【零基础篇】SpringCloud介绍及微服务架构编码构建_第7张图片

2、父工程pom配置

• 1.3.0 mybatis.spring.boot.version 的版本太低,无法使用注解@Mapper,@Parm


<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">
    <modelVersion>4.0.0modelVersion>
 
    <groupId>springcloudgroupId>
    <artifactId>cloud2020artifactId>
    <version>1.0-SNAPSHOTversion>
 
    <packaging>pompackaging>
 
    
    <properties>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
        <maven.compiler.source>1.8maven.compiler.source>
        <maven.compiler.target>1.8maven.compiler.target>
        <junit.version>4.12junit.version>
        <log4j.version>1.2.17log4j.version>
        <lombok.version>1.16.18lombok.version>
        <mysql.version>5.1.47mysql.version>
        <druid.version>1.1.16druid.version>
        <mybatis.spring.boot.version>1.3.0mybatis.spring.boot.version>
    properties>
 
    
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.apache.maven.pluginsgroupId>
                <artifactId>maven-project-info-reports-pluginartifactId>
                <version>3.0.0version>
            dependency>
 
            
            
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-dependenciesartifactId>
                <version>2.2.2.RELEASEversion>
                <type>pomtype>
                <scope>importscope>
            dependency>
            
            <dependency>
                <groupId>org.springframework.cloudgroupId>
                <artifactId>spring-cloud-dependenciesartifactId>
                <version>Hoxton.SR1version>
                <type>pomtype>
                <scope>importscope>
            dependency>
            
            <dependency>
                <groupId>com.alibaba.cloudgroupId>
                <artifactId>spring-cloud-alibaba-dependenciesartifactId>
                <version>2.1.0.RELEASEversion>
                <type>pomtype>
                <scope>importscope>
            dependency>
 
            
            <dependency>
                <groupId>mysqlgroupId>
                <artifactId>mysql-connector-javaartifactId>
                <version>${mysql.version}version>
                <scope>runtimescope>
            dependency>
            
            <dependency>
                <groupId>com.alibabagroupId>
                <artifactId>druidartifactId>
                <version>${druid.version}version>
            dependency>
            <dependency>
                <groupId>org.mybatis.spring.bootgroupId>
                <artifactId>mybatis-spring-boot-starterartifactId>
                <version>${mybatis.spring.boot.version}version>
            dependency>
            
            <dependency>
                <groupId>junitgroupId>
                <artifactId>junitartifactId>
                <version>${junit.version}version>
            dependency>
            
            <dependency>
                <groupId>log4jgroupId>
                <artifactId>log4jartifactId>
                <version>${log4j.version}version>
            dependency>
 
        dependencies>
 
    dependencyManagement>
 
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
                <configuration>
                    <fork>truefork>
                    <addResources>trueaddResources>
                configuration>
            plugin>
        plugins>
    build>
project>

3、Maven工程落地细节复习

SpringCloud学习笔记【零基础篇】SpringCloud介绍及微服务架构编码构建_第8张图片
SpringCloud学习笔记【零基础篇】SpringCloud介绍及微服务架构编码构建_第9张图片

(二)Rest微服务工程构建

1、支付Module模块8001
新建模块cloud-provider-payment8001

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>cloud2020artifactId>
        <groupId>springcloudgroupId>
        <version>1.0-SNAPSHOTversion>
    parent>
    <modelVersion>4.0.0modelVersion>
 
    <artifactId>cloud-provider-payment8001artifactId>
 
    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-actuatorartifactId>
        dependency>
        <dependency>
            <groupId>org.mybatis.spring.bootgroupId>
            <artifactId>mybatis-spring-boot-starterartifactId>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druid-spring-boot-starterartifactId>
            <version>1.1.10version>
        dependency>
        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
        dependency>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-jdbcartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-devtoolsartifactId>
            <scope>runtimescope>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
    dependencies>
project>

application.yml

server:
  port: 8001
 
spring:
  application:
    name: cloud-payment-service # 项目名,也是注册的名字
 
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource  #当前数据源操作类型
    driver-class-name: org.gjt.mm.mysql.Driver    #mysql驱动包
    url: jdbc:mysql://localhost:3306/db2019?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
    username: root
    password: 12345
 
mybatis:
  mapper-locations: classpath:mapper/*.xml
  # 所有Entity 别名类所在包
  type-aliases-package: com.atguigu.springcloud.entities  

主启动类

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

建表SQL

create table `payment`(
    `id` bigint(20) not null auto_increment comment 'ID',
    `serial` varchar(200) default '',
    PRIMARY KEY (`id`)
 
)ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8
select * from payment;

实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Payment implements Serializable {
    private long id; //数据库是bigint
    private String serial;
}

返回给前端的通用json数据串

@Data
@NoArgsConstructor
@AllArgsConstructor
public class CommonResult<T> {
    private Integer code;
    private String message;
    private T data;
    public CommonResult(Integer id,String message){
        this(id,message,null);
    }
}

dao

@Mapper
public interface PaymentDao {
    public int create(Payment payment);
    public Payment getPaymentById(@Param("id") Long id);
}

resource下创建mapper文件夹,新建mapper.xml。在yml里有所有entity别名类所在包,所有payment不用写全类名


DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.atguigu.springcloud.springcloud.dao.PaymentDao">
    <resultMap id="BaseResultMap" type="Payment">
        <id column="id" property="id" jdbcType="BIGINT"/>
        <id column="serial" property="serial" jdbcType="VARCHAR"/>
    resultMap>
    <insert id="create" parameterType="Payment" useGeneratedKeys="true" keyProperty="id">
        insert into payment(serial) values(#{serial})
    insert>
    <select id="getPaymentById" parameterType="Long" resultMap="BaseResultMap">
        select * from payment where id = #{id}
    select>
mapper>

service

public interface PaymentService {
    public int create(Payment payment);
    public Payment getPaymentById(@Param("id") Long id);
}

serviceImpl

@Service
public class PaymentServiceImpl implements PaymentService {
 
    @Resource
    private PaymentDao paymentDao;
 
    @Override
    public int create(Payment payment){
        return paymentDao.create(payment);
    }
 
    @Override
    public Payment getPaymentById(Long id){
        return paymentDao.getPaymentById(id);
    }
}

controller

@RestController
@Slf4j
public class PaymentController {
    @Resource
    private PaymentService paymentService;
 
    @PostMapping(value = "/payment/create")
    public CommonResult create(@RequestBody Payment payment){
        int result = paymentService.create(payment);
        log.info("***********插入结果:"+result);
 
        if (result > 0){
            return new CommonResult(200,"插入数据库成功",result);
        }else {
            return new CommonResult(444,"插入数据库失败",null);
        }
    }
 
    @GetMapping(value = "/payment/get/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id){
        Payment payment = paymentService.getPaymentById(id);
        log.info("***********查询结果:"+payment+"\t"+"oo哈哈");
 
        if (payment!=null){
            return new CommonResult(200,"查询成功",payment);
        }else {
            return new CommonResult(444,"查询失败",null);
        }
    }
}

使用Postman测试:http://localhost:8001/payment/get/31
返回JSON数据:{“code”:200,“message”:“查询成功,serverPort:8001”,“data”:{“id”:31,“serial”:“尚硅谷”}}

热部署配置devtools

效果:代码改动后自动生效,不用重新运行; 重点:热部署只允许在开发阶段使用
第一步:

往springcloud的微服务模块的POM添加【引入jar包】:上面也已经添加好了.
<dependency>
	<groupId>org.springframework.bootgroupId>
	<artifactId>spring-boot-devtoolsartifactId>
	<scope>runtimescope>
	<optional>trueoptional>
dependency>

第二步:
往springcloud的父工程的POM添加【添加插件】:上面也已经添加好了.

<build>
	<plugins>
		<plugin>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-maven-pluginartifactId>
			<version>2.2.2.RELEASEversion>
			<configuration>
			<fork>truefork>
			<addResources>trueaddResources>
			configuration>
		plugin>
	plugins>
build>

第三步:
往idea的settings里面在File | Settings | Build, Execution, Deployment | Compiler
勾选A、D、B、C
SpringCloud学习笔记【零基础篇】SpringCloud介绍及微服务架构编码构建_第10张图片
第四步:
开启idea热部署快捷键 Ctrl+shift+Alt+/ 选第一个 1 Registry… 进入,
勾选
Compiler.automake.allow.when.app.running 和 actionSystem.assertFocusAccessFromEdt
SpringCloud学习笔记【零基础篇】SpringCloud介绍及微服务架构编码构建_第11张图片
第五步
重启Idea

2、消费者订单Module模块80

新建模块cloud-consumer-order80

消费者现在只模拟调用提供者的Controller方法,没有持久层配置,只有Controller和实体类
当然也要配置主启动类和启动端口

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>cloud2020artifactId>
        <groupId>springcloudgroupId>
        <version>1.0-SNAPSHOTversion>
    parent>
 
    <modelVersion>4.0.0modelVersion>
 
    <artifactId>cloud-consumer-order80artifactId>
 
    <dependencies>
        
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-zipkinartifactId>
        dependency>
        
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-netflix-eureka-clientartifactId>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-actuatorartifactId>
        dependency>






 
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-devtoolsartifactId>
            <scope>runtimescope>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
    dependencies>
project>

application.yml

 server:
  port: 80

主启动类

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

实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Payment implements Serializable {
    private long id;
    private String serial;
}

返回给前端的通用json数据串

@Data
@AllArgsConstructor
@NoArgsConstructor
public class CommonResult<T> {
    private Integer code;
    private String message;
    private T data;
 
    public CommonResult(Integer code, String message) {
        this(code, message, null);
    }
}

RestTemplate介绍

RestTemplate提供了多种便捷访问远程Http服务的方法, 是一种简单便捷的访问restful服务模板类,是Spring提供的用于访问Rest服务的客户端模板工具集。

官网地址
https://docs.spring.io/spring-framework/docs/5.2.2.RELEASE/javadoc-api/org/springframework/web/client/RestTemplate.html

使用
使用restTemplate访问restful接口非常的简单粗暴无脑。(url, requestMap, ResponseBean.class)这三个参数分别代表 REST请求地址、请求参数、HTTP响应转换被转换成的对象类型。

config配置类

@Configuration
public class ApplicationContextConfig {
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }
}

controller

@Slf4j
@RestController
public class OrderController {
    //远程调用的地址
    public static final String PAYMENT_URL="http://localhost:8001";
    @Resource
    private RestTemplate restTemplate;
    @PostMapping("/consumer/payment/create")
    public CommonResult<Payment> create(@RequestBody Payment payment){
        return restTemplate.postForObject(PAYMENT_URL+"/payment/create",//请求地址
                                                payment,//请求参数
                                                CommonResult.class);//返回类型
    }
    @GetMapping("/consumer/payment/get/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id")Long id){
        return restTemplate.getForObject(PAYMENT_URL+"/payment/get/"+id,//请求地址
                                            CommonResult.class);//返回类型
    }
}

使用Postman测试:http://localhost/consumer/payment/get/31
返回JSON数据:{“code”:200,“message”:“查询成功,serverPort:8001”,“data”:{“id”:31,“serial”:“尚硅谷”}}

3、工程重构

系统中有重复部分
新建模块cloud-api-commons
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>cloud2020artifactId>
        <groupId>springcloudgroupId>
        <version>1.0-SNAPSHOTversion>
    parent>
    <modelVersion>4.0.0modelVersion>
    <artifactId>cloud-api-commonsartifactId>
    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-devtoolsartifactId>
            <scope>runtimescope>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>
        
        <dependency>
            <groupId>cn.hutoolgroupId>
            <artifactId>hutool-allartifactId>
            <version>5.1.0version>
        dependency>
    dependencies>
project>

实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Payment implements Serializable {
    private long id;
    private String serial;
}

CommonResult通用封装类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Payment implements Serializable {
    private long id;
    private String serial;
}

maven命令clean install
SpringCloud学习笔记【零基础篇】SpringCloud介绍及微服务架构编码构建_第12张图片
订单80和支付8001分别改造,删除各自的原先有过的entities文件夹,分别粘贴

<dependency>
     <groupId>springcloudgroupId>
     <artifactId>cloud-api-commonsartifactId>
     <version>${project.version}version>
dependency>

你可能感兴趣的:(#,SpringCloud学习,spring,cloud,微服务,架构)