废话不多讲,跟紧我,开启你的SpringCloud初体验

首先回顾微服务的基本组成:

[图片 here]

生产者:提供服务

消费者:消费服务

服务注册/发现中心:服务注册,发现,监控

所以,首先明白springcloud微服务的架构基础 :生产者(client),消费者(client),服务注册/发现中心(server)

*************************************************************************************************************************

预先说明!!springboot与SpringCloud及SpringCloud的相关组件有版本兼容问题,以下代码中选择的版本都是经过实际测试,请勿随意修改版本,否则会出现未知问题!

**************************************************************************************************************************

先看demo结构:基础组件学习共需要创建7个小spring-boot项目,本章节先创建其中4个基础项目,其余组件的学习后续加入进来即可, JDK统一选择1.8

首先创建父工程 j-cloud

创建简单的名为j-cloud的springboot工程,打包方式为pom,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>cn.jorian.framework</groupId>
  <artifactId>j-cloud</artifactId>
  <version>1.0.0</version>
  <packaging>pom</packaging>

  <name>j-cloud</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <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>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <!-- Swagger API文档 -->
    <dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-swagger2</artifactId>
      <version>2.9.2</version>
    </dependency>
    <dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-swagger-ui</artifactId>
      <version>2.9.2</version>
    </dependency>
    <dependency>
      <groupId>com.github.xiaoymin</groupId>
      <artifactId>swagger-bootstrap-ui</artifactId>
      <version>1.9.3</version>
    </dependency>
    <dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-bean-validators</artifactId>
      <version>2.9.2</version>
    </dependency>
  </dependencies>
  <modules>
   
  </modules>


</project>

一,创建服务注册发现中心工程:j-cloud-server-eureka

1.在父工程j-cloud右击创建一个module: j-cloud-server-eureka

2.填写相关信息

3.新创建的模块结构如下:

4.模块j-cloud-server-eureka的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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>cn.jorian.framework</groupId>
    <artifactId>j-cloud-server-eureka</artifactId>
    <version>1.0.0</version>
    <name>j-cloud-server-eureka</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Hoxton.SR1</spring-cloud.version>
    </properties>

    <dependencies>
        <!--eureka-server-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
        <!--LOMBOK-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.20</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </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>
        </plugins>
    </build>

</project>

5.模块j-cloud-server-eureka的application.yml如下

spring:
  security:
    basic:
      enabled: true
    user:
      name: jorian
      password: 123456
server:
  port: 8761

eureka:
  client:
    register-with-eureka: false
    fetch-registry: false
    service-url:
      defaultZone: http://jorian:123456@localhost:8761/eureka

注意 :yml格式的文件有特殊要求,必须树形结构,不能有tab,具体请百度 

6.模块j-cloud-server-eureka的启动类需加上注解@EnableEurekaServer, 来声明其是一个基于Eureka的服务注册发现中心

package cn.jorian.framework.jcloudservereureka;

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

@SpringBootApplication
@EnableEurekaServer //标明是一个server
public class JCloudServerEurekaApplication {

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

        System.out.println("---服务监控访问地址"+"http://localhost:8761");
    }

}

7.启动j-cloud-server-eureka服务:

执行main方法启动springboot工程

8.在浏览器访问:http://localhost:8761,查看eureka服务注册发现中心是否启动

启动成功界面如下:

二,创建生产者模块:j-cloud-provider1

1.同上,在父工程j-cloud右击创建一个module: j-cloud-provider1

2.填写相关信息,打包方式为jar

3.整个工程结构如下:

4.生产者模块j-cloud-provider1的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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>cn.jorian.framework</groupId>
    <artifactId>j-cloud-provider1</artifactId>
    <version>1.0.0</version>
    <name>j-cloud-provider1</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Hoxton.SR1</spring-cloud.version>
    </properties>

    <dependencies>
        <!--eureka-client 依赖-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <!--LOMBOK-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.20</version>
            <scope>provided</scope>
        </dependency>
        <!--单元测试依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.2.4.RELEASE</version>
            <scope>compile</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>
        </plugins>
    </build>

</project>

5.生产者模块j-cloud-provider1的application.yml如下, 此处注意配置文件中声明了服务注册中心的地址

# 应用端口
server:
  port: 7901
spring:
  application:
    # 应用名称
    name: provider-user

# eureka 配置
eureka:
  client:
    serviceUrl:
      defaultZone: http://jorian:123456@localhost:8761/eureka

logging:
  level:
    root: INFO

6.生产者模块j-cloud-provider1的启动类如下,添加注解:@EnableEurekaClient来声明其是一个client(生产者或者消费者,在这里他是生产者)

package cn.jorian.framework;

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

/**
 * @author jorian
 */
@SpringBootApplication
@EnableEurekaClient //表明这是一个eureka客户端
public class JCloudProvider1Application {

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

}

7.创建UserController.java,用来提供测试用的API

UserController.java代码

