使用Spring Cloud构建简单的微服务

◇目标

使用SpringCloud构建简单的微服务。

◇目标

创建一个服务,当接收到来自客户端的请求时,从数据库中获取(SELECT)的值并返回。

【目标】整体情况

4.png
構成要素名役割APIGatewayリバースプロキシの役割を担う。Zuulを使用。DiscoveryServiceサービスの登録/検索/呼出の役割を担う。Eurekaを使用。ConfigService各サービスのプロパティをGitLabから取得し、返却する。Spring Cloud Configを使用。GitLab各サービスのプロパティを管理する。(ポート番号/DBのURL・ユーザ・パスワード等)ProductServiceリクエストされたDB値をJSONで返却する。

【目标】补充说明

由于希望主要讨论各服务的构建和联接方法,所以不使用HA结构。
※ 在HA结构的情况下,会将各服务冗余化,并添加一个负载均衡器。

◇基础条件

    • Windows7 64bit環境のローカルマシン上でサービスを動かす。

 

    • DBはPostgreSQLをローカルマシンにインストールして使用。

 

    • GitLabはGitLab.comを使用。

 

    • Spring Boot 2.0.0.RELEASE、Spring Cloud Finchley.M8を使用。

 

    • IDEは↓で構築したSTSを使用。

 

    Spring Tool Suite(STS)のインストール&日本語化&Gradleプラグイン追加の手順

◇已经完成的代码

这是网址:https://gitlab.com/tk_230to/spring-cloud-msa-sample

◇仅需一种选择,在汉语中转述以下内容:

Spring Cloud参考手册请点击此处https://spring.io/docs/reference。

◇摘要

准备工作

    1. 【准备】安装PostgreSQL并创建数据库

 

    【准备】创建GitLab仓库

建立

    1. 创建ConfigService

 

    1. 创建DiscoveryService

 

    1. 创建ProductService

 

    创建APIGateway

◇准备

1. 【准备】安装PostgreSQL并创建数据库。

本次我们将在本地准备一个由ProductService连接的数据库。
我们将使用PostgreSQL。

1.1 下载

从下载链接中选择PostgreSQL的版本和操作系统进行下载。

undefined

安装 1.2

运行下载的安装程序,除了以下设置其他全部默认选项:
– 密码:”postgres”(可使用您喜欢的密码)
– 区域设置:”日本,日本”
– 堆栈构建器:无

