Spring Boot实现Eureka注册功能

南笙酒味 提交于 2020-03-10 15:11:35

一、新建两个子模块,我这边的命名Eureka和Client,在父级的pom.xml

<!-- 集成web方式的开发 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 服务与注册中心 -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-eureka-server</artifactId>
</dependency>

二、在Eureka中新建package、Application服务需要在包下才能正常加载启动,根目录下启动会报异常

package eureka;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@SpringBootApplication
@EnableEurekaServer --作为服务端注解
public class EurekaServer {

    public static void main(String[] args) {
        new SpringApplicationBuilder(EurekaServer.class).web(true).run(args);
    }
}

Eureka下的application.yml

server:
  port: 9001
eureka:
  instance:
    hostname: localhost
    prefer-ip-address: true
  client:
    register-with-eureka: false #不作为服务注册
    fetch-registry: false #单点服务不需要同步其他服务数据
    service-url:
      defaultZone: http://localhost:9001/eureka/ #服务注册地址

三、Client下新建package和Application

package redis;

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

@SpringBootApplication
@EnableEurekaClient --作为客户端注解
public class RedisServer {

    public static void main(String[] args) {
        new SpringApplicationBuilder(RedisServer.class).web(true).run(args);
    }
}

Client下application.yml

server:
  port: 9009
spring:
  application:
    name: springCloud-redis
eureka:
  instance:
    hostname: localhost
  client:
    register-with-eureka: true
    fetch-registry: false
    service-url:
      defaultZone: http://localhost:9001/eureka/

四、启动Eureka、Client,浏览器访问http://localhost:9001

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!