Client向Eureka注册服务

2019-01-14  本文已影响0人  2B键盘

这个模块的parent也是父项目,eureka和client都基于cloud父项目。

首先在原有的项目上创建一个model,命名为client-hello。

记得先看下parent是否是你的父项目,如果不是请改为你的父项目

然后引入依赖。。。

引入依赖

spring-cloud-netflix-eureka-client依赖和springboot的web依赖

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- springcloud的客户端组件依赖 -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-netflix-eureka-client</artifactId>
    </dependency>
</dependencies>

配置application.yml文件


server:
  port: 8762

spring:
  application:
    #这边的name表示注册到eureka注册中心的名称
    name: client-hello

eureka:
  client:
    instance:
      hostname: localhost
    #这边的url是eureka-server配置文件中的url,表示这个客户端是向它去进行注册
    service-url:
      defaultZone: http://localhost:8761/eureka/

启动项目


package com.keyboard.client;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 2B键盘
 * @version 1.0.0
 * @date 2019/1/4 18:43
 * @descripting TODO
 */
@SpringBootApplication
//这个注解表明这是个eureka-client服务
@EnableEurekaClient
@RestController
public class ClientHelloApplication {

    //获取配置文件中配置的端口号
    @Value("${server.port}")
    String port;

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

    @RequestMapping("/hello")
    public String hello(@RequestParam(value = "name",defaultValue = "keyboard")String name){
        return "我是eureka客户端,我叫:"+name+"!我来自"+port+"端口";
    }

}

启动完项目后刷新eureka-server页面,查看Instances currently registered with Eureka标题下是否存在client-hello,如果存在说明已经注册成功了,这个服务已经在eureka中了

上一篇 下一篇

猜你喜欢

热点阅读