天天看點

學習springCloud(一)之項目的搭建

springCloud簡介

SpringCloud就是一套分布式服務治理的架構,既然它是一套服務治理的架構,那麼它本身不會提供具體功能性的操作,更專注于服務之間的通訊、熔斷、監控等。是以就需要很多的元件來支援一套功能。

springCloud架構流程

學習springCloud(一)之項目的搭建

1、外部或者内部的非SpringCloud項目都統一通過API網關(Zuul)來通路内部服務.

2、網關接收到請求後,從注冊中心(Eureka)擷取可用服務

3、由Ribbon進行均衡負載後,分發到後端的具體執行個體

4、微服務之間通過Feign進行通信處理業務

5、Hystrix負責處理服務逾時熔斷

6、Turbine監控服務間的調用和熔斷相關名額

基于springboot和springCloud項目的搭建

既然是微服務,整個項目必然會分成一個個微子產品,

springcloud-api 子產品,作為公共的資訊導入配置子產品;

springcloud-provider-product:作為服務提供者;

springcloud-consumer:作為微服務調用的用戶端使用;

springcloudparent父子產品

建立立一個maven項目:springcloudparent

其中pom檔案如下

<?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>enjoy</groupId>
    <artifactId>springcloud</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>springcloudapi</module>
        <module>springcloudproviderproduct</module>
        <module>springcloudconsumer</module>
    </modules>
    <properties>
        <jdk.version>1.8</jdk.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencyManagement>
    <dependencies>
    <dependency> <!-- 進行SpringCloud依賴包的導入處理 -->
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-dependencies</artifactId>
        <version>Finchley.RELEASE</version>
        <type>pom</type>
        <scope>import</scope>
    </dependency>
    <dependency> 
    <!-- SpringCloud離不開SpringBoot,是以必須要配置此依賴包 -->
    <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-dependencies</artifactId>
        <version>2.1.2.RELEASE</version>
        <type>pom</type>
        <scope>import</scope>
    </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.31</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.0</version>
        </dependency>
        <dependency>
            <groupId>enjoy</groupId>
            <artifactId>microcloud-api</artifactId>
            <version>1.0.0</version>
        </dependency>
    </dependencies>
    </dependencyManagement>
    <build>
        <finalName>microcloud</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>${jdk.version}</source><!-- 源代碼使用的開發版本 -->
                    <target>${jdk.version}</target><!-- 需要生成的目标class檔案的編譯版本 -->
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

           

注意:spingcloud中針對依賴包的版本并不像傳統項目一樣使用的是數字形式定義,反而是使用了一系列英國的地鐵或者城市名字來定義,springcloud使用了springboot,其中對于的版本如下

Release Train Boot Version

Greenwich 2.1.x

Finchley 2.0.x

Edgware 1.5.x

Dalston 1.5.x

公共子產品

【springcloud-api】子產品,建立一個公共模闆,這子產品的主要功能是提供公共處理的工具類,實體,接口等。

pom檔案如下

<?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>springcloud</artifactId>
        <groupId>enjoy</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>springcloud-api</artifactId>
    <version>1.0.0</version>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

</project>

           

由于實體對象不管是服務提供放還是消費者都需要用到,實體對象先建立到api子產品中,建立一個Product實體

package cn.enjoy.vo;
import java.io.Serializable;
public class Product implements Serializable {

    private Long productId;
    private String productName;
    private String productDesc;

    public String getProductDesc() {
        return productDesc;
    }
    public void setProductDesc(String productDesc) {
        this.productDesc = productDesc;
    }
    public String getProductName() {
        return productName;
    }
    public void setProductName(String productName) {
        this.productName = productName;
    }
    public Long getProductId() {
        return productId;
    }
    public void setProductId(Long productId) {
        this.productId = productId;
    }
    @Override
    public String toString() {
        return "Product{" +
                "productId=" + productId +
                ", productName='" + productName + '\'' +
                ", productDesc='" + productDesc + '\'' +
                '}';
    }
}

           

服務提供方子產品

【springcloud-provider-product】建立一個Product Rest提供者的項目子產品,這個子產品對應的資料庫腳本如下

CREATE DATABASE springcloud CHARACTER SET UTF8 ;
USE springcloud ;
CREATE TABLE product (
prodcutId BIGINT AUTO_INCREMENT ,
productName VARCHAR(50) ,
 productDesc VARCHAR(50) ,
CONSTRAINT pk_prodcut_id PRIMARY KEY(prodcutId)
) ;

INSERT INTO product(productName,productDesc) VALUES ('java程式設計',database()) ;
INSERT INTO product(productName,productDesc) VALUES ('Springboot',database()) ;
INSERT INTO product(productName,productDesc) VALUES ('西遊記',database()) ;
INSERT INTO product(productName,productDesc) VALUES ('水浒傳',database()) ;
INSERT INTO product(productName,productDesc) VALUES ('西廂記',database()) ;

           

【springcloud-provider-product】子產品繼續使用mybaits對資料庫進行操作,pom檔案如下

<?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>springcloud</artifactId>
        <groupId>enjoy</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <version>1.0.0</version>

    <artifactId>springcloud-provider-product</artifactId>
    <dependencies>
        <dependency>
            <groupId>enjoy</groupId>
            <artifactId>springcloud-api</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
    </dependencies>

</project>

           

【springcloud-provider-product】建立一個ProductMapper對資料庫的操作接口,這個接口方法特别簡單

