SpringCloud 入门系列【2】使用Eureka 进行服务治理

服务治理可以说是微服务架构中最为核心和基础的模块,它主要用来实现各个微服务实例的自动化注册和发现。

Spring Cloud Eureka是Spring Cloud Netflix 微服务套件的一部分,主要负责完成微服务架构中的服务治理功能。

本文通过简单的小例子来分享下如何通过Eureka进行服务治理:

  • 搭建服务注册中心
  • 注册服务提供者
  • 服务发现和消费

一、搭建服务注册中心

先列出完整目录结构:

  SpringCloud 入门系列【2】使用Eureka 进行服务治理

搭建过程如下:

1、创建maven工程:eureka(具体实现略)

2、修改pom文件,引入依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<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.sam</groupId>
    <artifactId>eureka</artifactId>
    <version>0.0.1-SNAPSHOT</version>
 
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.1.RELEASE</version>
    </parent>
 
    <properties>
        <javaVersion>1.8</javaVersion>
    </properties>
    <!-- 使用dependencyManagement进行版本管理 -->
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Camden.SR6</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
 
    </dependencyManagement>
 
    <dependencies>
        <!-- 引入eureka server依赖 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka-server</artifactId>
        </dependency>
 
    </dependencies>
 
</project>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.1.RELEASE</version>
</parent>

<properties>
<javaVersion>1.8</javaVersion>
</properties>
<!-- 使用dependencyManagement进行版本管理 -->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Camden.SR6</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>

</dependencyManagement>

<dependencies>
<!-- 引入eureka server依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka-server</artifactId>
</dependency>

</dependencies>

</project>

3、创建启动类

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
 * 
 * @EnableEurekaServer
 * 用来指定该项目为Eureka的服务注册中心
 */
@EnableEurekaServer
@SpringBootApplication
public class EurekaApp {
 
    public static void main(String[] args) {
        SpringApplication.run(EurekaApp.class, args);
    }
}

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

4、配置application.properties文件

1
2
3
4
5
6
7
8
9
10
11
12
#设置tomcat服务端口号
server.port=1111
#设置服务名称
spring.application.name=eureka-service
 
eureka.instance.hostname=localhost
#注册中心不需要注册自己
eureka.client.register-with-eureka=false
#注册中心不需要去发现服务
eureka.client.fetch-registry=false
#设置服务注册中心的URL
eureka.client.serviceUrl.defaultZone=http://${eureka.instance.hostname}:${server.port}/eureka

eureka.instance.hostname=localhost
#注册中心不需要注册自己
eureka.client.register-with-eureka=false
#注册中心不需要去发现服务
eureka.client.fetch-registry=false
#设置服务注册中心的URL
eureka.client.serviceUrl.defaultZone=http://${eureka.instance.hostname}:${server.port}/eureka

5、启动服务并访问,我们会看到这样的画面:

SpringCloud 入门系列【2】使用Eureka 进行服务治理

二、注册服务提供者

先列出完整目录结构:

SpringCloud 入门系列【2】使用Eureka 进行服务治理

搭建过程如下:

1、创建maven工程:hello-service(具体实现略)

2、修改pom文件,引入依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<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.sam</groupId>
    <artifactId>hello-service</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.1.RELEASE</version>
    </parent>
 
    <properties>
        <javaVersion>1.8</javaVersion>
    </properties>
 
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Camden.SR6</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
 
    </dependencyManagement>
 
    <dependencies>
        <!-- 引入eureka 客户端依赖 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
 
    </dependencies>
</project>

<properties>
<javaVersion>1.8</javaVersion>
</properties>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Camden.SR6</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>

</dependencyManagement>

<dependencies>
<!-- 引入eureka 客户端依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>

</dependencies>
</project>

3、创建启动类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/***
 * 
 * @EnableDiscoveryClient
 * 让服务使用eureka服务器
 * 实现服务注册和发现
 *
 */
@EnableDiscoveryClient
@SpringBootApplication
public class HelloApp {
 
    public static void main(String[] args) {
 
        SpringApplication.run(HelloApp.class, args);
    }
 
}

public static void main(String[] args) {

SpringApplication.run(HelloApp.class, args);
}

}

4、创建controller

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@RestController
public class HelloController {
 
    Logger logger = LoggerFactory.getLogger(HelloController.class);
 
    @Autowired
    DiscoveryClient discoveryClient;
 
    @RequestMapping("/hello")
    public String hello() {
        ServiceInstance instance = discoveryClient.getLocalServiceInstance();
        //打印服务的服务id
        logger.info("*********" + instance.getServiceId());
        return "hello,this is hello-service";
    }
}

Logger logger = LoggerFactory.getLogger(HelloController.class);

@Autowired
DiscoveryClient discoveryClient;

@RequestMapping("/hello")
public String hello() {
ServiceInstance instance = discoveryClient.getLocalServiceInstance();
//打印服务的服务id
logger.info("*********" + instance.getServiceId());
return "hello,this is hello-service";
}
}

5、配置application.properties文件

1
2
3
4
5
server.port=9090
#设置服务名
spring.application.name=hello-service
#设置服务注册中心的URL,本服务要向该服务注册中心注册自己
eureka.client.serviceUrl.defaultZone=http://localhost:1111/eureka

6、启动并测试

启动后再hello-service的控制台会有这种字样(xxx代表你的PC名)

1
Registered instance HELLO-SERVICE/xxx:hello-service:9090 with status UP (replication=false)

eureka的控制台会打印出如下字样(xxx代表你的PC名)

