Spring Cloud Eureka服务注册与发现

  • 建一个Eureka 单Server
  • 建一个普通服务并注册
  • Spring Cloud版本问题

Eureka 单Server

主要代码如下:


@SpringBootApplication
@EnableEurekaServer
public class MyApplication {

    
    public static void main(String[] args) {

      SpringApplication.run(MyApplication.class, args);
    }

}

yml文件定义
application.yml注意作为server就要关闭自我注册功能;

server:
  port: 1111

eureka:
  instance:
    hostname: localhost
  client:
    registerWithEureka: false
    fetchRegistry: false
    serviceUrl:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

普通服务注册到该Server

注意使用@EnableEurekaClient


@SpringBootApplication
@EnableEurekaClient    
public class PlusApplication {

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

}

yml文件定义

server:
  port: 2222

spring:
  application:
    name: plus-service

eureka:
  instance:
    hostname: localhost
  client:
#    registerWithEureka: false
#    fetchRegistry: false
    serviceUrl:
      defaultZone: http://${eureka.instance.hostname}:1111/eureka/

注意,这里端口要错开,本地同一台机器跑的话,另外开其注册,并设置服务地址的端口是前面新建的Eureka服务器1111

Spring Cloud版本问题

本案例参考翟永超的文章Spring Cloud构建微服务架构(一)服务注册与发现
http://blog.didispace.com/springcloud1/

但其源码跑起来会报错,故改为Camden.SR6

<dependencyManagement>
    <dependencies>
        <dependency>
        <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
                <version>Camden.SR6</version>
            <type>pom</type>
            <scope>import</scope>
            <exclusions> <exclusion></exclusion></exclusions>
    </dependency>
    </dependencies>
</dependencyManagement>

本案例已验证可以跑起来,入门的童鞋可以尝试跑下。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容