文章目录
1.介绍
一个简单的微服务调用,可以使用三个微服务实现,
- 服务注册中心(Eureka Server)
- 服务提供方(服务生产者):使用Eureka Client向服务注册中心注册自身的REST服务。
- 服务调用方(服务消费者):从注册中心获取注册信息,调用REST服务。
本文提供了如下SpringBoot项目:
————服务提供方:
hello-service:通过Eureka Client将服务注册到服务注册中心。
————服务调用方:
服务调用方式一:hello-service-loadbalancerconsumer:用LoadBalancerClient进行客户端负载均衡,用RestTemplate实现服务的调用。
服务调用方式二:hello-service-ribbonconsumer:用ribbon进行客户端负载均衡,并用RestTemplate实现服务的调用。
服务调用方式三:hello-service-feignconsumer:用feign实现服务的调用。
环境配置:
SpringBoot 2.1.8.RELEASE
SpringCloud Greenwich.SR3
【注】其中服务注册中心通过Eureka Server实现(可参考Spring Cloud微服务(一):服务注册与发现(Greenwich SR3))。在启动hello-service(服务提供方)项目之前,先启动Eureka服务注册中心。
2.服务提供方
【步骤一】:创建一个SpringBoot项目,项目名为hello-service,在pom.xml
文件中添加Eureka client的依赖。
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.8.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Greenwich.SR3</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<properties>
<java.version>1.8</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
【步骤二】:在SpringBoot项目配置文件application.properties
中添加配置。配置内容如下:
server.port=8888
spring.application.name=hello-service
eureka.client.serviceUrl.defaultZone=http://peer1:8001/eureka/
其中spring.application.name
用于指定微服务的名称,服务调用方对服务发起调用时需要此名称。eureka.client.serviceUrl.defaultZone
配置的是eureka服务注册中心的位置。
【步骤三】:SpringBoot的启动类Application和REST服务接口。
Greenwich SR3版本的Spring Cloud中可以不添加@EnableDiscoveryClient注解,只需添加enreka client的maven依赖。
@SpringBootApplication
//@EnableDiscoveryClient 可不加
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@RestController
public class HelloController