SpringCloud系列二:硬編碼實現簡單的服務提供者與服務消費者

從本文開始,以一個電影售票系統爲例講解Spring Cloudhtml

1. 版本java

  jdk:1.8web

  SpringBoot:2.0.0.RELEASEspring

  SpringCloud:Finchley.M8sql

2. 系統信息數據庫

  使用Spring Data JPA做爲持久層框架,使用H2做爲數據庫apache

3. 編寫服務提供者網絡

  開發:架構

  > 建立一個Spring Boot項目。pom.xml內容以下:app

<?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>com.itmuch.cloud</groupId>
    <artifactId>microservice-simple-provider-user</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

  其中,spring-boot-starter-web提供了SpringMVC支持;spring-boot-starter-data-jpa提供了Spring Data JPA的支持。

  > 準備好建表語句,在項目的resources目錄下建立sql文件夾,在sql文件夾下創建schema.sql,並添加以下內容:

DROP TABLE user if EXISTS; CREATE TABLE user ( id bigint generated BY DEFAULT AS IDENTITY, username VARCHAR(40), name VARCHAR(20), age INT(3), balance DECIMAL(10, 2), PRIMARY KEY (id) );

  > 準備幾條數據,在sql文件夾下建立data.sql,並添加以下內容:

INSERT INTO user (id, username, name, age, balance) VALUES (1, 'account1', '張三', 20, 100.00); INSERT INTO user (id, username, name, age, balance) VALUES (2, 'account2', '李四', 28, 180.00); INSERT INTO user (id, username, name, age, balance) VALUES (3, 'account3', '王五', 32, 280.00);

  > 建立用戶實體類

package com.itmuch.cloud.microservicesimpleprovideruser.pojo; import javax.persistence.*; import java.math.BigDecimal; @Entity public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column private String username; @Column private String name; @Column private Integer age; @Column private BigDecimal balance; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public BigDecimal getBalance() { return balance; } public void setBalance(BigDecimal balance) { this.balance = balance; } }

  > 建立DAO

package com.itmuch.cloud.microservicesimpleprovideruser.dao; import com.itmuch.cloud.microservicesimpleprovideruser.pojo.User; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface UserRepository extends JpaRepository<User, Long> { }

  > 建立Controller

package com.itmuch.cloud.microservicesimpleprovideruser.controller; import com.itmuch.cloud.microservicesimpleprovideruser.dao.UserRepository; import com.itmuch.cloud.microservicesimpleprovideruser.pojo.User; 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.RestController; @RestController public class UserController { @Autowired private UserRepository userRepository; @GetMapping("/{id}") public User findById(@PathVariable Long id) { User findOne = userRepository.findById(id).get(); return findOne; } }

  > 編寫配置文件。將application.properties重命名爲application.yml。

server: port: 8000 spring: jpa: generate-ddl: false show-sql: true hibernate: ddl-auto: none datasource: # 指定數據源 platform: h2 # 指定數據源類型 url: jdbc:h2:mem:cloud # 指定h2數據庫的鏈接地址 driver-class-name: org.h2.Driver # 指定h2數據庫的驅動 username: root # 指定h2數據庫的登陸用戶 password: 20121221 # 指定h2數據庫的登陸密碼 schema: classpath:/sql/schema.sql # 指定h2數據庫的建表腳本 data: classpath:/sql/data.sql # 指定h2數據庫的數據腳本 h2: console: path: /h2-console enabled: true logging: level: org.hibernate: info org.hibernate.type.descriptor.sql.BasicBinder: TRACE org.hibernate.type.descriptor.sql.BasicExtractor: TRACE info: app: name: microservice-simple-provider-user encoding: UTF-8 java: source: 1.8 target: 1.8

  測試:

  在開發中整合了actuator模塊,Spring Boot Actuator提供了不少監控端點。

  具體可查看:http://www.cnblogs.com/jinjiyese153/p/8607895.html

  > Spring Boot Actuator測試

  啓動Spring Boot項目,訪問:http://localhost:8000/actuator/health,若以下圖,則正常

  (默認只展現狀態,詳細信息不展現。若想查看詳細信息,可點擊上方URL查看

  > 項目測試

  啓動Spring Boot項目,訪問:http://localhost:8000/1,若以下圖,則正常

 4. 編寫服務消費者

  開發:

  > 建立一個Spring Boot項目。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>com.itmuch.cloud</groupId>
    <artifactId>microservice-simple-consumer-movie</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

  > 建立一個用戶實體類

package com.itmuch.cloud.microservicesimpleconsumermovie.pojo; import java.math.BigDecimal; public class User { private Long id; private String username; private String name; private Integer age; private BigDecimal balance; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public BigDecimal getBalance() { return balance; } public void setBalance(BigDecimal balance) { this.balance = balance; } }

  > 修改啓動類

package com.itmuch.cloud.microservicesimpleconsumermovie; 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 MicroserviceSimpleConsumerMovieApplication { public static void main(String[] args) { SpringApplication.run(MicroserviceSimpleConsumerMovieApplication.class, args); } @Bean public RestTemplate restTemplate() { return new RestTemplate(); } }

  > 建立Controller,在其中使用RestTemplate請求用戶微服務的API。

package com.itmuch.cloud.microservicesimpleconsumermovie.controller; import com.itmuch.cloud.microservicesimpleconsumermovie.pojo.User; 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.RestController; import org.springframework.web.client.RestTemplate; @RestController public class MovieController { @Autowired private RestTemplate restTemplate; @GetMapping("/user/{id}") public User findById(@PathVariable Long id) { return this.restTemplate.getForObject("http://localhost:8000/" + id, User.class); } }

  > 編寫配置文件。將application.properties重命名爲application.yml。

server: port: 8010 info: app: name: microservice-simple-consumer-movie encoding: UTF-8 java: source: 1.8 target: 1.8

  測試:

  在開發中一樣整合了actuator模塊

  具體可查看:http://www.cnblogs.com/jinjiyese153/p/8607895.html

  > Spring Boot Actuator測試

  啓動Spring Boot項目,訪問:http://localhost:8010/actuator/health,若以下圖,則正常

  > 項目測試

  啓動Spring Boot項目,訪問:http://localhost:8010/user/1,若以下圖,則正常

5. 總結

  在傳統的應用程序中,通常都是這樣作的。然而,這種方式存在問題。

  1. 適用場景有限:若是服務提供者的網絡地址(IP和端口)發生了變化,將會影響服務消費者。

  2. 沒法動彈伸縮:在生成環境中,每一個微服務通常都會部署多個實例,從而實現容災和負載均衡。在微服務架構的系統中,還須要系統具有自動伸縮的能力,例如動態增長節點等。硬編碼沒法適應這種需求。

  將會在下一篇博客中,解決這些問題。敬請期待~~~

6. 參考
  周立 --- 《Spring Cloud與Docker微服務架構與實戰》

相關文章
相關標籤/搜索