1
Registered instance HELLO-SERVICE/xxx:hello-service:9090 with status UP (replication=false)

再次访问localhost:1111,会发现有服务注册到注册中心了SpringCloud 入门系列【2】使用Eureka 进行服务治理

三、服务发现和消费

完整目录结构如下:

SpringCloud 入门系列【2】使用Eureka 进行服务治理

搭建过程:

1、创建maven工程(具体实现略)

2、修改pom文件,引入依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<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.sam</groupId>
    <artifactId>hello-consumer</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.1.RELEASE</version>
    </parent>
 
    <properties>
        <javaVersion>1.8</javaVersion>
    </properties>
 
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Camden.SR6</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
 
    </dependencyManagement>
 
    <dependencies>
        <!-- 引入eureka 客户端依赖 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
        <!-- 引入ribbon 依赖 ,用来实现负载均衡,我们这里只是使用,先不作其他介绍-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-ribbon</artifactId>
        </dependency>
 
    </dependencies>
</project>
 
这里比hello-service服务提供者,多了ribbon的依赖

<properties>
<javaVersion>1.8</javaVersion>
</properties>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Camden.SR6</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>

</dependencyManagement>

<dependencies>
<!-- 引入eureka 客户端依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<!-- 引入ribbon 依赖 ,用来实现负载均衡,我们这里只是使用,先不作其他介绍-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
</dependency>

</dependencies>
</project>

这里比hello-service服务提供者,多了ribbon的依赖

3、创建启动类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@EnableDiscoveryClient
@SpringBootApplication
public class ConsumerApp {
 
 
    //@Bean 应用在方法上,用来将方法返回值设为为bean
    @Bean
    @LoadBalanced  //@LoadBalanced实现负载均衡
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
 
    public static void main(String[] args) {
        SpringApplication.run(ConsumerApp.class, args);
    }
}
 
 
这里也要用到@EnableDiscoveryClient, 让服务使用eureka服务器, 实现服务注册和发现

//@Bean 应用在方法上,用来将方法返回值设为为bean
@Bean
@LoadBalanced //@LoadBalanced实现负载均衡
public RestTemplate restTemplate() {
return new RestTemplate();
}

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

这里也要用到@EnableDiscoveryClient, 让服务使用eureka服务器, 实现服务注册和发现

4、创建controller

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@RestController
public class ConsumerController {
 
    //这里注入的restTemplate就是在com.sam.ConsumerApp中通过@Bean配置的实例
    @Autowired
    RestTemplate restTemplate;
 
    @RequestMapping("/hello-consumer")
    public String helloConsumer() {
        //调用hello-service服务,注意这里用的是服务名,而不是具体的ip+port
        restTemplate.getForObject("http://hello-service/hello", String.class);
        return "hello consumer finish !!!";
    }
}

//这里注入的restTemplate就是在com.sam.ConsumerApp中通过@Bean配置的实例
@Autowired
RestTemplate restTemplate;

@RequestMapping("/hello-consumer")
public String helloConsumer() {
//调用hello-service服务,注意这里用的是服务名,而不是具体的ip+port
restTemplate.getForObject("http://hello-service/hello", String.class);
return "hello consumer finish !!!";
}
}

5、配置application.properties文件

1
2
3
4
5
6
7
server.port=9999
 
spring.application.name=hello-consumer
eureka.client.serviceUrl.defaultZone=http://localhost:1111/eureka
 
 
#这里的配置项目和服务提供者hello-service一样

spring.application.name=hello-consumer
eureka.client.serviceUrl.defaultZone=http://localhost:1111/eureka

#这里的配置项目和服务提供者hello-service一样

6、启动,测试

  1. )启动eureka。为了展示负责均衡的效果,我们的hello-service启动两个服务,启动两个服务的具体步骤如下
    1. SpringCloud 入门系列【2】使用Eureka 进行服务治理SpringCloud 入门系列【2】使用Eureka 进行服务治理SpringCloud 入门系列【2】使用Eureka 进行服务治理

      SpringCloud 入门系列【2】使用Eureka 进行服务治理

      以上是hello-service1的启动步骤,端口号为9090;同样方法设置hello-service2,端口号为9091(具体实现略)。

  2. )启动hello-consumer
  3. )再次访问http://localhost:1111/,会发现有2个hello-service服务(端口号一个是9090,一个是9091),1个hello-consume服务
  4. )   多次访问http://localhost:9999/hello-consumer,会发现hello-service1和hello-service2会轮流被调用(已经实现了负责均衡),可以通过两者的控制台打印内容确认(还记得我们在hello-service的controller中有个loggerlogger.info("*********" + instance.getServiceId());吗?对,就是这个打印)SpringCloud 入门系列【2】使用Eureka 进行服务治理SpringCloud 入门系列【2】使用Eureka 进行服务治理SpringCloud 入门系列【2】使用Eureka 进行服务治理

    SpringCloud 入门系列【2】使用Eureka 进行服务治理

四、总结

以上实例实现了基本的服务治理:

  • 通过spring-cloud-starter-eureka-server和@EnableEurekaServer实现服务注册中心
  • 通过spring-cloud-starter-eureka和@EnableDiscoveryClient使用并注册到服务注册中心
  • 通过spring-cloud-starter-eureka和@EnableDiscoveryClient使用注册中心并发现服务,通过spring-cloud-starter-ribbon来实现负载均衡消费服务

PS:这里说明下,我用的IDE是Spring Tool Suite,是spring定制版的eclipse,方便我们使用spring进行开发,有兴趣的朋友可以自行百度了解下。

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

关注我们