细水长流——Eureka实现Demo

首先,我们来解释下什么是Eureka?

  Eureka:基于REST服务的分布式中间件,主要用于服务管理。服务直接的调用并不是通过Eureka,只是维护一些服务的列表。

 

  对比上面的图,我们举一个详细的例子来说明下,我们可以将Eureka服务器看作是我们现在的电商平台(比如京东),Eureka客户端的服务提供者看作是供应商(这里我们选择华为),Eureka客户端

的服务调用者就是我们的用户了。好,理解了上面的架构图,让我们一块来实现一个李白(服务调用者)在京东(Eureka服务器)购买华为(Eurake客户端的服务提供者)手机的小案例。

 

首先,我们创建3个简单的maven项目

 

 

 创建好之后,我们首先来搭建京东这个Eureka服务器,在pom.xml中加入Eureka的依赖,如下

<dependencyManagement>

<dependencies>

<dependency>

<groupId>org.springframework.cloud</groupId>

<artifactId>spring-cloud-dependencies</artifactId>

<version>Dalston.SR5</version>

<type>pom</type>

<scope>import</scope>

</dependency>

</dependencies>

</dependencyManagement>

 

<dependencies>

<dependency>

<groupId>org.springframework.cloud</groupId>

<artifactId>spring-cloud-starter-config</artifactId>

</dependency>

<dependency>

<groupId>org.springframework.cloud</groupId>

<artifactId>spring-cloud-starter-eureka-server</artifactId>

</dependency>

</dependencies>

 

再编写一个启动类

 

@SpringBootApplication

@EnableEurekaServer

public class StartUp {

public static void main(String[] args) {

new SpringApplicationBuilder(StartUp.class).web(true).run(args);

}

}

 

这时候,我们启动发现报错,这是因为,京东这个项目也注册到Eureka服务端,服务端默认端口8761,因此我们需要设置一些Eureka的配置

 

 

此时我们再启动项目,就会发现启动正常了,我们访问,localhost:8761查看Eureka 

 

好,到这一步,Eureka到服务器我们已经搭建好了,下面我们将华为注册到京东上去,操作eureka-huawei项目,同样,我们首先在pom.xml中加入依赖 

 

<dependencyManagement>

<dependencies>

<dependency>

<groupId>org.springframework.cloud</groupId>

<artifactId>spring-cloud-dependencies</artifactId>

<version>Dalston.SR5</version>

<type>pom</type>

<scope>import</scope>

</dependency>

</dependencies>

</dependencyManagement>

<dependencies>

<dependency>

<groupId>org.springframework.cloud</groupId>

<artifactId>spring-cloud-starter-config</artifactId>

</dependency>

<dependency>

<groupId>org.springframework.cloud</groupId>

<artifactId>spring-cloud-starter-eureka</artifactId>

</dependency>

</dependencies>

 

编写启动类

 

 

我们提供一个手机购买的方法

 

 

创建application.yml文件,将我们华为项目注册进入京东(Eureka服务器)

 

这时候我们再启动华为项目,再次访问localhost:8761,这时候我们就会发现华为这个Eureka服务提供商被我们注册进来了

 

测试我们的手机功能:localhost:8000/phone/1

 

 

最后,我们来操作我们的eureka-customer项目,同样先添加依赖,这里我们多引入了一个ribbon框架,因为现在大部分服务器都是负载均衡,我们使用多时候不需要知道具体是由哪个服务器提供,

启动类同huawei项目相同,这里不再重复

yml文件只是改下名称,同样注册到我们Eureka服务器

 

这里我们用restTemplate来调用服务,编写一个配置类,提供RestTemplate

 

最后,我们再编写controller,写一个购买手机服务,用来购买我们华为提供的商品

好,现在我们再启动customer项目,查看localhost:8761

 

 这时,我们的李白也注册了一个京东账户了,接下来,他就可以买产品了,我们调用http://localhost:9000/buyPhone/3,发现他成功的购买了华为的商品

到此一个简单的Eureka项目已经编写完毕

 

posted on 2018-04-13 18:32  指尖改变世界  阅读(154)  评论(0编辑  收藏  举报

导航