• SpringCloud入门案例



    📃个人主页:不断前进的皮卡丘
    🌞博客描述:梦想也许遥不可及,但重要的是追梦的过程,用博客记录自己的成长,记录自己一步一步向上攀登的印记
    🔥个人专栏:微服务专栏

    创建父工程

    在这里插入图片描述

    删除src目录

    然后把maven改成自己的本地仓库

    字符编码

    在这里插入图片描述

    注解生效激活

    在这里插入图片描述

    Java编译版本1.8

    在这里插入图片描述

    pom依赖

    在这里插入图片描述

    
    <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>com.zyh.springcloudgroupId>
        <artifactId>cloud2022artifactId>
        <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>8.0.26mysql.version>
            <druid.version>1.1.16druid.version>
            <mybatis.spring.boot.version>1.3.0mybatis.spring.boot.version>
        properties>
    
        
        <dependencyManagement>
            <dependencies>
                
                <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>
                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>
                <dependency>
                    <groupId>org.projectlombokgroupId>
                    <artifactId>lombokartifactId>
                    <version>${lombok.version}version>
                    <optional>trueoptional>
                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>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101

    微服务架构编码构建-Rest微服务-【服务提供者】

    创建子模块

    在这里插入图片描述

    pom依赖

     <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>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44

    yml

    server:
      port: 8001
    
    spring:
      application:
        name: cloud-payment-service
      datasource:
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://localhost:3306/cloud2022?serverTimezone=Asia/Shanghai&useSSL=true&useUnicode=true&characterEncoding=UTF-8
        username: root
        password: 123456
    
    mybatis:
      mapperLocations: classpath:/mapper/*.xml
      type-aliases-package: com.zyh.springcloud.entities
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    主启动类

    在这里插入图片描述

    数据库

    CREATE DATABASE  IF NOT EXISTS cloud2022 DEFAULT CHARACTER SET utf8 ;
    
    USE cloud2022 ;
    
    DROP TABLE IF EXISTS payment ;
    
    CREATE TABLE payment (
      id BIGINT (20) NOT NULL AUTO_INCREMENT COMMENT 'ID',
      SERIAL VARCHAR (300) DEFAULT NULL,
      PRIMARY KEY (id)
    ) ENGINE = INNODB AUTO_INCREMENT = 33 DEFAULT CHARSET = utf8 ;
    
    INSERT INTO payment (id, SERIAL) VALUES(1, '皮卡丘1'),(2, '皮卡丘2') ;
    
     
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    实体类

    在这里插入图片描述

    在这里插入图片描述

    Controller

    com.zyh.springcloud.controller.PaymentController

    @RestController
    @Slf4j
    public class PaymentController {
    
        @Autowired
        private PaymentService paymentService;
    
        @PostMapping(value = "/payment/create")
        public CommonResult<Payment> create(@RequestBody Payment payment){
            int result = paymentService.create(payment);
            log.info("*****插入结果:"+payment);
            if (result>0){  //成功
                return new CommonResult(200,"插入数据库成功",payment);
            }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);
            if (payment!=null){  //说明有数据,能查询成功
                return new CommonResult(200,"查询成功",payment);
            }else {
                return new CommonResult(444,"没有对应记录,查询ID:"+id,null);
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    Service

    com/zyh/springcloud/service/PaymentService.java

    public interface PaymentService {
        /**
         * 存储数据
         * @param payment
         * @return
         */
         int create(Payment payment);
    
        /**
         * 获取数据
         * @param id
         * @return
         */
          Payment getPaymentById(Long id);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    Service的实现类

    com/zyh/springcloud/service/impl/PaymentServiceImpl.java

    @Service
    public class PaymentServiceImpl implements PaymentService {
        @Autowired
        private PaymentMapper paymentMapper;
        @Override
        public int create(Payment payment) {
            return paymentMapper.create(payment);
        }
    
        @Override
        public Payment getPaymentById(Long id) {
            return paymentMapper.getPaymentById(id);
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    Mapper

    com/zyh/springcloud/mapper/PaymentMapper.java

    @Mapper
    public interface PaymentMapper {
        /**
         * 插入一条数据
         * @param payment
         * @return
         */
        int create(Payment payment);
    
        /**
         * 根据id查询数据
         * @param id
         * @return
         */
        Payment getPaymentById(@Param("id") long id);
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    Mapper映射文件

    
    DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.zyh.springcloud.mapper.PaymentMapper">
        <insert id="create"  useGeneratedKeys="true" keyProperty="id">
            insert into payment(serial) values(#{serial});
        insert>
    
        <resultMap id="BaseResultMap" type="com.zyh.springcloud.entities.Payment">
            <id column="id" property="id" jdbcType="BIGINT">id>
            <result column="serial" property="serial" jdbcType="VARCHAR">result>
        resultMap>
    
        <select id="getPaymentById"  parameterType="Long" resultMap="BaseResultMap">
            select * from payment where id=#{id}
        select>
    mapper>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    在这里插入图片描述

    测试

    在这里插入图片描述

    在这里插入图片描述

    image.png

    微服务架构编码构建-Rest微服务-【服务消费者】

    新建模块

    在这里插入图片描述

    导入依赖

    <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.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>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    yml

    server:
      port: 80
    spring:
      application:
        name: cloud-consumer-order80
    
    • 1
    • 2
    • 3
    • 4
    • 5

    主启动类

    在这里插入图片描述

    创建entities

    (将cloud-provider-payment8001工程下的entities包下的两个实体类复制过来)

    RestTemplate

    • RestTemplate提供了多种便捷访问远程Http服务的方法,是一种简单便捷的访问Restful服务模板类,是Spring 提供的用于访问Rest服务的客户端模板工具集。
    • Spring框架提供的RestTemplate类可用于在应用中调用rest服务,它简化了与http服务的通信方式,统

    一了RESTful的标准,封装了http链接, 我们只需要传入url及返回值类型即可。相较于之前常用的HttpClient,RestTemplate是一种更优雅的调用RESTful服务的方式。

    • 在Spring应用程序中访问第三方REST服务与使用Spring RestTemplate类有关。RestTemplate类的设计

    原则与许多其他Spring 模板类(例如JdbcTemplate、JmsTemplate)相同,为执行复杂任务提供了一种具
    有默认行为的简化方法。

    • RestTemplate默认依赖JDK提供http连接的能力(HttpURLConnection),如果有需要的话也可以通过

    setRequestFactory方法替换为例如 Apache HttpComponents、Netty或OkHttp等其它HTTP library。
    考虑到RestTemplate类是为调用REST服务而设计的,因此它的主要方法与REST的基础紧密相连就不足
    为奇了,后者是HTTP协议的方法:HEAD、GET、POST、PUT、DELETE和OPTIONS。例如, RestTemplate类具有headForHeaders()、getForObject()、postForObject()、put()和delete()等方法。

    在这里插入图片描述

    配置类

    在这里插入图片描述

    把service拷贝过来
    在这里插入图片描述

    controller

    @RestController
    @Slf4j
    public class OrderController {
        /*面向接口编程:推荐,但是需要使用OpenFeign组件
        @Autowired
        private PaymentService paymentService;
    
        @RequestMapping("/consumer/payment/get/{id}")
        public CommonResult get(@PathVariable("id")Long id){
            Payment payment = paymentService.getPaymentById(id);
            System.out.println("payment:"+payment);
            return new CommonResult(200,"操作成功",payment);
    
        }
    
        @PostMapping("/consumer/payment/create")
        public CommonResult create(@RequestBody Payment payment){
            System.out.println("payment:"+payment);
            paymentService.create(payment);
            return new CommonResult(200,"操作成功",payment);
        }
        */
    
        /**
         * 基于RestTemplate模板类进行远程调用
         */
        public static final String PAYMENT_URL = "http://localhost:8001";
    
        @Autowired
        private RestTemplate restTemplate;
    
        @RequestMapping("/consumer/payment/get/{id}")
        public CommonResult get(@PathVariable("id") Long id) {
            CommonResult<Payment> commonResult = restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
            log.info("commonResult:" + commonResult);
            return commonResult;
        }
    
        @PostMapping("/consumer/payment/create")
        public CommonResult create(@RequestBody Payment payment) {
            log.info("payment:"+payment);
            CommonResult commonResult = restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, CommonResult.class);
            return commonResult;
        }
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47

    测试

    1. 先启动cloud-provider-payment8001
    2. 再启动cloud-consumer-order80
    3. http://localhost/consumer/payment/get/1
    4. 不要忘记@RequestBody注解
    5. 服务提供者接口方法需要增加@RequestBody注解;否则,接收不到数据。
      在这里插入图片描述

      在这里插入图片描述

      在这里插入图片描述

    代码改善

    存在的问题

    上面所写的模块,存在以下问题,两个模块都用到了实体类,但是代码是重复的,我们可以提取出来。
    在这里插入图片描述

    在这里插入图片描述

    新建:cloud-api-commons

    pom依赖

    
    <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>cloud2022artifactId>
            <groupId>com.zyh.springcloudgroupId>
            <version>1.0-SNAPSHOTversion>
        parent>
        <modelVersion>4.0.0modelVersion>
    
        <groupId>com.zyh.springcloudgroupId>
        <version>1.0-SNAPSHOTversion>
        <artifactId>cloud-api-commonsartifactId>
        
        <properties>
            <maven.compiler.source>8maven.compiler.source>
            <maven.compiler.target>8maven.compiler.target>
        properties>
        <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>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41

    把公共代码写在这个模块中,然后删除上面那两个模块的重复代码

    然后把cloud-api-commons模块的坐标添加到消费者和提供者的pom文件中

    <groupId>com.zyh.springcloud</groupId>
        <version>1.0-SNAPSHOT</version>
        <artifactId>cloud-api-commons</artifactId>
    
    • 1
    • 2
    • 3

    在这里插入图片描述

    测试

    在这里插入图片描述

  • 相关阅读:
    探索计算机视觉技术的应用前景
    Spring Boot整合Thymeleaf
    C++ 基础入门 之 结构体/结构体定义和使用/结构体数组/结构体指针/ 结构体嵌套结构体/结构体做函数参数/结构体中 const 使用场景/结构体案例
    成功解决:Xshell 无法连接虚拟机。如何使用Xshell连接CentOS7虚拟机(详细步骤过程)
    在pycharm中通过ctrl进入调用函数,如何返回到原函数
    java面试100题(应届生必备)
    【Java】Spring scruity 简单上手
    Vue实现简易购物车功能
    Python常用函数
    linux上gitlab备份与还原
  • 原文地址:https://blog.csdn.net/qq_52797170/article/details/127682504