Spring Cloud微服务(二):服务提供与调用(Greenwich SR3)

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 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值