天天看点

Springboot 整合 SpringCloud组件-Eureka 微服务 EurekaClient(二)

我们已经完成了Eureka 注册中心 Server的搭建与部署,那么这篇,我们就来创建一个微服务 EurekaClient,将其成功注册到我们的注册中心去。

同样,创建一个springboot项目,起名client1作为一个微服务:

Springboot 整合 SpringCloud组件-Eureka 微服务 EurekaClient(二)

(同样,我们这里选用的springcloud版本是:Finchley.RELEASE) 

pom.xml中相关的组件依赖是(web包是为了写接口使用):

<dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>      

 然后是application.yml配置文件:

server:
  port: 8762

spring:
  application:
    name: client-test
eureka:
  instance:
#以IP地址注册到服务中心,相互注册使用IP地址
    preferIpAddress: true
    instance-id: ${spring.cloud.client.ip-address}:${server.port}
  client:
#eureka server注册中心的地址
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/      

 (配置文件中那一段以IP地址注册的相关配置项,大家可以试试去掉,到时在注册中心就可以看到不显示具体IP地址)

 (spring: application : name 特别重要,这个name,在后面服务之间调用就是用的它)

然后在启动类上开启 EurekaClient注册注解 @EnableEurekaClient:

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

@SpringBootApplication
@EnableEurekaClient
public class Client1Application {

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

}      

 接着我们写一个接口来调用测试下,TestController.java:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


/**
 * @Author:JCccc
 * @Description:
 * @Date: created in 14:19 2018/3/5
 */
@RestController
public class TestController {

    @Value("${server.port}")
    String port;
    @RequestMapping("/haveatry")
    public String home(@RequestParam(value = "name", defaultValue = "forezp") String name) throws InterruptedException {

        return "微服务 client-test被调用, " + "name为:"+name + " ,被调用的服务端口 port:" + port;
    }


}      

 OK,项目跑起来,我们先访问下Eureka Server注册中心 ​​http://localhost:8761/​​  :

Springboot 整合 SpringCloud组件-Eureka 微服务 EurekaClient(二)

可以看到,我们的client-test 服务已经成功注册到了注册中心。

我们用Postman访问下接口:

Springboot 整合 SpringCloud组件-Eureka 微服务 EurekaClient(二)

继续阅读