package cn.enjoy.mapper;
import cn.enjoy.vo.Product;
import java.util.List;
public interface ProductMapper {
    boolean create(Product product);
    public Product findById(Long id);
    public List<Product> findAll();
}

           

【springcloud-provider-product】新增修改application.yml檔案,追加對mybatis以及資料庫的支援

server:
 port: 8080
mybatis:
 mapper-locations: # 所有的mapper映射檔案
 - classpath:mapping/*.xml
spring:
 datasource:
   type: com.alibaba.druid.pool.DruidDataSource # 配置目前要使用的資料源的操作類型
   driver-class-name: com.mysql.cj.jdbc.Driver # 配置MySQL的驅動程式類
   url: jdbc:mysql://localhost:3306/springcloud?serverTimezone=GMT%2B8 # 資料庫連接配接位址
   username: root # 資料庫使用者名
   password: root1234% # 資料庫連接配接密碼
logging:
  level:
cn.enjoy.mapper: debug


           

【springcloud-provider-product】建立修改 src/main/resources/mapping/ProductMapper.xml檔案

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.enjoy.mapper.ProductMapper">
    <select id="findById" resultType="cn.enjoy.vo.Product" parameterType="long">
        select productId,productName,productDesc from product WHERE productId=#{id} ;
    </select>
    <select id="findAll" resultType="cn.enjoy.vo.Product">
        SELECT productId,productName,productDesc from product;
    </select>
    <insert id="create" parameterType="cn.enjoy.vo.Product">
        INSERT INTO product(productName,productDesc) VALUES (#{productName},database()) ;
    </insert>
</mapper>
           

【springcloud-provider-product】建立IProductService接口,并建立相關實作類

package cn.enjoy.service;
import cn.enjoy.vo.Product;
import java.util.List;
public interface IProductService {
    Product get(long id);
    boolean add(Product product);
    List<Product> list();
}
           

【springcloud-provider-product】 定義主程式類,并定義好mapper掃描包

package cn.enjoy;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("cn.enjoy.mapper")
public class ProductApp{
    public static void main(String[] args) {
        SpringApplication.run(ProductApp.class,args);
    }
}
           

【springcloud-provider-product】建立ProductController建立一個Rest服務類

package cn.enjoy.controller;
import cn.enjoy.service.IProductService;
import cn.enjoy.vo.Product;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
@RestController
@RequestMapping("/prodcut")
public class ProductController {

    @Resource
    private IProductService iProductService;

    @RequestMapping(value="/get/{id}")
    public Object get(@PathVariable("id") long id) {
        return this.iProductService.get(id) ;
    }
    @RequestMapping(value="/add")
    public Object add(@RequestBody Product product) {
        return this.iProductService.add(product) ;
    }
    @RequestMapping(value="/list")
    public Object list() {
        return this.iProductService.list() ;
    }
}
           

服務的消費方

建立一個maven新子產品:【springcloud-consumer】

這個子產品作為服務的消費方,調用前面的product服務

【springcloud-consumer】修改pom檔案,pom檔案内容如下

<?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>springcloud</artifactId>
        <groupId>enjoy</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>springcloud-consumer</artifactId>
    <dependencies>
        <dependency>
            <groupId>enjoy</groupId>
            <artifactId>springcloud-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
    </dependencies>
</project>
           

【springcloud-consumer】修改application.yml配置檔案,該配置檔案還需要色值端口号就行了。

server:
  port: 80
           

【springcloud-consumer】建立Rest配置類,在這需要調用Rest服務,一般需要用到RestTemplate類對象

package cn.enjoy.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestConfig {
    @Bean
    public RestTemplate restTemplate() {
        return  new RestTemplate();
    }
}
           

【springcloud-consumer】建立一個controller,負責使用RestTemplate調用遠端的product服務

package cn.enjoy.controller;
import cn.enjoy.vo.Product;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import java.util.List;
@RestController
@RequestMapping("/consumer")
public class ConsumerProductController {
    public static final String PRODUCT_GET_URL = "http://localhost:8080/prodcut/get/";
    public static final String PRODUCT_LIST_URL="http://localhost:8080/prodcut/list/";
    public static final String PRODUCT_ADD_URL = "http://localhost:8080/prodcut/add/";
    @Resource
    private RestTemplate restTemplate;

    @RequestMapping("/product/get")
    public Object getProduct(long id) {
        Product product = restTemplate.getForObject(PRODUCT_GET_URL + id, Product.class);
        return  product;
    }

    @RequestMapping("/product/list")
    public  Object listProduct() {
        List<Product> list = restTemplate.getForObject(PRODUCT_LIST_URL, List.class);
        return  list;
    }

    @RequestMapping("/product/add")
    public Object addPorduct(Product product) {
        Boolean result = restTemplate.postForObject(PRODUCT_ADD_URL, product, Boolean.class);
        return  result;
    }
}
           

【springcloud-consumer】編寫啟動類

package cn.enjoy;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ConsumerApp {
    public static void main(String[] args) {
        SpringApplication.run(ConsumerApp.class,args);
    }
}

           

調用測試

新增:http://localhost/consumer/product/add?productName=lison

清單查詢:http://localhost/consumer/product/list

獲得單個資料:http://localhost/consumer/product/get?id=1

總結

該子產品目前是基于springboot搭建的,其實springCloud也是依賴于springboot搭建的。該搭建隻是簡單的子產品之間的調用,還沒引入Eureka注冊中心,後續的文章中引入。

繼續閱讀