Java教程

SpringCloud案例准备

本文主要是介绍SpringCloud案例准备,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1. 案例说明

  • 建立一个商品上架的微服务项目,当服务提供者上架新商品,返回商品ID给服务消费者

  • 完整业务流程图:

  

 

 

 1.1 案例数据库环境准备(使用Mysql 5.7.x)

CREATE TABLE products(
id INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(50), #商品名称
price DOUBLE,
flag VARCHAR(2), #上架状态
goods_desc VARCHAR(100), #商品描述
images VARCHAR(400), #商品图片
goods_stock INT, #商品库存
goods_type VARCHAR(20) #商品类型
);

 

 

1.2 工程搭建

1.2.1 父工程 lagou-parent

  • pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>lagou-parent</artifactId>
    <version>1.0-SNAPSHOT</version>
    <!--父工程打包方式-->
    <packaging>pom</packaging>
    <!--spring boot 父启动器依赖-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
    </parent>
    <dependencies>
        <!--web依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--日志依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-logging</artifactId>
        </dependency>
        <!--测试依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--lombok工具-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.4</version>
            <scope>provided</scope>
        </dependency>
        <!-- Actuator可以帮助你监控和管理Spring Boot应用-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <!--热部署-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <!--编译插件-->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>11</source>
                    <target>11</target>
                    <encoding>utf-8</encoding>
                </configuration>
            </plugin>
            <!--打包插件-->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

1.2.2 公共组件微服务

  • pom.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <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>lagou-parent</artifactId>
            <groupId>org.example</groupId>
            <version>1.0-SNAPSHOT</version>
        </parent>
        <modelVersion>4.0.0</modelVersion>
    
        <artifactId>lagou-service-common</artifactId>
        <dependencies>
            <!-- 加强版的mybatis,让具体的Mapper接口继承BaseMapper即可完成相应功能-->
            <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus-boot-starter</artifactId>
                <version>3.3.2</version>
            </dependency>
            <!--pojo持久化使用-->
            <dependency>
                <groupId>javax.persistence</groupId>
                <artifactId>javax.persistence-api</artifactId>
                <version>2.2</version>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <scope>runtime</scope>
            </dependency>
        </dependencies>
    
    </project>
  • 实体类
package entity;


import lombok.Data;

import javax.persistence.Id;
import javax.persistence.Table;

@Data //自动生成getSet方法
@Table(name = "products")//对应数据表名称
public class Products {

  @Id //标识主键
  private long id;
  private String name;
  private double price;
  private String flag;
  private String goodsDesc;
  private String images;
  private long goodsStock;
  private String goodsType;


}

1.2.3 商品微服务

  • pom.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <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>lagou-parent</artifactId>
            <groupId>org.example</groupId>
            <version>1.0-SNAPSHOT</version>
        </parent>
        <modelVersion>4.0.0</modelVersion>
    
        <artifactId>lagou-service-product</artifactId>
        
        <dependencies>
            <dependency>
                <groupId>org.example</groupId>
                <artifactId>lagou-service-common</artifactId>
                <version>1.0-SNAPSHOT</version>
            </dependency>
        </dependencies>
    
    </project>
  • yml文件配置信息
    server:
      port: 9000  # 后期该微服务多实例,9000(10个以内)
    spring:
      application:
        name: lagou-service-product
      datasource:
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://localhost:3306/smd?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
        username: root
        password: 123456
  • mapper接口
    package com.rf.mapper;
    
    import com.baomidou.mybatisplus.core.mapper.BaseMapper;
    import entity.Products;
    
    /**
     * 现在使用的Mybatis-plus组件是Mybatis的加强版
     * 能够与SpringBoot进行非常友好的整合,对比Mybatis框架只有使用便捷的改变
     * 没有具体功能的改变
     * 具体使用:让具体的Mapper接口继承BaseMapper即可
     */
    public interface ProductMapper extends BaseMapper<Products> {
    }
  • service开发
    package com.rf.service;
    
    import entity.Products;
    
    public interface ProductService {
        /**
         * 根据ID查找商品
         * @param id
         * @return
         */
        public Products queryById(Integer id);
    }
    
    
    package com.rf.service.impl;
    
    import com.rf.mapper.ProductMapper;
    import com.rf.service.ProductService;
    import entity.Products;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    @Service
    public class ProductServiceImpl implements ProductService {
        @Autowired
        private ProductMapper productMapper;
        @Override
        public Products queryById(Integer id) {
            return productMapper.selectById(id);
        }
    }
  • controller开发
    package com.rf.controller;
    
    import com.rf.service.ProductService;
    import entity.Products;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    @RequestMapping("/product")
    public class ProductController {
        @Autowired
        private ProductService productService;
        @GetMapping("/query/{id}")
        public Products queryByID(@PathVariable Integer id){
            return productService.queryById(id);
        }
    }
  • 启动类
    package com.rf;
    
    import org.mybatis.spring.annotation.MapperScan;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    @MapperScan("com.rf.mapper")
    public class ProductApplication {
        public static void main(String[] args) {
            SpringApplication.run(ProductApplication.class,args);
        }
    }
  • 测试

 

 