package cn.jorian.framework.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {
	@RequestMapping("/sayHello")
	public String sayhello(){
		return "I`m provider 1 ,Hello consumer!";
	}
	@RequestMapping("/sayHi")
	public String sayHi(){
		return "I`m provider 1 ,Hello consumer!";
	}
	@RequestMapping("/sayHaha")
	public String sayHaha(){
		return "I`m provider 1 ,Hello consumer!";
	}
}

8.执行main方法,启动生产者模块: j-cloud-provider1

9.在浏览器访问或者刷新:http://localhost:8761,在eureka服务注册发现中心查看生产者服务是否已被发现注册

注册成功如下:可以看到应用名称,访问地址,也可以自行测试接口的返回结果

三,创建消费者:j-cloud-sonsumer

1.同上,在父工程j-cloud右击创建一个module:j-cloud-sonsumer

2.填写相关信息,打包方式为jar

3.整个消费者模块:j-cloud-sonsumer工程结构如下:

4.消费者模块:j-cloud-sonsumer的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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>cn.jorian.framework</groupId>
    <artifactId>j-cloud-consumer</artifactId>
    <version>1.0.0</version>
    <name>j-cloud-consumer</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Hoxton.SR1</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <!--LOMBOK-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.20</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.2.4.RELEASE</version>
            <scope>compile</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>
        </plugins>
    </build>

</project>

5. 消费者模块:j-cloud-sonsumer的application.yml如下

server:
  port: 8001
spring:
  application:
    name: j-cloud-consumer

# eureka 配置
eureka:
  client:
    serviceUrl:
      defaultZone: http://jorian:123456@localhost:8761/eureka
logging:
  level:
    root: INFO

6.消费者模块:j-cloud-sonsumer的启动类如下,添加注解:@EnableEurekaClient来声明其是一个client(生产者或者消费者,在这里他是消费者)

package cn.jorian.framework;

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

@SpringBootApplication
@EnableEurekaClient
public class JCloudConsumerApplication {

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

}

7.创建HelloController对外提供访问API

HelloController代码如下:

package cn.jorian.framework.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 *
 * @author jorian
 *
 */
@RestController
public class HelloController {

	@Bean
	@LoadBalanced
	public RestTemplate getResttemplate(){
		return new RestTemplate();
	}
	@Autowired
	private RestTemplate resttemplate;

	@RequestMapping("/hello")
	public String hello(){
		//指出服务地址   http://{服务提供者应用名名称}/{具体的controller}
		String url="http://provider-user/user/sayHello";

		//返回值类型和我们的业务返回值一致
		return resttemplate.getForObject(url, String.class);

	}
	@RequestMapping("/hi")
	public String hi(){
		//指出服务地址   http://{服务提供者应用名名称}/{具体的controller}
		String url="http://provider-user/user/sayHi";

		//返回值类型和我们的业务返回值一致
		return resttemplate.getForObject(url, String.class);

	}
	@RequestMapping("/haha")
	public String haha(){
		//指出服务地址   http://{服务提供者应用名名称}/{具体的controller}
		String url="http://provider-user/user/sayHaha";
		//返回值类型和我们的业务返回值一致
		return resttemplate.getForObject(url, String.class);

	}
}

7.执行j-cloud-sonsumer的main方法,启动消费者工程

8.在浏览器访问或者刷新:http://localhost:8761,在eureka服务注册发现中心查看消费者服务是否已被发现注册

注册成功如下,可以看到应用名称,访问地址

四,测试

1.在地址栏直接访问消费者地址,http://localhost:8001/hello,成功调用到 j-cloud-provider1提供的接口并返回结果!

2.**升级难度**尝试开启多个provider实例,用来测试负载均衡****

可以采用修改yml文件 中的端口号重复启动实例也可以另外新建多个provider(我们采用这种方式),修改其中的yml文件中的端口号,然后启动。

由于eureka配置了ribbon负载均衡策略,消费者的请求会在客户端被决定好发送到哪台服务提供者进行处理。

创建与启动过程不再赘述,参考j-cloud-provider1创建启动过程

注意:

  1. 创建与j-cloud-provider1所有内容一致的j-cloud-provider2
  2. 只修改第二个生产者j-cloud-provider2 的 application.yml 中的端口号为7902即可
  3. 注意不要修改application.yml 中的应用名称, 两个生产者要用同样的名称,代表同一个应用的两个实列
  4.  然后启动工程

第二个生产者模块: j-cloud-provider2项目结构如下:

3.启动成功后在注册中心查看服务注册情况,2个provider都已经上线

4.地址栏重复访问消费者地址N次,http://localhost:8001/hello,会发现返回结果在两个provider切换,实现了负载均衡

第n次:

第n+1次:

至此,基础demo搭建完成

您可以继续查看下一章:springcloud教程 -- 2.feign的使用实践,优雅的发送请求

下载完整工程在这里:若对您有用,帮忙点个赞,谢谢icon-default.png?t=M3C8https://github.com/Jorian93/j-cloud.git

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