Docker下的Spring Cloud三部曲之二:细说Spring Cloud开发

简介: 《Docker下的Spring Cloud三部曲》系列的第二篇,详细讲解上一篇实例中用到的eureka、provider、consumer等三个应用的开发过程

欢迎访问我的GitHub

这里分类和汇总了欣宸的全部原创(含配套源码): https://github.com/zq2599/blog_demos

本篇概览

  • 本文是《Docker下的Spring Cloud三部曲》系列的第二篇,详细讲解上一篇实例中用到的eureka、provider、consumer等三个应用的开发过程;

环境信息

  • 回顾一下实战环境,如下图:

这里写图片描述

源码地址

  • 上图的eureka、provider、consumer是三个spring boot的web工程,源码可以在GitHub下载,地址和链接信息如下表所示:
名称 链接 备注
项目主页 https://github.com/zq2599/blog_demos 该项目在GitHub上的主页
git仓库地址(https) https://github.com/zq2599/blog_demos.git 该项目源码的仓库地址,https协议
git仓库地址(ssh) git@github.com:zq2599/blog_demos.git 该项目源码的仓库地址,ssh协议
  • 这个git项目中有多个工程,本次实战的工程是springcloudscaledemo,如下图红框所示:

这里写图片描述

如何将spring boot工程构建成docker镜像

  • 如果您想了解如何将spring boot工程构建docker镜像,欢迎访问以下三篇实战文章:
  1. 《maven构建docker镜像三部曲之一:准备环境》
  2. 《maven构建docker镜像三部曲之二:编码和构建镜像》;
  3. 《maven构建docker镜像三部曲之三:推送到远程仓库(内网和阿里云)》;
  • 本次实战用到的知识点主要集中在上面的第二部;

开发环境

  • 本次实战开发环境的具体信息如下:
  1. 操作系统:Ubuntu16;
  2. Docker版本:17.03.2-ce;
  3. JDK:1.8.0_151;
  4. maven:3.3.3;
  • 接下来我们依次开发eureka、provider、consumer等三个应用;

eureka-server应用的pom.xml

  • 新建一个名为 eureka-server的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.bolingcavalry</groupId>
    <artifactId>eureka-server</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>eureka-server</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.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>
        <spring-cloud.version>Edgware.SR1</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka-server</artifactId>
        </dependency>

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

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

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

            <!--新增的docker maven插件-->
            <plugin>
                <groupId>com.spotify</groupId>
                <artifactId>docker-maven-plugin</artifactId>
                <version>0.4.12</version>
                <!--docker镜像相关的配置信息-->
                <configuration>
                    <!--镜像名,这里用工程名-->
                    <imageName>bolingcavalry/${project.artifactId}</imageName>
                    <!--TAG,这里用工程版本号-->
                    <imageTags>
                        <imageTag>${project.version}</imageTag>
                    </imageTags>
                    <!--镜像的FROM,使用java官方镜像-->
                    <baseImage>java:8u111-jdk</baseImage>
                    <!--该镜像的容器启动后,直接运行spring boot工程-->
                    <entryPoint>["java", "-jar", "/${project.build.finalName}.jar"]</entryPoint>
                    <!--构建镜像的配置信息-->
                    <resources>
                        <resource>
                            <targetPath>/</targetPath>
                            <directory>${project.build.directory}</directory>
                            <include>${project.build.finalName}.jar</include>
                        </resource>
                    </resources>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
  • pom.xml中的几个关键点如下:
  1. spring cloud的版本是Edgware.SR1;
  2. 添加spring-cloud-starter-eureka-server的依赖;
  3. 添加spring-cloud-dependencies的依赖(pom的形式);
  4. 添加插件docker-maven-plugin,用于将当前工程制作成本地docker镜像;

eureka-server应用的源码

  • eureka-server应用只有一个java文件,内容如下:
package com.bolingcavalry.eurekaserver;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {

    public static void main(String[] args) {
        SpringApplication.run(EurekaServerApplication.class, args);
    }
}
  • 注意要添加@EnableEurekaServer注解;

eureka-server的配置信息

  • 配置信息application.properties的内容如下:
server.port=8080