1.2.4 页面静态微服务

  • pom.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <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>lagou-parent</artifactId>
            <groupId>org.example</groupId>
            <version>1.0-SNAPSHOT</version>
        </parent>
        <modelVersion>4.0.0</modelVersion>
    
        <artifactId>lagou-service-page</artifactId>
    
        <dependencies>
            <dependency>
                <groupId>org.example</groupId>
                <artifactId>lagou-service-common</artifactId>
                <version>1.0-SNAPSHOT</version>
            </dependency>
        </dependencies>
    </project>
  • yml文件配置信息
    server:
      port: 9100 # 后期该微服务多实例,端口从9100递增(10个以内)
    spring: 
      application:
        name: lagou-service-page 
      datasource:
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://localhost:3306/smd?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
        username: root
        password: 123456
  • 编写PageController,在PageController中调用商品微服务对应的URL
package com.rf.controller;

import entity.Products;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/page")
public class PageController {
    @Autowired  //封装httpClient对象,执行HTTP请求
    private RestTemplate restTemplate;
    @RequestMapping("/getProduct/{id}")
    public Products getProduct(@PathVariable Integer id){
        String url ="http://localhost:9000/product/query/"; //URL地址硬编码
        Products products = restTemplate.getForObject(url + id, Products.class);
        return products;
    }

}
  • 编写启动类,注入RestTemplate
package com;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
public class PageApplication {
    @Bean  //封装httpClient对象,执行HTTP请求
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }

    public static void main(String[] args) {
        SpringApplication.run(PageApplication.class,args);
    }
}
  • 测试

1.3 存在问题与解决方案

  • 在服务消费者中,我们把url地址硬编码到代码中,不方便后期维护===》服务管理:自动注册与发现、状态监管
  • 服务提供者只有一个服务,即便服务提供者形成集群,服务消费者还需要自己实现负载均衡===》服务负载均衡
  • 在服务消费者中,不清楚服务提供者的状态===》熔断机制
  • 服务消费者调用服务提供者时候,如果出现故障能否及时发现不向用户抛出异常页面?===》远程过程调用
  • RestTemplate这种请求调用方式是否还有优化空间?能不能类似于Dubbo那样玩?==-》网关拦截、路由转发
  • 这么多的微服务统一认证如何实现?===》网关拦截、路由转发、统一认证
  • 配置文件每次都修改好多个很麻烦!?===》集中式配置管理,配置信息实时自动更新

2. 第一代 Spring Cloud 核心组件

2.1 Eureka服务注册中心

  • 服务注册中心
  • Eurake
  • 搭建Eureka Server服务注册中心
  • 搭建Eureka Server 高可用集群

2.2 Ribbon负载均衡

这篇关于SpringCloud案例准备的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!