1.3 创建表格 (Yī

创建一个带有商品ID(item_id)和商品名称(item_name)的简单商品表格。

1.3.1 创建商品表格

Noカラム名型NotNullPK1item_idinteger○○2item_namecharacter varying(255)○

1.3.2 创建表的步骤

(1) 在「开始」菜单中搜索「pgadmin」,然后运行「pgAdmin 4」。
(2) 在「pgAdmin 4」的界面中,点击「工具」,再选择「查询工具」。
(3) 将下方的SQL语句粘贴进去,按下「F5」执行。

-- item_idのシーケンス作成
CREATE SEQUENCE item_id_seq;

-- テーブル作成
CREATE TABLE public.item
(
    item_id integer PRIMARY KEY DEFAULT nextval('item_id_seq'),
    item_name character varying(255) COLLATE pg_catalog."default" NOT NULL
)
WITH (
    OIDS = FALSE
)
TABLESPACE pg_default;

ALTER TABLE public.item
    OWNER to postgres;

1.4 数据注册

(1) 将下面的SQL语句粘贴并点击“F5”来执行。

INSERT INTO item (item_name) VALUES ('商品1');

创建GitLab仓库的【准备工作】

创建一个GitLab仓库来管理属性。

创建GitLab.com的免费账户。

undefined
undefined
undefined

2.2 创建存储库

undefined

创建2.3主分支

undefined

建立

由于PostgreSQL和GitLab已经准备就绪,所以我们可以开始创建服务。

1. 创建ConfigService

由于各项服务的属性都是从ConfigService中获取的,
所以如果ConfigService没有完成,各项服务就无法运行。
因此,首先需要创建ConfigService。

摘要步骤

手順概要1.1 プロジェクト作成「Springスターター・プロジェクト」でプロジェクトの雛形を作成1.2 Javaアプリケーション作成「@EnableConfigServer」にて、私はConfigServiceですよと宣言1.3 build.gradleファイル作成動作するSpringのバージョンを設定1.4 プロパティファイル作成GitLabのURIや起動ポート番号を設定1.5 動作確認実行してみる

1. 创建项目

创建一个新项目。

启动STS,点击”文件”→”新建”→”Spring Starter项目”。

1.1.2 设定项目名称等

undefined

1.1.3 建立依存关系

undefined

1.2 创建Java应用程式

在src/main/java的ConfigServiceApplication.java文件中添加”@EnableConfigServer”注解。

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;

@SpringBootApplication
@EnableConfigServer // ←付与
public class ConfigServiceApplication {

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

1. 创建1.3版本的build.gradle文件

将版本更改为可执行的版本。
将springBootVersion更改为’2.0.0.RELEASE’。
将springCloudVersion更改为’Finchley.M8’。

buildscript {
    ext {
        springBootVersion = '2.0.0.RELEASE' // 変更
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
    mavenCentral()
    maven { url "https://repo.spring.io/milestone" }
}


ext {
    springCloudVersion = 'Finchley.M8' // 変更
}

dependencies {
    compile('org.springframework.cloud:spring-cloud-config-server')
    testCompile('org.springframework.boot:spring-boot-starter-test')
}

dependencyManagement {
    imports {
        mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
    }
}

创建1.4版本的属性文件。

创建1.4.1的bootstrap.yml文件。

将src/main/resources的application.properties重命名为bootstrap.yml并进行编辑。
bootstrap.yml是Spring Boot中被优先获取的属性文件。

# サービス名
spring.application.name: ConfigService

# 使用するポート番号
server.port: 8888

# GitリポジトリURI (「2. 【準備】GitLabリポジトリ作成」で作成したGitLabのURIに変えてください)
spring.cloud.config.server.git.uri: https://gitlab.com/tk_230to/conf.git

1.5 确定操作

1.5.1 最新化Gradle的依赖关系

右键点击「ConfigService」→「Gradle」→「刷新Gradle项目」。

1.5.2 服务启动

右击「ConfigService」→选择「运行」→选择「Spring Boot应用程序」。

尝试访问1.5.3

如果尝试访问 http://localhost:8888/admin/env 并且获得了 JSON 响应,则表示OK。
如果想要更清晰地查看,可以使用 DHC REST Client 等工具。

undefined

2. 创建DiscoveryService

步骤概览

手順概要2.1 プロジェクト作成「Springスターター・プロジェクト」でプロジェクトの雛形を作成2.2 Javaアプリケーション作成「@EnableEurekaServer」にて、私はEurekaですよと宣言2.3 build.gradleファイル作成動作するSpringのバージョンを設定2.4 プロパティファイル作成(1)ConfigServiceのURIと自サービス名を教える(bootstrap.yml)
(2)自身のプロパティをGitLabに登録(DiscoveryService.yml)2.5 動作確認実行してみる

2.1 创建项目

类似于”ConfigService创建”,不同之处在于加粗字体。
– 项目名称 = “DiscoveryService”,类型 = “Gradle(Buildship 2.x)”。
– 在依赖项中选择”Eureka服务器”和”配置客户端”,然后完成。

2.2 创建Java应用程序

在src/main/java的DiscoveryServiceApplication.java文件中加上“@EnableEurekaServer”和“@RefreshScope”注解。

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@SpringBootApplication
@EnableEurekaServer // ←追加
@RefreshScope // ←追加
public class DiscoveryServiceApplication {

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

创建2.3版本的build.gradle文件。

与1.3相同。

buildscript {
    ext {
        springBootVersion = '2.0.0.RELEASE' // 変更
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
    mavenCentral()
    maven { url "https://repo.spring.io/milestone" }
}


ext {
    springCloudVersion = 'Finchley.M8' // 変更
}

dependencies {
    compile('org.springframework.cloud:spring-cloud-starter-config')
    compile('org.springframework.cloud:spring-cloud-starter-netflix-eureka-server')
    testCompile('org.springframework.boot:spring-boot-starter-test')
}

dependencyManagement {
    imports {
        mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
    }
}

创建2.4属性文件

创建两种文件,分别为bootstrap.yml和DiscoveryService.yml。

種類説明bootstrap.ymlConfigServiceに関するプロパティを保持。それ以外のプロパティは↓に保持。DiscoveryService.ymlGitLabに外出しするプロパティ。ConfigServiceから取得される。

创建bootstrap.yml文件

将src/main/resources下的application.properties文件重命名为bootstrap.yml并进行编辑。
ConfigService将会获取到”{服务名}.yml”(DiscoveryService.yml)。
※确切地说是”{服务名}-{配置文件名}.yml”。
配置文件名可以是product/development/default。
为了避免混淆,本次省略配置文件名。

# サービス名
spring.application.name: DiscoveryService

# ConfigServiceのURI
spring.cloud.config.uri: http://localhost:8888

创建DiscoveryService.yml文件。

在GitLab的代码库中创建DiscoveryService.yml文件。

# 使用するポート番号(デフォルト8761だが分かりやすく明示)
server.port: 8761

# 自分自身をEurekaのレジストリに登録しない
eureka.client.registerWithEureka: false
eureka.client.fetchRegistry: false
undefined

确认动作

与1.5相同,但是因为要从ConfigService获取属性,所以要先启动ConfigService,然后再启动DiscoveryService的顺序。

undefined

3. 创建产品服务

手順概述

手順概要3.1 プロジェクト作成「Springスターター・プロジェクト」でプロジェクトの雛形を作成3.2 Javaアプリケーション作成「@EnableEurekaClient」でEurekaクライアント宣言3.3 Entityクラス作成商品テーブルの情報を保持するクラスを作成3.4 Repositoryクラス作成商品テーブルのCRUDクラスを作成3.5 build.gradleファイル作成動作するSpringのバージョンを設定3.6 プロパティファイル作成(1)ConfigServiceのURIと自サービス名を教える(bootstrap.yml)
(2)自身のプロパティをGitLabに登録(ProductService.yml)3.7 動作確認実行してみる

创建项目

与「ConfigService作成」相似,不同之处在于加粗字体。
– 项目名称为「ProductService」,类型为「Gradle (Buildship 2.x)」。
– 在依赖关系中选择「Eureka Discovery」、「配置客户端」、「JPA」、「Rest Repository」和「PostgreSQL」并完成。

3.2 创建Java应用程序

在src/main/java的ProductServiceApplication.java文件中添加”@EnableEurekaClient”和”@RefreshScope”。

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@SpringBootApplication
@EnableEurekaClient // ←追加
@RefreshScope // ←追加
public class ProductServiceApplication {

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

3.3 创建实体类Entity

在src/main/java中创建商品表的实体类。

package com.example.demo;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="item")
public class Item implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @Column(name="item_id")
    private Integer itemId;

    @Column(name="item_name")
    private String itemName;

    public Integer getItemId() {
        return itemId;
    }

    public void setItemId(Integer itemId) {
        this.itemId = itemId;
    }

    public String getItemName() {
        return itemName;
    }

    public void setItemName(String itemName) {
        this.itemName = itemName;
    }
}

由于使用Lombok时,GET响应中没有输出商品名称,因此直接编写了getter/setter。

创建3.4仓库类(Repository class)。

在src/main/java中创建一个用于操作商品表CRUD的Repository类。由于使用了”JpaRepository”,因此还会创建Rest URI的终点。

package com.example.demo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface ItemRepository extends JpaRepository<Item, Integer> {
}

创建一个3.5版本的build.gradle文件。

与1.3相似。

buildscript {
    ext {
        springBootVersion = '2.0.0.RELEASE' // 変更
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
    mavenCentral()
    maven { url "https://repo.spring.io/milestone" }
}


ext {
    springCloudVersion = 'Finchley.M8' // 変更
}

dependencies {
    compile('org.springframework.boot:spring-boot-starter-data-jpa')
    compile('org.springframework.boot:spring-boot-starter-data-rest')
    compile('org.springframework.cloud:spring-cloud-starter-config')
    compile('org.springframework.cloud:spring-cloud-starter-netflix-eureka-client')
    runtime('org.postgresql:postgresql')
    testCompile('org.springframework.boot:spring-boot-starter-test')
}

dependencyManagement {
    imports {
        mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
    }
}

3.6 创建属性文件

创建两种类型的bootstrap.yml和ProductService.yml,与2.4版本相似。

创建一个3.6.1版本的bootstrap.yml文件。

将src/main/resources目录下的application.properties文件重命名为bootstrap.yml,并进行编辑。

# サービス名
spring.application.name: ProductService

# ConfigServiceのURI
spring.cloud.config.uri: http://localhost:8888

创建3.6.2 ProductService.yml文件

在GitLab仓库中创建ProductService.yml文件。

# 使用するポート番号
server:
  port: 8081

# DB接続情報
spring:
  datasource:
    driver-class-name: org.postgresql.Driver
    url: jdbc:postgresql://localhost:5432/postgres
    username: postgres
    password: postgres

# Eurekaの情報
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/

3.7 确认操作

undefined

创建API网关

操作流程概览

手順概要4.1 プロジェクト作成「Springスターター・プロジェクト」でプロジェクトの雛形を作成4.2 Javaアプリケーション作成「@EnableZuulProxy」にて、Zuul Proxyを有効化4.3 build.gradleファイル作成動作するSpringのバージョンを設定4.4 プロパティファイル作成(1)ConfigServiceのURIと自サービス名を教える(bootstrap.yml)
(2)自身のプロパティをGitLabに登録(APIGateway.yml)4.5 動作確認実行してみる

创立项目

与「ConfigService创建」相似,不同之处在于粗体部分。
– 项目名称 =「APIGateway」,类型 =「Gradle (Buildship 2.x)」。
– 在依赖项中选择「Eureka发现」「配置客户端」「Zuul」以完成。

4.2创建Java应用程序

在`src/main/java`目录下的`APIGatewayApplication.java`文件中添加`@EnableZuulProxy`、`@EnableEurekaClient`和`@RefreshScope`注解。

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;

@SpringBootApplication
@EnableEurekaClient // ←追加
@RefreshScope // ←追加
@EnableZuulProxy // ←追加
public class ApiGatewayApplication {

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

创建4.3版本的build.gradle文件。

与1.3相同。

buildscript {
    ext {
        springBootVersion = '2.0.0.RELEASE' // 変更
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
    mavenCentral()
    maven { url "https://repo.spring.io/milestone" }
}


ext {
    springCloudVersion = 'Finchley.M8' // 変更
}

dependencies {
    compile('org.springframework.cloud:spring-cloud-starter-config')
    compile('org.springframework.cloud:spring-cloud-starter-netflix-eureka-client')
    compile('org.springframework.cloud:spring-cloud-starter-netflix-zuul')
    testCompile('org.springframework.boot:spring-boot-starter-test')
}

dependencyManagement {
    imports {
        mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
    }
}

4.4 创建属性文件

生成2种类型的配置文件,包括bootstrap.yml和APIGateway.yml,与2.4版本相同。

创建4.4.1版本的bootstrap.yml文件。

将src/main/resources目录下的application.properties文件重命名为bootstrap.yml并进行编辑。

# サービス名
spring.application.name: APIGateway

# ConfigServiceのURI
spring.cloud.config.uri: http://localhost:8888

创建了4.4.2版本的APIGateway.yml。

在GitLab的代码仓库中创建一个APIGateway.yml文件。

# 使用するポート番号
server:
  port: 8000

# Eurekaの情報
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/

# ProductServiceのルート情報
zuul:
  routes:
    users:
      path: /items/**
      serviceId: ProductService
      stripPrefix: false

4.5 运作确认

以与2.5相同的方式,按照ConfigService→DiscoveryService→ProductService→APIGateway的顺序启动。
尝试访问http://localhost:8000/items/1,如果返回”商品1″,则表示正常。

广告
将在 10 秒后关闭
bannerAds