eureka.instance.hostname=localhost
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
eureka.client.serviceUrl.defaultZone=http://${eureka.instance.hostname}:${server.port}/eureka/

构建eureka-server应用的docker镜像

  • 在pom.xml文件所在目录下,执行如下命令可以构建docker镜像:
mvn clean package -U -DskipTests docker:build
  • 构建成功后,执行命令docker images可见新构建的镜像,如下:
ubuntu@VM-129-56-ubuntu:~$ sudo docker images
REPOSITORY                       TAG                 IMAGE ID            CREATED             SIZE
bolingcavalry/eureka-server      0.0.1-SNAPSHOT      80663220a5f5        35 hours ago        683 MB
bolingcavalry/eureka-server      latest              80663220a5f5        35 hours ago        683 MB
  • eureka-server的镜像OK后,我们接下来构建provide的镜像;

provider应用的pom.xml

  • 新建一个名为service-provider的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.bolingcavalry</groupId>
    <artifactId>service-provider</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>service-provider</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.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>
        <spring-cloud.version>Edgware.SR1</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka-server</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>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

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

            <!--新增的docker maven插件-->
            <plugin>
                <groupId>com.spotify</groupId>
                <artifactId>docker-maven-plugin</artifactId>
                <version>0.4.12</version>
                <!--docker镜像相关的配置信息-->
                <configuration>
                    <!--镜像名,这里用工程名-->
                    <imageName>bolingcavalry/${project.artifactId}</imageName>
                    <!--TAG,这里用工程版本号-->
                    <imageTags>
                        <imageTag>${project.version}</imageTag>
                    </imageTags>
                    <!--镜像的FROM,使用java官方镜像-->
                    <baseImage>java:8u111-jdk</baseImage>
                    <!--该镜像的容器启动后,直接运行spring boot工程-->
                    <entryPoint>["java", "-jar", "/${project.build.finalName}.jar"]</entryPoint>
                    <!--构建镜像的配置信息-->
                    <resources>
                        <resource>
                            <targetPath>/</targetPath>
                            <directory>${project.build.directory}</directory>
                            <include>${project.build.finalName}.jar</include>
                        </resource>
                    </resources>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

provider应用的源码

  • 入口类ServiceProviderApplication的源码如下:
package com.bolingcavalry.serviceprovider;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@EnableDiscoveryClient
@SpringBootApplication
public class ServiceProviderApplication {
    public static void main(String[] args) {
        SpringApplication.run(ServiceProviderApplication.class, args);
    }
}
  • 注意要添加@EnableDiscoveryClient注解;
  • 只有一个controller类UserController ,对外提供http服务:
@RestController
public class UserController {
    @RequestMapping(value = "/getuserinfo/{id}", method = RequestMethod.GET)
    public String getUserInfo(@PathVariable String id){
        return String.format("user[%s]", id);
    }

    @RequestMapping(value = "/getuserinfo", method = RequestMethod.GET)
    public String getUserInfoWithRequestParam(@RequestParam("id") String id, @RequestParam("name") String name){
        return String.format("user [%s], id [%s], from server [%s]", name, id, getIPAddr());
    }

    /**
     * 获取本机IP地址
     * @return
     */
    private static String getIPAddr(){
        String hostAddress = null;
        try{
            InetAddress address = InetAddress.getLocalHost();
            hostAddress = address.getHostAddress();
        }catch (UnknownHostException e){
            e.printStackTrace();
        }

        return hostAddress;
    }
}
  • 上面的controller提供两个http服务,getUserInfoWithRequestParam服务会返回应用所在机器的IP地址;

provider的配置信息

  • provider的配置信息存放在application.yml文件中,内容如下:
server:
  port: 8080
spring:
  application:
    name: microservice-provider-user
eureka:
  client:
    serviceUrl:
      defaultZone: http://eurekahost:8080/eureka/
  instance:
    prefer-ip-address: true
  • 注意上面配置的注册中心地址为http://eurekahost:8080/eureka/,eurekahost在docker-compose中会作为link参数对应eureka server;

构建provider应用的docker镜像

  • 在pom.xml文件所在目录下,执行如下命令可以构建docker镜像:
mvn clean package -U -DskipTests docker:build
  • 构建成功后,执行命令docker images可见新构建的镜像,如下:
ubuntu@VM-129-56-ubuntu:~$ sudo docker images
REPOSITORY                       TAG                 IMAGE ID            CREATED             SIZE
bolingcavalry/eureka-server      0.0.1-SNAPSHOT      80663220a5f5        35 hours ago        683 MB
bolingcavalry/eureka-server      latest              80663220a5f5        35 hours ago        683 MB
bolingcavalry/service-provider   0.0.1-SNAPSHOT      a02f307bc1a9        22 hours ago        683 MB
bolingcavalry/service-provider   latest              a02f307bc1a9        22 hours ago        683 MB
  • provider已经OK,接下来是consumer工程;

consumer应用的pom.xml

  • 新建一个名为service-consumer的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.bolingcavalry</groupId>
    <artifactId>service-consumer</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>service-consumer</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.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>
        <spring-cloud.version>Edgware.SR1</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka-server</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-feign</artifactId>
        </dependency>

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

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

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

            <!--新增的docker maven插件-->
            <plugin>
                <groupId>com.spotify</groupId>
                <artifactId>docker-maven-plugin</artifactId>
                <version>0.4.12</version>
                <!--docker镜像相关的配置信息-->
                <configuration>
                    <!--镜像名,这里用工程名-->
                    <imageName>bolingcavalry/${project.artifactId}</imageName>
                    <!--TAG,这里用工程版本号-->
                    <imageTags>
                        <imageTag>${project.version}</imageTag>
                    </imageTags>
                    <!--镜像的FROM,使用java官方镜像-->
                    <baseImage>java:8u111-jdk</baseImage>
                    <!--该镜像的容器启动后,直接运行spring boot工程-->
                    <entryPoint>["java", "-jar", "/${project.build.finalName}.jar"]</entryPoint>
                    <!--构建镜像的配置信息-->
                    <resources>
                        <resource>
                            <targetPath>/</targetPath>
                            <directory>${project.build.directory}</directory>
                            <include>${project.build.finalName}.jar</include>
                        </resource>
                    </resources>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
  • 和前面两个应用相比,这里要引入spring-cloud-starter-feign

consumer的源码

  • 入口类ServiceConsumerApplication 源码如下:
package com.bolingcavalry.serviceconsumer;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;

@EnableDiscoveryClient
@SpringBootApplication
@EnableFeignClients
public class ServiceConsumerApplication {

    public static void main(String[] args) {
        SpringApplication.run(ServiceConsumerApplication.class, args);
    }
}
  • 注意要增加@EnableDiscoveryClient@SpringBootApplication这两个注解;
  • 增加一个带注解@FeignClient的接口,用于在spring cloud环境中声明远程调用信息:
@FeignClient(name = "microservice-provider-user")
public interface UserFeignClient {

    @RequestMapping(value = "/getuserinfo", method = RequestMethod.GET)
    String getUserInfoWithRequestParam(@RequestParam("id") String id, @RequestParam("name") String name);
}
  • 增加一个controller类UserFacadeController,为浏览器访问提供http服务,并且在响应请求的时候会通过UserFeignClient接口的实现远程调用provider应用的服务:
@RestController
public class UserFacadeController {

    @Autowired
    private UserFeignClient userFeignClient;

    @GetMapping("/user/{id}/{name}")
    public String getUserInfo(@PathVariable("id") final String id, @PathVariable("name") final String name) {
        return "1. ---" + userFeignClient.getUserInfoWithRequestParam(id, name);
    }
}

consumer的配置信息

  • provider的配置信息存放在application.yml文件中,内容如下:
server:
  port: 8080
spring:
  application:
    name: service-consumer
eureka:
  client:
    serviceUrl:
      defaultZone: http://eurekahost:8080/eureka/
  instance:
    prefer-ip-address: true
  • 注意上面配置的注册中心地址为http://eurekahost:8080/eureka/,eurekahost在docker-compose中会作为link参数对应eureka server;

构建provider应用的docker镜像

  • 在pom.xml文件所在目录下,执行如下命令可以构建docker镜像:
mvn clean package -U -DskipTests docker:build
  • 构建成功后,执行命令docker images可见新构建的镜像,如下:
ubuntu@VM-129-56-ubuntu:~$docker images
REPOSITORY                       TAG                 IMAGE ID            CREATED             SIZE
bolingcavalry/service-provider   0.0.1-SNAPSHOT      a02f307bc1a9        47 hours ago        683 MB
bolingcavalry/service-provider   latest              a02f307bc1a9        47 hours ago        683 MB
bolingcavalry/service-consumer   0.0.1-SNAPSHOT      ae6b37b99754        2 days ago          683 MB
bolingcavalry/service-consumer   latest              ae6b37b99754        2 days ago          683 MB
bolingcavalry/eureka-server      0.0.1-SNAPSHOT      80663220a5f5        2 days ago          683 MB
bolingcavalry/eureka-server      latest              80663220a5f5        2 days ago          683 MB
  • 至此,本次实战所需的所有镜像都制作完毕,相关的demo工程的开发过程我们也一起过了一遍,上一章中的实战您已经可以独立做出来了,接下来的实战中,我们一起来尝试服务横向扩容;

欢迎关注阿里云开发者社区博客:程序员欣宸

学习路上,你不孤单,欣宸原创一路相伴...
相关文章
|
3天前
|
XML JSON Java
Spring Boot 开发中常见的错误
本文总结了 Java 开发中常见的几个问题及其改进方法,包括:1. 过度使用 `@Component` 注解;2. `@ResponseBody` 注解的错误用法;3. `@Autowired` 的不当使用;4. `application.properties` 管理不善;5. 异常处理不当。每部分详细解释了错误情况和建议的改进方案,并提供了相应的代码示例。
31 11
|
3天前
|
IDE Java 测试技术
互联网应用主流框架整合之Spring Boot开发
通过本文的介绍,我们详细探讨了Spring Boot开发的核心概念和实践方法,包括项目结构、数据访问层、服务层、控制层、配置管理、单元测试以及部署与运行。Spring Boot通过简化配置和强大的生态系统,使得互联网应用的开发更加高效和可靠。希望本文能够帮助开发者快速掌握Spring Boot,并在实际项目中灵活应用。
23 5
|
1天前
|
前端开发 Java 开发者
这款免费 IDEA 插件让你开发 Spring 程序更简单
Feign-Helper 是一款支持 Spring 框架的 IDEA 免费插件,提供 URL 快速搜索、Spring Web Controller 路径一键复制及 Feign 与 Controller 接口互相导航等功能,极大提升了开发效率。
|
19天前
|
消息中间件 监控 Java
如何将Spring Boot + RabbitMQ应用程序部署到Pivotal Cloud Foundry (PCF)
如何将Spring Boot + RabbitMQ应用程序部署到Pivotal Cloud Foundry (PCF)
31 6
|
19天前
|
负载均衡 Java 开发者
深入探索Spring Cloud与Spring Boot:构建微服务架构的实践经验
深入探索Spring Cloud与Spring Boot:构建微服务架构的实践经验
62 5
|
19天前
|
Java 关系型数据库 MySQL
如何将Spring Boot + MySQL应用程序部署到Pivotal Cloud Foundry (PCF)
如何将Spring Boot + MySQL应用程序部署到Pivotal Cloud Foundry (PCF)
38 5
|
19天前
|
缓存 监控 Java
如何将Spring Boot应用程序部署到Pivotal Cloud Foundry (PCF)
如何将Spring Boot应用程序部署到Pivotal Cloud Foundry (PCF)
31 5
|
18天前
|
Java 应用服务中间件 Docker
将基于 Spring 的 WAR 应用程序部署到 Docker:详尽指南
将基于 Spring 的 WAR 应用程序部署到 Docker:详尽指南
22 2
|
21天前
|
前端开发 JavaScript Java
如何使用 Spring Boot 和 Angular 开发全栈应用程序:全面指南
如何使用 Spring Boot 和 Angular 开发全栈应用程序:全面指南
31 1
|
24天前
|
Java Linux Docker
什么是 Docker?如何将 Spring Boot 应用程序部署到 Docker?
什么是 Docker?如何将 Spring Boot 应用程序部署到 Docker?
41 3
下一篇
DataWorks